2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
27 my %verbose_messages = ();
28 my %verbose_emitted = ();
49 my $gitroot = $ENV{'GIT_DIR'};
50 $gitroot = ".git" if !defined($gitroot);
58 my $configuration_file = ".checkpatch.conf";
59 my $max_line_length = 100;
60 my $ignore_perl_version = 0;
61 my $minimum_perl_version = 5.10.0;
62 my $min_conf_desc_length = 4;
63 my $spelling_file = "$D/spelling.txt";
65 my $codespellfile = "/usr/share/codespell/dictionary.txt";
66 my $conststructsfile = "$D/const_structs.checkpatch";
67 my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
70 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
71 # git output parsing needs US English output, so first set backtick child process LANGUAGE
72 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
74 my ${CONFIG_} = "CONFIG_";
80 Usage: $P [OPTION]... [FILE]...
85 -v, --verbose verbose mode
86 --no-tree run without a kernel tree
87 --no-signoff do not check for 'Signed-off-by' line
88 --patch treat FILE as patchfile (default)
89 --emacs emacs compile window format
90 --terse one line per report
91 --showfile emit diffed file position, not input file position
92 -g, --git treat FILE as a single commit or git revision range
93 single git commit with:
97 multiple git commits with:
101 git merges are ignored
102 -f, --file treat FILE as regular source file
103 --subjective, --strict enable more subjective tests
104 --list-types list the possible message types
105 --types TYPE(,TYPE2...) show only these comma separated message types
106 --ignore TYPE(,TYPE2...) ignore various comma separated message types
107 --show-types show the specific message type in the output
108 --max-line-length=n set the maximum line length, (default $max_line_length)
109 if exceeded, warn on patches
110 requires --strict for use with --file
111 --min-conf-desc-length=n set the min description length, if shorter, warn
112 --tab-size=n set the number of spaces for tab (default $tabsize)
113 --root=PATH PATH to the kernel tree root
114 --no-summary suppress the per-file summary
115 --mailback only produce a report in case of warnings/errors
116 --summary-file include the filename in summary
117 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
118 'values', 'possible', 'type', and 'attr' (default
120 --test-only=WORD report only warnings/errors containing WORD
122 --fix EXPERIMENTAL - may create horrible results
123 If correctable single-line errors exist, create
124 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
125 with potential errors corrected to the preferred
127 --fix-inplace EXPERIMENTAL - may create horrible results
128 Is the same as --fix, but overwrites the input
129 file. It's your fault if there's no backup or git
130 --ignore-perl-version override checking of perl version. expect
132 --codespell Use the codespell dictionary for spelling/typos
133 (default:/usr/share/codespell/dictionary.txt)
134 --codespellfile Use this codespell dictionary
135 --typedefsfile Read additional types from this file
136 --color[=WHEN] Use colors 'always', 'never', or only when output
137 is a terminal ('auto'). Default is 'auto'.
138 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
140 -h, --help, --version display this help and exit
142 When FILE is - read standard input.
150 return grep { !$seen{$_}++ } @_;
160 open(my $script, '<', abs_path($P)) or
161 die "$P: Can't read '$P' $!\n";
163 my $text = <$script>;
167 # Also catch when type or level is passed through a variable
168 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
170 if (exists($types{$2})) {
171 $types{$2} .= ",$1" if ($types{$2} ne $1);
176 $types{$2} = "UNDETERMINED";
180 print("#\tMessage type\n\n");
182 print(" ( Color coding: ");
183 print(RED . "ERROR" . RESET);
185 print(YELLOW . "WARNING" . RESET);
187 print(GREEN . "CHECK" . RESET);
189 print("Multiple levels / Undetermined");
193 foreach my $type (sort keys %types) {
194 my $orig_type = $type;
196 my $level = $types{$type};
197 if ($level eq "ERROR") {
198 $type = RED . $type . RESET;
199 } elsif ($level eq "WARN") {
200 $type = YELLOW . $type . RESET;
201 } elsif ($level eq "CHK") {
202 $type = GREEN . $type . RESET;
205 print(++$count . "\t" . $type . "\n");
206 if ($verbose && exists($verbose_messages{$orig_type})) {
207 my $message = $verbose_messages{$orig_type};
208 $message =~ s/\n/\n\t/g;
209 print("\t" . $message . "\n\n");
216 my $conf = which_conf($configuration_file);
219 open(my $conffile, '<', "$conf")
220 or warn "$P: Can't find a readable $configuration_file file $!\n";
222 while (<$conffile>) {
225 $line =~ s/\s*\n?$//g;
229 next if ($line =~ m/^\s*#/);
230 next if ($line =~ m/^\s*$/);
232 my @words = split(" ", $line);
233 foreach my $word (@words) {
234 last if ($word =~ m/^#/);
235 push (@conf_args, $word);
239 unshift(@ARGV, @conf_args) if @conf_args;
243 open(my $docs, '<', "$docsfile")
244 or warn "$P: Can't read the documentation file $docsfile $!\n";
255 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
257 $verbose_messages{$type} = trim($desc);
263 if ($line =~ /^(?:\s{4,}|$)/) {
268 $verbose_messages{$type} = trim($desc);
277 $verbose_messages{$type} = trim($desc);
282 # Perl's Getopt::Long allows options to take optional arguments after a space.
283 # Prevent --color by itself from consuming other arguments
285 if ($_ eq "--color" || $_ eq "-color") {
286 $_ = "--color=$color";
291 'q|quiet+' => \$quiet,
292 'v|verbose!' => \$verbose,
294 'signoff!' => \$chk_signoff,
295 'patch!' => \$chk_patch,
298 'showfile!' => \$showfile,
301 'subjective!' => \$check,
302 'strict!' => \$check,
303 'ignore=s' => \@ignore,
305 'show-types!' => \$show_types,
306 'list-types!' => \$list_types,
307 'max-line-length=i' => \$max_line_length,
308 'min-conf-desc-length=i' => \$min_conf_desc_length,
309 'tab-size=i' => \$tabsize,
311 'summary!' => \$summary,
312 'mailback!' => \$mailback,
313 'summary-file!' => \$summary_file,
315 'fix-inplace!' => \$fix_inplace,
316 'ignore-perl-version!' => \$ignore_perl_version,
317 'debug=s' => \%debug,
318 'test-only=s' => \$tst_only,
319 'codespell!' => \$codespell,
320 'codespellfile=s' => \$codespellfile,
321 'typedefsfile=s' => \$typedefsfile,
322 'color=s' => \$color,
323 'no-color' => \$color, #keep old behaviors of -nocolor
324 'nocolor' => \$color, #keep old behaviors of -nocolor
325 'kconfig-prefix=s' => \${CONFIG_},
332 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
333 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
335 if ($color =~ /^[01]$/) {
337 } elsif ($color =~ /^always$/i) {
339 } elsif ($color =~ /^never$/i) {
341 } elsif ($color =~ /^auto$/i) {
342 $color = (-t STDOUT);
344 die "$P: Invalid color mode: $color\n";
347 load_docs() if ($verbose);
348 list_types(0) if ($list_types);
350 $fix = 1 if ($fix_inplace);
351 $check_orig = $check;
355 my $perl_version_ok = 1;
356 if ($^V && $^V lt $minimum_perl_version) {
357 $perl_version_ok = 0;
358 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
359 exit(1) if (!$ignore_perl_version);
362 #if no filenames are given, push '-' to read patch from stdin
367 # skip TAB size 1 to avoid additional checks on $tabsize - 1
368 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
370 sub hash_save_array_words {
371 my ($hashRef, $arrayRef) = @_;
373 my @array = split(/,/, join(',', @$arrayRef));
374 foreach my $word (@array) {
375 $word =~ s/\s*\n?$//g;
378 $word =~ tr/[a-z]/[A-Z]/;
380 next if ($word =~ m/^\s*#/);
381 next if ($word =~ m/^\s*$/);
387 sub hash_show_words {
388 my ($hashRef, $prefix) = @_;
390 if (keys %$hashRef) {
391 print "\nNOTE: $prefix message types:";
392 foreach my $word (sort keys %$hashRef) {
399 hash_save_array_words(\%ignore_type, \@ignore);
400 hash_save_array_words(\%use_type, \@use);
403 my $dbg_possible = 0;
406 for my $key (keys %debug) {
408 eval "\${dbg_$key} = '$debug{$key}';";
412 my $rpt_cleaners = 0;
421 if (!top_of_kernel_tree($root)) {
422 die "$P: $root: --root does not point at a valid tree\n";
425 if (top_of_kernel_tree('.')) {
427 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
428 top_of_kernel_tree($1)) {
433 if (!defined $root) {
434 print "Must be run from the top-level dir. of a kernel tree\n";
439 my $emitted_corrupt = 0;
442 [A-Za-z_][A-Za-z\d_]*
443 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
445 our $Storage = qr{extern|static|asmlinkage};
459 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
460 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
461 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
462 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
463 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
465 # Notes to $Attribute:
466 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
489 ____cacheline_aligned|
490 ____cacheline_aligned_in_smp|
491 ____cacheline_internodealigned_in_smp|
495 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
496 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
497 our $Lval = qr{$Ident(?:$Member)*};
499 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
500 our $Binary = qr{(?i)0b[01]+$Int_type?};
501 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
502 our $Int = qr{[0-9]+$Int_type?};
503 our $Octal = qr{0[0-7]+$Int_type?};
504 our $String = qr{(?:\b[Lu])?"[X\t]*"};
505 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
506 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
507 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
508 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
509 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
510 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
511 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
512 our $Arithmetic = qr{\+|-|\*|\/|%};
516 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
519 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
523 our $NonptrTypeMisordered;
524 our $NonptrTypeWithAttr;
528 our $DeclareMisordered;
530 our $NON_ASCII_UTF8 = qr{
531 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
532 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
533 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
534 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
535 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
536 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
537 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
541 [\x09\x0A\x0D\x20-\x7E] # ASCII
545 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
546 our $typeOtherOSTypedefs = qr{(?x:
547 u_(?:char|short|int|long) | # bsd
548 u(?:nchar|short|int|long) # sysv
550 our $typeKernelTypedefs = qr{(?x:
551 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
554 our $typeTypedefs = qr{(?x:
556 $typeOtherOSTypedefs\b|
557 $typeKernelTypedefs\b
560 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
562 our $logFunctions = qr{(?x:
563 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
564 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
566 WARN(?:_RATELIMIT|_ONCE|)|
569 seq_vprintf|seq_printf|seq_puts
572 our $allocFunctions = qr{(?x:
574 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
577 (?:\w+)?alloc_skb(?:_ip_align)? |
578 # dev_alloc_skb/netdev_alloc_skb, et al
582 our $signature_tags = qr{(?xi:
594 our $tracing_logging_tags = qr{(?xi:
618 sub edit_distance_min {
620 my $len = scalar @arr;
621 if ((scalar @arr) < 1) {
622 # if underflow, return
626 for my $i (0 .. ($len-1)) {
627 if ($arr[$i] < $min) {
634 sub get_edit_distance {
635 my ($str1, $str2) = @_;
640 my $len1 = length($str1);
641 my $len2 = length($str2);
642 # two dimensional array storing minimum edit distance
644 for my $i (0 .. $len1) {
645 for my $j (0 .. $len2) {
647 $distance[$i][$j] = $j;
649 $distance[$i][$j] = $i;
650 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
651 $distance[$i][$j] = $distance[$i - 1][$j - 1];
653 my $dist1 = $distance[$i][$j - 1]; #insert distance
654 my $dist2 = $distance[$i - 1][$j]; # remove
655 my $dist3 = $distance[$i - 1][$j - 1]; #replace
656 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
660 return $distance[$len1][$len2];
663 sub find_standard_signature {
665 my @standard_signature_tags = (
666 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
667 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
669 foreach my $signature (@standard_signature_tags) {
670 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
676 our @typeListMisordered = (
677 qr{char\s+(?:un)?signed},
678 qr{int\s+(?:(?:un)?signed\s+)?short\s},
679 qr{int\s+short(?:\s+(?:un)?signed)},
680 qr{short\s+int(?:\s+(?:un)?signed)},
681 qr{(?:un)?signed\s+int\s+short},
682 qr{short\s+(?:un)?signed},
683 qr{long\s+int\s+(?:un)?signed},
684 qr{int\s+long\s+(?:un)?signed},
685 qr{long\s+(?:un)?signed\s+int},
686 qr{int\s+(?:un)?signed\s+long},
687 qr{int\s+(?:un)?signed},
688 qr{int\s+long\s+long\s+(?:un)?signed},
689 qr{long\s+long\s+int\s+(?:un)?signed},
690 qr{long\s+long\s+(?:un)?signed\s+int},
691 qr{long\s+long\s+(?:un)?signed},
692 qr{long\s+(?:un)?signed},
697 qr{(?:(?:un)?signed\s+)?char},
698 qr{(?:(?:un)?signed\s+)?short\s+int},
699 qr{(?:(?:un)?signed\s+)?short},
700 qr{(?:(?:un)?signed\s+)?int},
701 qr{(?:(?:un)?signed\s+)?long\s+int},
702 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
703 qr{(?:(?:un)?signed\s+)?long\s+long},
704 qr{(?:(?:un)?signed\s+)?long},
713 qr{${Ident}_handler},
714 qr{${Ident}_handler_fn},
718 our $C90_int_types = qr{(?x:
719 long\s+long\s+int\s+(?:un)?signed|
720 long\s+long\s+(?:un)?signed\s+int|
721 long\s+long\s+(?:un)?signed|
722 (?:(?:un)?signed\s+)?long\s+long\s+int|
723 (?:(?:un)?signed\s+)?long\s+long|
724 int\s+long\s+long\s+(?:un)?signed|
725 int\s+(?:(?:un)?signed\s+)?long\s+long|
727 long\s+int\s+(?:un)?signed|
728 long\s+(?:un)?signed\s+int|
729 long\s+(?:un)?signed|
730 (?:(?:un)?signed\s+)?long\s+int|
731 (?:(?:un)?signed\s+)?long|
732 int\s+long\s+(?:un)?signed|
733 int\s+(?:(?:un)?signed\s+)?long|
736 (?:(?:un)?signed\s+)?int
739 our @typeListFile = ();
740 our @typeListWithAttr = (
742 qr{struct\s+$InitAttribute\s+$Ident},
743 qr{union\s+$InitAttribute\s+$Ident},
746 our @modifierList = (
749 our @modifierListFile = ();
751 our @mode_permission_funcs = (
753 ["module_param_(?:array|named|string)", 4],
754 ["module_param_array_named", 5],
755 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
756 ["proc_create(?:_data|)", 2],
757 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
758 ["IIO_DEV_ATTR_[A-Z_]+", 1],
759 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
760 ["SENSOR_TEMPLATE(?:_2|)", 3],
764 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
766 #Create a search pattern for all these functions to speed up a loop below
767 our $mode_perms_search = "";
768 foreach my $entry (@mode_permission_funcs) {
769 $mode_perms_search .= '|' if ($mode_perms_search ne "");
770 $mode_perms_search .= $entry->[0];
772 $mode_perms_search = "(?:${mode_perms_search})";
774 our %deprecated_apis = (
775 "synchronize_rcu_bh" => "synchronize_rcu",
776 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
777 "call_rcu_bh" => "call_rcu",
778 "rcu_barrier_bh" => "rcu_barrier",
779 "synchronize_sched" => "synchronize_rcu",
780 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
781 "call_rcu_sched" => "call_rcu",
782 "rcu_barrier_sched" => "rcu_barrier",
783 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
784 "cond_synchronize_sched" => "cond_synchronize_rcu",
787 #Create a search pattern for all these strings to speed up a loop below
788 our $deprecated_apis_search = "";
789 foreach my $entry (keys %deprecated_apis) {
790 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
791 $deprecated_apis_search .= $entry;
793 $deprecated_apis_search = "(?:${deprecated_apis_search})";
795 our $mode_perms_world_writable = qr{
803 our %mode_permission_string_types = (
822 #Create a search pattern for all these strings to speed up a loop below
823 our $mode_perms_string_search = "";
824 foreach my $entry (keys %mode_permission_string_types) {
825 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
826 $mode_perms_string_search .= $entry;
828 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
829 our $multi_mode_perms_string_search = qr{
830 ${single_mode_perms_string_search}
831 (?:\s*\|\s*${single_mode_perms_string_search})*
837 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
844 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
845 $curpos = pos($string);
848 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
850 $to |= $mode_permission_string_types{$match};
851 $val .= '\s*\|\s*' if ($val ne "");
855 $oval =~ s/^\s*\|\s*//;
856 $oval =~ s/\s*\|\s*$//;
857 return sprintf("%04o", $to);
860 our $allowed_asm_includes = qr{(?x:
866 # memory.h: ARM has a custom one
868 # Load common spelling mistakes and build regular expression list.
872 if (open(my $spelling, '<', $spelling_file)) {
873 while (<$spelling>) {
876 $line =~ s/\s*\n?$//g;
879 next if ($line =~ m/^\s*#/);
880 next if ($line =~ m/^\s*$/);
882 my ($suspect, $fix) = split(/\|\|/, $line);
884 $spelling_fix{$suspect} = $fix;
888 warn "No typos will be found - file '$spelling_file': $!\n";
892 if (open(my $spelling, '<', $codespellfile)) {
893 while (<$spelling>) {
896 $line =~ s/\s*\n?$//g;
899 next if ($line =~ m/^\s*#/);
900 next if ($line =~ m/^\s*$/);
901 next if ($line =~ m/, disabled/i);
905 my ($suspect, $fix) = split(/->/, $line);
907 $spelling_fix{$suspect} = $fix;
911 warn "No codespell typos will be found - file '$codespellfile': $!\n";
915 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
918 my ($wordsRef, $file) = @_;
920 if (open(my $words, '<', $file)) {
924 $line =~ s/\s*\n?$//g;
927 next if ($line =~ m/^\s*#/);
928 next if ($line =~ m/^\s*$/);
930 print("$file: '$line' invalid - ignored\n");
934 $$wordsRef .= '|' if (defined $$wordsRef);
945 if (show_type("CONST_STRUCT")) {
946 read_words(\$const_structs, $conststructsfile)
947 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
950 if (defined($typedefsfile)) {
951 my $typeOtherTypedefs;
952 read_words(\$typeOtherTypedefs, $typedefsfile)
953 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
954 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
958 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
959 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
960 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
961 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
962 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
968 (?:$Modifier\s+|const\s+)*
970 (?:typeof|__typeof__)\s*\([^\)]*\)|
974 (?:\s+$Modifier|\s+const)*
976 $NonptrTypeMisordered = qr{
977 (?:$Modifier\s+|const\s+)*
981 (?:\s+$Modifier|\s+const)*
983 $NonptrTypeWithAttr = qr{
984 (?:$Modifier\s+|const\s+)*
986 (?:typeof|__typeof__)\s*\([^\)]*\)|
990 (?:\s+$Modifier|\s+const)*
994 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
995 (?:\s+$Inline|\s+$Modifier)*
997 $TypeMisordered = qr{
998 $NonptrTypeMisordered
999 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1000 (?:\s+$Inline|\s+$Modifier)*
1002 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1003 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1007 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1009 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1010 # requires at least perl version v5.10.0
1011 # Any use must be runtime checked with $^V
1013 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1014 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1015 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1017 our $declaration_macros = qr{(?x:
1018 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1019 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1020 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
1023 our %allow_repeated_words = (
1030 sub deparenthesize {
1032 return "" if (!defined($string));
1034 while ($string =~ /^\s*\(.*\)\s*$/) {
1035 $string =~ s@^\s*\(\s*@@;
1036 $string =~ s@\s*\)\s*$@@;
1039 $string =~ s@\s+@ @g;
1044 sub seed_camelcase_file {
1047 return if (!(-f $file));
1051 open(my $include_file, '<', "$file")
1052 or warn "$P: Can't read '$file' $!\n";
1053 my $text = <$include_file>;
1054 close($include_file);
1056 my @lines = split('\n', $text);
1058 foreach my $line (@lines) {
1059 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1060 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1062 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1064 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1070 our %maintained_status = ();
1072 sub is_maintained_obsolete {
1073 my ($filename) = @_;
1075 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1077 if (!exists($maintained_status{$filename})) {
1078 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1081 return $maintained_status{$filename} =~ /obsolete/i;
1084 sub is_SPDX_License_valid {
1087 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1089 my $root_path = abs_path($root);
1090 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1091 return 0 if ($status ne "");
1095 my $camelcase_seeded = 0;
1096 sub seed_camelcase_includes {
1097 return if ($camelcase_seeded);
1100 my $camelcase_cache = "";
1101 my @include_files = ();
1103 $camelcase_seeded = 1;
1105 if (-e "$gitroot") {
1106 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1107 chomp $git_last_include_commit;
1108 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1110 my $last_mod_date = 0;
1111 $files = `find $root/include -name "*.h"`;
1112 @include_files = split('\n', $files);
1113 foreach my $file (@include_files) {
1114 my $date = POSIX::strftime("%Y%m%d%H%M",
1115 localtime((stat $file)[9]));
1116 $last_mod_date = $date if ($last_mod_date < $date);
1118 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1121 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1122 open(my $camelcase_file, '<', "$camelcase_cache")
1123 or warn "$P: Can't read '$camelcase_cache' $!\n";
1124 while (<$camelcase_file>) {
1128 close($camelcase_file);
1133 if (-e "$gitroot") {
1134 $files = `${git_command} ls-files "include/*.h"`;
1135 @include_files = split('\n', $files);
1138 foreach my $file (@include_files) {
1139 seed_camelcase_file($file);
1142 if ($camelcase_cache ne "") {
1143 unlink glob ".checkpatch-camelcase.*";
1144 open(my $camelcase_file, '>', "$camelcase_cache")
1145 or warn "$P: Can't write '$camelcase_cache' $!\n";
1146 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1147 print $camelcase_file ("$_\n");
1149 close($camelcase_file);
1153 sub git_is_single_file {
1154 my ($filename) = @_;
1156 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1158 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1159 my $count = $output =~ tr/\n//;
1160 return $count eq 1 && $output =~ m{^${filename}$};
1163 sub git_commit_info {
1164 my ($commit, $id, $desc) = @_;
1166 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1168 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1169 $output =~ s/^\s*//gm;
1170 my @lines = split("\n", $output);
1172 return ($id, $desc) if ($#lines < 0);
1174 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1175 # Maybe one day convert this block of bash into something that returns
1176 # all matching commit ids, but it's very slow...
1178 # echo "checking commits $1..."
1179 # git rev-list --remotes | grep -i "^$1" |
1180 # while read line ; do
1181 # git log --format='%H %s' -1 $line |
1182 # echo "commit $(cut -c 1-12,41-)"
1184 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1185 $lines[0] =~ /^fatal: bad object $commit/) {
1188 $id = substr($lines[0], 0, 12);
1189 $desc = substr($lines[0], 41);
1192 return ($id, $desc);
1195 $chk_signoff = 0 if ($file);
1200 my @fixed_inserted = ();
1201 my @fixed_deleted = ();
1204 # If input is git commits, extract all commits from the commit expressions.
1205 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1206 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1210 foreach my $commit_expr (@ARGV) {
1212 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1213 $git_range = "-$2 $1";
1214 } elsif ($commit_expr =~ m/\.\./) {
1215 $git_range = "$commit_expr";
1217 $git_range = "-1 $commit_expr";
1219 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1220 foreach my $line (split(/\n/, $lines)) {
1221 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1222 next if (!defined($1) || !defined($2));
1225 unshift(@commits, $sha1);
1226 $git_commits{$sha1} = $subject;
1229 die "$P: no git commits after extraction!\n" if (@commits == 0);
1234 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1235 for my $filename (@ARGV) {
1237 my $is_git_file = git_is_single_file($filename);
1238 my $oldfile = $file;
1239 $file = 1 if ($is_git_file);
1241 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1242 die "$P: $filename: git format-patch failed - $!\n";
1244 open($FILE, '-|', "diff -u /dev/null $filename") ||
1245 die "$P: $filename: diff failed - $!\n";
1246 } elsif ($filename eq '-') {
1247 open($FILE, '<&STDIN');
1249 open($FILE, '<', "$filename") ||
1250 die "$P: $filename: open failed - $!\n";
1252 if ($filename eq '-') {
1253 $vname = 'Your patch';
1255 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1261 push(@rawlines, $_);
1262 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1266 if ($#ARGV > 0 && $quiet == 0) {
1267 print '-' x length($vname) . "\n";
1269 print '-' x length($vname) . "\n";
1272 if (!process($filename)) {
1278 @fixed_inserted = ();
1279 @fixed_deleted = ();
1281 @modifierListFile = ();
1284 $file = $oldfile if ($is_git_file);
1288 hash_show_words(\%use_type, "Used");
1289 hash_show_words(\%ignore_type, "Ignored");
1291 if (!$perl_version_ok) {
1294 NOTE: perl $^V is not modern enough to detect all possible issues.
1295 An upgrade to at least perl $minimum_perl_version is suggested.
1301 NOTE: If any of the errors are false positives, please report
1302 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1309 sub top_of_kernel_tree {
1313 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1314 "README", "Documentation", "arch", "include", "drivers",
1315 "fs", "init", "ipc", "kernel", "lib", "scripts",
1318 foreach my $check (@tree_check) {
1319 if (! -e $root . '/' . $check) {
1327 my ($formatted_email) = @_;
1331 my $name_comment = "";
1335 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1338 $comment = $3 if defined $3;
1339 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1341 $comment = $2 if defined $2;
1342 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1344 $comment = $2 if defined $2;
1345 $formatted_email =~ s/\Q$address\E.*$//;
1346 $name = $formatted_email;
1347 $name = trim($name);
1348 $name =~ s/^\"|\"$//g;
1349 # If there's a name left after stripping spaces and
1350 # leading quotes, and the address doesn't have both
1351 # leading and trailing angle brackets, the address
1353 # "joe smith joe@smith.com" bad
1354 # "joe smith <joe@smith.com" bad
1355 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1362 # Extract comments from names excluding quoted parts
1363 # "John D. (Doe)" - Do not extract
1364 if ($name =~ s/\"(.+)\"//) {
1367 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1368 $name_comment .= trim($1);
1370 $name =~ s/^[ \"]+|[ \"]+$//g;
1371 $name = trim("$quoted $name");
1373 $address = trim($address);
1374 $address =~ s/^\<|\>$//g;
1375 $comment = trim($comment);
1377 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1378 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1379 $name = "\"$name\"";
1382 return ($name, $name_comment, $address, $comment);
1386 my ($name, $name_comment, $address, $comment) = @_;
1388 my $formatted_email;
1390 $name =~ s/^[ \"]+|[ \"]+$//g;
1391 $address = trim($address);
1392 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1394 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1395 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1396 $name = "\"$name\"";
1399 $name_comment = trim($name_comment);
1400 $name_comment = " $name_comment" if ($name_comment ne "");
1401 $comment = trim($comment);
1402 $comment = " $comment" if ($comment ne "");
1404 if ("$name" eq "") {
1405 $formatted_email = "$address";
1407 $formatted_email = "$name$name_comment <$address>";
1409 $formatted_email .= "$comment";
1410 return $formatted_email;
1413 sub reformat_email {
1416 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1417 return format_email($email_name, $name_comment, $email_address, $comment);
1420 sub same_email_addresses {
1421 my ($email1, $email2) = @_;
1423 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1424 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1426 return $email1_name eq $email2_name &&
1427 $email1_address eq $email2_address &&
1428 $name1_comment eq $name2_comment &&
1429 $comment1 eq $comment2;
1435 foreach my $path (split(/:/, $ENV{PATH})) {
1436 if (-e "$path/$bin") {
1437 return "$path/$bin";
1447 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1448 if (-e "$path/$conf") {
1449 return "$path/$conf";
1461 for my $c (split(//, $str)) {
1465 for (; ($n % $tabsize) != 0; $n++) {
1477 (my $res = shift) =~ tr/\t/ /c;
1484 # Drop the diff line leader and expand tabs
1486 $line = expand_tabs($line);
1488 # Pick the indent from the front of the line.
1489 my ($white) = ($line =~ /^(\s*)/);
1491 return (length($line), length($white));
1494 my $sanitise_quote = '';
1496 sub sanitise_line_reset {
1497 my ($in_comment) = @_;
1500 $sanitise_quote = '*/';
1502 $sanitise_quote = '';
1515 # Always copy over the diff marker.
1516 $res = substr($line, 0, 1);
1518 for ($off = 1; $off < length($line); $off++) {
1519 $c = substr($line, $off, 1);
1521 # Comments we are whacking completely including the begin
1522 # and end, all to $;.
1523 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1524 $sanitise_quote = '*/';
1526 substr($res, $off, 2, "$;$;");
1530 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1531 $sanitise_quote = '';
1532 substr($res, $off, 2, "$;$;");
1536 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1537 $sanitise_quote = '//';
1539 substr($res, $off, 2, $sanitise_quote);
1544 # A \ in a string means ignore the next character.
1545 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1547 substr($res, $off, 2, 'XX');
1552 if ($c eq "'" || $c eq '"') {
1553 if ($sanitise_quote eq '') {
1554 $sanitise_quote = $c;
1556 substr($res, $off, 1, $c);
1558 } elsif ($sanitise_quote eq $c) {
1559 $sanitise_quote = '';
1563 #print "c<$c> SQ<$sanitise_quote>\n";
1564 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1565 substr($res, $off, 1, $;);
1566 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1567 substr($res, $off, 1, $;);
1568 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1569 substr($res, $off, 1, 'X');
1571 substr($res, $off, 1, $c);
1575 if ($sanitise_quote eq '//') {
1576 $sanitise_quote = '';
1579 # The pathname on a #include may be surrounded by '<' and '>'.
1580 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1581 my $clean = 'X' x length($1);
1582 $res =~ s@\<.*\>@<$clean>@;
1584 # The whole of a #error is a string.
1585 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1586 my $clean = 'X' x length($1);
1587 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1590 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1592 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1598 sub get_quoted_string {
1599 my ($line, $rawline) = @_;
1601 return "" if (!defined($line) || !defined($rawline));
1602 return "" if ($line !~ m/($String)/g);
1603 return substr($rawline, $-[0], $+[0] - $-[0]);
1606 sub ctx_statement_block {
1607 my ($linenr, $remain, $off) = @_;
1608 my $line = $linenr - 1;
1611 my $coff = $off - 1;
1625 @stack = (['', 0]) if ($#stack == -1);
1627 #warn "CSB: blk<$blk> remain<$remain>\n";
1628 # If we are about to drop off the end, pull in more
1631 for (; $remain > 0; $line++) {
1632 last if (!defined $lines[$line]);
1633 next if ($lines[$line] =~ /^-/);
1636 $blk .= $lines[$line] . "\n";
1637 $len = length($blk);
1641 # Bail if there is no further context.
1642 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1646 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1652 $c = substr($blk, $off, 1);
1653 $remainder = substr($blk, $off);
1655 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1657 # Handle nested #if/#else.
1658 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1659 push(@stack, [ $type, $level ]);
1660 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1661 ($type, $level) = @{$stack[$#stack - 1]};
1662 } elsif ($remainder =~ /^#\s*endif\b/) {
1663 ($type, $level) = @{pop(@stack)};
1666 # Statement ends at the ';' or a close '}' at the
1668 if ($level == 0 && $c eq ';') {
1672 # An else is really a conditional as long as its not else if
1673 if ($level == 0 && $coff_set == 0 &&
1674 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1675 $remainder =~ /^(else)(?:\s|{)/ &&
1676 $remainder !~ /^else\s+if\b/) {
1677 $coff = $off + length($1) - 1;
1679 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1680 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1683 if (($type eq '' || $type eq '(') && $c eq '(') {
1687 if ($type eq '(' && $c eq ')') {
1689 $type = ($level != 0)? '(' : '';
1691 if ($level == 0 && $coff < $soff) {
1694 #warn "CSB: mark coff<$coff>\n";
1697 if (($type eq '' || $type eq '{') && $c eq '{') {
1701 if ($type eq '{' && $c eq '}') {
1703 $type = ($level != 0)? '{' : '';
1706 if (substr($blk, $off + 1, 1) eq ';') {
1712 # Preprocessor commands end at the newline unless escaped.
1713 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1721 # We are truly at the end, so shuffle to the next line.
1728 my $statement = substr($blk, $soff, $off - $soff + 1);
1729 my $condition = substr($blk, $soff, $coff - $soff + 1);
1731 #warn "STATEMENT<$statement>\n";
1732 #warn "CONDITION<$condition>\n";
1734 #print "coff<$coff> soff<$off> loff<$loff>\n";
1736 return ($statement, $condition,
1737 $line, $remain + 1, $off - $loff + 1, $level);
1740 sub statement_lines {
1743 # Strip the diff line prefixes and rip blank lines at start and end.
1744 $stmt =~ s/(^|\n)./$1/g;
1748 my @stmt_lines = ($stmt =~ /\n/g);
1750 return $#stmt_lines + 2;
1753 sub statement_rawlines {
1756 my @stmt_lines = ($stmt =~ /\n/g);
1758 return $#stmt_lines + 2;
1761 sub statement_block_size {
1764 $stmt =~ s/(^|\n)./$1/g;
1770 my @stmt_lines = ($stmt =~ /\n/g);
1771 my @stmt_statements = ($stmt =~ /;/g);
1773 my $stmt_lines = $#stmt_lines + 2;
1774 my $stmt_statements = $#stmt_statements + 1;
1776 if ($stmt_lines > $stmt_statements) {
1779 return $stmt_statements;
1783 sub ctx_statement_full {
1784 my ($linenr, $remain, $off) = @_;
1785 my ($statement, $condition, $level);
1789 # Grab the first conditional/block pair.
1790 ($statement, $condition, $linenr, $remain, $off, $level) =
1791 ctx_statement_block($linenr, $remain, $off);
1792 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1793 push(@chunks, [ $condition, $statement ]);
1794 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1795 return ($level, $linenr, @chunks);
1798 # Pull in the following conditional/block pairs and see if they
1799 # could continue the statement.
1801 ($statement, $condition, $linenr, $remain, $off, $level) =
1802 ctx_statement_block($linenr, $remain, $off);
1803 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1804 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1806 push(@chunks, [ $condition, $statement ]);
1809 return ($level, $linenr, @chunks);
1813 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1815 my $start = $linenr - 1;
1822 my @stack = ($level);
1823 for ($line = $start; $remain > 0; $line++) {
1824 next if ($rawlines[$line] =~ /^-/);
1827 $blk .= $rawlines[$line];
1829 # Handle nested #if/#else.
1830 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1831 push(@stack, $level);
1832 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1833 $level = $stack[$#stack - 1];
1834 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1835 $level = pop(@stack);
1838 foreach my $c (split(//, $lines[$line])) {
1839 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1845 if ($c eq $close && $level > 0) {
1847 last if ($level == 0);
1848 } elsif ($c eq $open) {
1853 if (!$outer || $level <= 1) {
1854 push(@res, $rawlines[$line]);
1857 last if ($level == 0);
1860 return ($level, @res);
1862 sub ctx_block_outer {
1863 my ($linenr, $remain) = @_;
1865 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1869 my ($linenr, $remain) = @_;
1871 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1875 my ($linenr, $remain, $off) = @_;
1877 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1880 sub ctx_block_level {
1881 my ($linenr, $remain) = @_;
1883 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1885 sub ctx_statement_level {
1886 my ($linenr, $remain, $off) = @_;
1888 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1891 sub ctx_locate_comment {
1892 my ($first_line, $end_line) = @_;
1894 # If c99 comment on the current line, or the line before or after
1895 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1896 return $current_comment if (defined $current_comment);
1897 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1898 return $current_comment if (defined $current_comment);
1899 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1900 return $current_comment if (defined $current_comment);
1902 # Catch a comment on the end of the line itself.
1903 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1904 return $current_comment if (defined $current_comment);
1906 # Look through the context and try and figure out if there is a
1909 $current_comment = '';
1910 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1911 my $line = $rawlines[$linenr - 1];
1913 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1916 if ($line =~ m@/\*@) {
1919 if (!$in_comment && $current_comment ne '') {
1920 $current_comment = '';
1922 $current_comment .= $line . "\n" if ($in_comment);
1923 if ($line =~ m@\*/@) {
1928 chomp($current_comment);
1929 return($current_comment);
1931 sub ctx_has_comment {
1932 my ($first_line, $end_line) = @_;
1933 my $cmt = ctx_locate_comment($first_line, $end_line);
1935 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1936 ##print "CMMT: $cmt\n";
1938 return ($cmt ne '');
1942 my ($linenr, $cnt) = @_;
1944 my $offset = $linenr - 1;
1949 $line = $rawlines[$offset++];
1950 next if (defined($line) && $line =~ /^-/);
1958 my ($linenr, $lc) = @_;
1960 my $stat_real = raw_line($linenr, 0);
1961 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1962 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1969 my ($linenr, $cnt, $here) = @_;
1971 my $herectx = $here . "\n";
1972 for (my $n = 0; $n < $cnt; $n++) {
1973 $herectx .= raw_line($linenr, $n) . "\n";
1984 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1987 $coded = sprintf("^%c", unpack('C', $2) + 64);
1996 my $av_preprocessor = 0;
2001 sub annotate_reset {
2002 $av_preprocessor = 0;
2004 @av_paren_type = ('E');
2005 $av_pend_colon = 'O';
2008 sub annotate_values {
2009 my ($stream, $type) = @_;
2012 my $var = '_' x length($stream);
2015 print "$stream\n" if ($dbg_values > 1);
2017 while (length($cur)) {
2018 @av_paren_type = ('E') if ($#av_paren_type < 0);
2019 print " <" . join('', @av_paren_type) .
2020 "> <$type> <$av_pending>" if ($dbg_values > 1);
2021 if ($cur =~ /^(\s+)/o) {
2022 print "WS($1)\n" if ($dbg_values > 1);
2023 if ($1 =~ /\n/ && $av_preprocessor) {
2024 $type = pop(@av_paren_type);
2025 $av_preprocessor = 0;
2028 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2029 print "CAST($1)\n" if ($dbg_values > 1);
2030 push(@av_paren_type, $type);
2033 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2034 print "DECLARE($1)\n" if ($dbg_values > 1);
2037 } elsif ($cur =~ /^($Modifier)\s*/) {
2038 print "MODIFIER($1)\n" if ($dbg_values > 1);
2041 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2042 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2043 $av_preprocessor = 1;
2044 push(@av_paren_type, $type);
2050 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2051 print "UNDEF($1)\n" if ($dbg_values > 1);
2052 $av_preprocessor = 1;
2053 push(@av_paren_type, $type);
2055 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2056 print "PRE_START($1)\n" if ($dbg_values > 1);
2057 $av_preprocessor = 1;
2059 push(@av_paren_type, $type);
2060 push(@av_paren_type, $type);
2063 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2064 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2065 $av_preprocessor = 1;
2067 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2071 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2072 print "PRE_END($1)\n" if ($dbg_values > 1);
2074 $av_preprocessor = 1;
2076 # Assume all arms of the conditional end as this
2077 # one does, and continue as if the #endif was not here.
2078 pop(@av_paren_type);
2079 push(@av_paren_type, $type);
2082 } elsif ($cur =~ /^(\\\n)/o) {
2083 print "PRECONT($1)\n" if ($dbg_values > 1);
2085 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2086 print "ATTR($1)\n" if ($dbg_values > 1);
2087 $av_pending = $type;
2090 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2091 print "SIZEOF($1)\n" if ($dbg_values > 1);
2097 } elsif ($cur =~ /^(if|while|for)\b/o) {
2098 print "COND($1)\n" if ($dbg_values > 1);
2102 } elsif ($cur =~/^(case)/o) {
2103 print "CASE($1)\n" if ($dbg_values > 1);
2104 $av_pend_colon = 'C';
2107 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2108 print "KEYWORD($1)\n" if ($dbg_values > 1);
2111 } elsif ($cur =~ /^(\()/o) {
2112 print "PAREN('$1')\n" if ($dbg_values > 1);
2113 push(@av_paren_type, $av_pending);
2117 } elsif ($cur =~ /^(\))/o) {
2118 my $new_type = pop(@av_paren_type);
2119 if ($new_type ne '_') {
2121 print "PAREN('$1') -> $type\n"
2122 if ($dbg_values > 1);
2124 print "PAREN('$1')\n" if ($dbg_values > 1);
2127 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2128 print "FUNC($1)\n" if ($dbg_values > 1);
2132 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2133 if (defined $2 && $type eq 'C' || $type eq 'T') {
2134 $av_pend_colon = 'B';
2135 } elsif ($type eq 'E') {
2136 $av_pend_colon = 'L';
2138 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2141 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2142 print "IDENT($1)\n" if ($dbg_values > 1);
2145 } elsif ($cur =~ /^($Assignment)/o) {
2146 print "ASSIGN($1)\n" if ($dbg_values > 1);
2149 } elsif ($cur =~/^(;|{|})/) {
2150 print "END($1)\n" if ($dbg_values > 1);
2152 $av_pend_colon = 'O';
2154 } elsif ($cur =~/^(,)/) {
2155 print "COMMA($1)\n" if ($dbg_values > 1);
2158 } elsif ($cur =~ /^(\?)/o) {
2159 print "QUESTION($1)\n" if ($dbg_values > 1);
2162 } elsif ($cur =~ /^(:)/o) {
2163 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2165 substr($var, length($res), 1, $av_pend_colon);
2166 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2171 $av_pend_colon = 'O';
2173 } elsif ($cur =~ /^(\[)/o) {
2174 print "CLOSE($1)\n" if ($dbg_values > 1);
2177 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2180 print "OPV($1)\n" if ($dbg_values > 1);
2187 substr($var, length($res), 1, $variant);
2190 } elsif ($cur =~ /^($Operators)/o) {
2191 print "OP($1)\n" if ($dbg_values > 1);
2192 if ($1 ne '++' && $1 ne '--') {
2196 } elsif ($cur =~ /(^.)/o) {
2197 print "C($1)\n" if ($dbg_values > 1);
2200 $cur = substr($cur, length($1));
2201 $res .= $type x length($1);
2205 return ($res, $var);
2209 my ($possible, $line) = @_;
2210 my $notPermitted = qr{(?:
2227 ^(?:typedef|struct|enum)\b
2229 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2230 if ($possible !~ $notPermitted) {
2231 # Check for modifiers.
2232 $possible =~ s/\s*$Storage\s*//g;
2233 $possible =~ s/\s*$Sparse\s*//g;
2234 if ($possible =~ /^\s*$/) {
2236 } elsif ($possible =~ /\s/) {
2237 $possible =~ s/\s*$Type\s*//g;
2238 for my $modifier (split(' ', $possible)) {
2239 if ($modifier !~ $notPermitted) {
2240 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2241 push(@modifierListFile, $modifier);
2246 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2247 push(@typeListFile, $possible);
2251 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2260 $type =~ tr/[a-z]/[A-Z]/;
2262 return defined $use_type{$type} if (scalar keys %use_type > 0);
2264 return !defined $ignore_type{$type};
2268 my ($level, $type, $msg) = @_;
2270 if (!show_type($type) ||
2271 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2276 if ($level eq 'ERROR') {
2278 } elsif ($level eq 'WARNING') {
2284 $output .= $prefix . $level . ':';
2286 $output .= BLUE if ($color);
2287 $output .= "$type:";
2289 $output .= RESET if ($color);
2290 $output .= ' ' . $msg . "\n";
2293 my @lines = split("\n", $output, -1);
2294 splice(@lines, 1, 1);
2295 $output = join("\n", @lines);
2299 $output = (split('\n', $output))[0] . "\n";
2302 if ($verbose && exists($verbose_messages{$type}) &&
2303 !exists($verbose_emitted{$type})) {
2304 $output .= $verbose_messages{$type} . "\n\n";
2305 $verbose_emitted{$type} = 1;
2308 push(our @report, $output);
2317 sub fixup_current_range {
2318 my ($lineRef, $offset, $length) = @_;
2320 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2323 my $no = $o + $offset;
2324 my $nl = $l + $length;
2325 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2329 sub fix_inserted_deleted_lines {
2330 my ($linesRef, $insertedRef, $deletedRef) = @_;
2332 my $range_last_linenr = 0;
2333 my $delta_offset = 0;
2338 my $next_insert = 0;
2339 my $next_delete = 0;
2343 my $inserted = @{$insertedRef}[$next_insert++];
2344 my $deleted = @{$deletedRef}[$next_delete++];
2346 foreach my $old_line (@{$linesRef}) {
2348 my $line = $old_line; #don't modify the array
2349 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2351 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2352 $range_last_linenr = $new_linenr;
2353 fixup_current_range(\$line, $delta_offset, 0);
2356 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2357 $deleted = @{$deletedRef}[$next_delete++];
2359 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2362 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2363 push(@lines, ${$inserted}{'LINE'});
2364 $inserted = @{$insertedRef}[$next_insert++];
2366 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2370 push(@lines, $line);
2380 sub fix_insert_line {
2381 my ($linenr, $line) = @_;
2387 push(@fixed_inserted, $inserted);
2390 sub fix_delete_line {
2391 my ($linenr, $line) = @_;
2398 push(@fixed_deleted, $deleted);
2402 my ($type, $msg) = @_;
2404 if (report("ERROR", $type, $msg)) {
2412 my ($type, $msg) = @_;
2414 if (report("WARNING", $type, $msg)) {
2422 my ($type, $msg) = @_;
2424 if ($check && report("CHECK", $type, $msg)) {
2432 sub check_absolute_file {
2433 my ($absolute, $herecurr) = @_;
2434 my $file = $absolute;
2436 ##print "absolute<$absolute>\n";
2438 # See if any suffix of this path is a path within the tree.
2439 while ($file =~ s@^[^/]*/@@) {
2440 if (-f "$root/$file") {
2441 ##print "file<$file>\n";
2449 # It is, so see if the prefix is acceptable.
2450 my $prefix = $absolute;
2451 substr($prefix, -length($file)) = '';
2453 ##print "prefix<$prefix>\n";
2454 if ($prefix ne ".../") {
2455 WARN("USE_RELATIVE_PATH",
2456 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2463 $string =~ s/^\s+|\s+$//g;
2471 $string =~ s/^\s+//;
2479 $string =~ s/\s+$//;
2484 sub string_find_replace {
2485 my ($string, $find, $replace) = @_;
2487 $string =~ s/$find/$replace/g;
2495 my $source_indent = $tabsize;
2496 my $max_spaces_before_tab = $source_indent - 1;
2497 my $spaces_to_tab = " " x $source_indent;
2499 #convert leading spaces to tabs
2500 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2501 #Remove spaces before a tab
2502 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2507 sub pos_last_openparen {
2512 my $opens = $line =~ tr/\(/\(/;
2513 my $closes = $line =~ tr/\)/\)/;
2515 my $last_openparen = 0;
2517 if (($opens == 0) || ($closes >= $opens)) {
2521 my $len = length($line);
2523 for ($pos = 0; $pos < $len; $pos++) {
2524 my $string = substr($line, $pos);
2525 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2526 $pos += length($1) - 1;
2527 } elsif (substr($line, $pos, 1) eq '(') {
2528 $last_openparen = $pos;
2529 } elsif (index($string, '(') == -1) {
2534 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2537 sub get_raw_comment {
2538 my ($line, $rawline) = @_;
2541 for my $i (0 .. (length($line) - 1)) {
2542 if (substr($line, $i, 1) eq "$;") {
2543 $comment .= substr($rawline, $i, 1);
2550 sub exclude_global_initialisers {
2551 my ($realfile) = @_;
2553 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2554 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2555 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2556 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2560 my $filename = shift;
2566 my $stashrawline="";
2576 my $authorsignoff = 0;
2577 my $author_sob = '';
2579 my $is_binding_patch = -1;
2580 my $in_header_lines = $file ? 0 : 1;
2581 my $in_commit_log = 0; #Scanning lines before patch
2582 my $has_patch_separator = 0; #Found a --- line
2583 my $has_commit_log = 0; #Encountered lines before patch
2584 my $commit_log_lines = 0; #Number of commit log lines
2585 my $commit_log_possible_stack_dump = 0;
2586 my $commit_log_long_line = 0;
2587 my $commit_log_has_diff = 0;
2588 my $reported_maintainer_file = 0;
2589 my $non_utf8_charset = 0;
2591 my $last_git_commit_id_linenr = -1;
2593 my $last_blank_line = 0;
2594 my $last_coalesced_string_linenr = -1;
2602 # Trace the real file/line as we go.
2607 my $context_function; #undef'd unless there's a known function
2609 my $comment_edge = 0;
2613 my $prev_values = 'E';
2616 my %suppress_ifbraces;
2617 my %suppress_whiletrailers;
2618 my %suppress_export;
2619 my $suppress_statement = 0;
2621 my %signatures = ();
2623 # Pre-scan the patch sanitizing the lines.
2624 # Pre-scan the patch looking for any __setup documentation.
2626 my @setup_docs = ();
2629 my $camelcase_file_seeded = 0;
2631 my $checklicenseline = 1;
2633 sanitise_line_reset();
2635 foreach my $rawline (@rawlines) {
2639 push(@fixed, $rawline) if ($fix);
2641 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2643 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2648 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2657 # Guestimate if this is a continuing comment. Run
2658 # the context looking for a comment "edge". If this
2659 # edge is a close comment then we must be in a comment
2663 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2664 next if (defined $rawlines[$ln - 1] &&
2665 $rawlines[$ln - 1] =~ /^-/);
2667 #print "RAW<$rawlines[$ln - 1]>\n";
2668 last if (!defined $rawlines[$ln - 1]);
2669 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2670 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2675 if (defined $edge && $edge eq '*/') {
2679 # Guestimate if this is a continuing comment. If this
2680 # is the start of a diff block and this line starts
2681 # ' *' then it is very likely a comment.
2682 if (!defined $edge &&
2683 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2688 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2689 sanitise_line_reset($in_comment);
2691 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2692 # Standardise the strings and chars within the input to
2693 # simplify matching -- only bother with positive lines.
2694 $line = sanitise_line($rawline);
2696 push(@lines, $line);
2699 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2704 #print "==>$rawline\n";
2705 #print "-->$line\n";
2707 if ($setup_docs && $line =~ /^\+/) {
2708 push(@setup_docs, $line);
2717 foreach my $line (@lines) {
2720 my $sline = $line; #copy of $line
2721 $sline =~ s/$;/ /g; #with comments as spaces
2723 my $rawline = $rawlines[$linenr - 1];
2724 my $raw_comment = get_raw_comment($line, $rawline);
2726 # check if it's a mode change, rename or start of a patch
2727 if (!$in_commit_log &&
2728 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2729 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2730 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2734 #extract the line range in the file after the patch is applied
2735 if (!$in_commit_log &&
2736 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2739 $first_line = $linenr + 1;
2749 %suppress_ifbraces = ();
2750 %suppress_whiletrailers = ();
2751 %suppress_export = ();
2752 $suppress_statement = 0;
2753 if ($context =~ /\b(\w+)\s*\(/) {
2754 $context_function = $1;
2756 undef $context_function;
2760 # track the line number as we move through the hunk, note that
2761 # new versions of GNU diff omit the leading space on completely
2762 # blank context lines so we need to count that too.
2763 } elsif ($line =~ /^( |\+|$)/) {
2765 $realcnt-- if ($realcnt != 0);
2767 # Measure the line length and indent.
2768 ($length, $indent) = line_stats($rawline);
2770 # Track the previous line.
2771 ($prevline, $stashline) = ($stashline, $line);
2772 ($previndent, $stashindent) = ($stashindent, $indent);
2773 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2775 #warn "line<$line>\n";
2777 } elsif ($realcnt == 1) {
2781 my $hunk_line = ($realcnt != 0);
2783 $here = "#$linenr: " if (!$file);
2784 $here = "#$realline: " if ($file);
2787 # extract the filename as it passes
2788 if ($line =~ /^diff --git.*?(\S+)$/) {
2790 $realfile =~ s@^([^/]*)/@@ if (!$file);
2793 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2795 $realfile =~ s@^([^/]*)/@@ if (!$file);
2799 if (!$file && $tree && $p1_prefix ne '' &&
2800 -e "$root/$p1_prefix") {
2801 WARN("PATCH_PREFIX",
2802 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2805 if ($realfile =~ m@^include/asm/@) {
2806 ERROR("MODIFIED_INCLUDE_ASM",
2807 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2812 #make up the handle for any error we report on this line
2814 $prefix = "$realfile:$realline: "
2817 $prefix = "$filename:$realline: ";
2819 $prefix = "$filename:$linenr: ";
2824 if (is_maintained_obsolete($realfile)) {
2826 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2828 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2831 $check = $check_orig;
2833 $checklicenseline = 1;
2835 if ($realfile !~ /^MAINTAINERS/) {
2836 my $last_binding_patch = $is_binding_patch;
2838 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2840 if (($last_binding_patch != -1) &&
2841 ($last_binding_patch ^ $is_binding_patch)) {
2842 WARN("DT_SPLIT_BINDING_PATCH",
2843 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2850 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2852 my $hereline = "$here\n$rawline\n";
2853 my $herecurr = "$here\n$rawline\n";
2854 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2856 $cnt_lines++ if ($realcnt != 0);
2858 # Verify the existence of a commit log if appropriate
2859 # 2 is used because a $signature is counted in $commit_log_lines
2860 if ($in_commit_log) {
2861 if ($line !~ /^\s*$/) {
2862 $commit_log_lines++; #could be a $signature
2864 } elsif ($has_commit_log && $commit_log_lines < 2) {
2865 WARN("COMMIT_MESSAGE",
2866 "Missing commit description - Add an appropriate one\n");
2867 $commit_log_lines = 2; #warn only once
2870 # Check if the commit log has what seems like a diff which can confuse patch
2871 if ($in_commit_log && !$commit_log_has_diff &&
2872 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2873 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2874 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2875 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2876 ERROR("DIFF_IN_COMMIT_MSG",
2877 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2878 $commit_log_has_diff = 1;
2881 # Check for incorrect file permissions
2882 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2883 my $permhere = $here . "FILE: $realfile\n";
2884 if ($realfile !~ m@scripts/@ &&
2885 $realfile !~ /\.(py|pl|awk|sh)$/) {
2886 ERROR("EXECUTE_PERMISSIONS",
2887 "do not set execute permissions for source files\n" . $permhere);
2891 # Check the patch for a From:
2892 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2894 my $curline = $linenr;
2895 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2898 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2900 $author = reformat_email($author);
2903 # Check the patch for a signoff:
2904 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2907 if ($author ne '' && $authorsignoff != 1) {
2908 if (same_email_addresses($1, $author)) {
2912 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2913 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2915 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2918 } elsif (lc $email_address eq lc $author_address) {
2921 } elsif ($email_name eq $author_name) {
2925 my $address1 = $email_address;
2926 my $address2 = $author_address;
2928 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2931 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2934 if ($address1 eq $address2) {
2942 # Check for patch separator
2943 if ($line =~ /^---$/) {
2944 $has_patch_separator = 1;
2948 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2949 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2950 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2951 $reported_maintainer_file = 1;
2954 # Check signature styles
2955 if (!$in_header_lines &&
2956 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2957 my $space_before = $1;
2959 my $space_after = $3;
2961 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2963 if ($sign_off !~ /$signature_tags/) {
2964 my $suggested_signature = find_standard_signature($sign_off);
2965 if ($suggested_signature eq "") {
2966 WARN("BAD_SIGN_OFF",
2967 "Non-standard signature: $sign_off\n" . $herecurr);
2969 if (WARN("BAD_SIGN_OFF",
2970 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
2972 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
2976 if (defined $space_before && $space_before ne "") {
2977 if (WARN("BAD_SIGN_OFF",
2978 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2980 $fixed[$fixlinenr] =
2981 "$ucfirst_sign_off $email";
2984 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2985 if (WARN("BAD_SIGN_OFF",
2986 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2988 $fixed[$fixlinenr] =
2989 "$ucfirst_sign_off $email";
2993 if (!defined $space_after || $space_after ne " ") {
2994 if (WARN("BAD_SIGN_OFF",
2995 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2997 $fixed[$fixlinenr] =
2998 "$ucfirst_sign_off $email";
3002 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3003 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3004 if ($suggested_email eq "") {
3005 ERROR("BAD_SIGN_OFF",
3006 "Unrecognized email address: '$email'\n" . $herecurr);
3008 my $dequoted = $suggested_email;
3009 $dequoted =~ s/^"//;
3010 $dequoted =~ s/" </ </;
3011 # Don't force email to have quotes
3012 # Allow just an angle bracketed address
3013 if (!same_email_addresses($email, $suggested_email)) {
3014 if (WARN("BAD_SIGN_OFF",
3015 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3017 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3021 # Address part shouldn't have comments
3022 my $stripped_address = $email_address;
3023 $stripped_address =~ s/\([^\(\)]*\)//g;
3024 if ($email_address ne $stripped_address) {
3025 if (WARN("BAD_SIGN_OFF",
3026 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3028 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3032 # Only one name comment should be allowed
3033 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3034 if ($comment_count > 1) {
3035 WARN("BAD_SIGN_OFF",
3036 "Use a single name comment in email: '$email'\n" . $herecurr);
3040 # stable@vger.kernel.org or stable@kernel.org shouldn't
3041 # have an email name. In addition comments should strictly
3043 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3044 if (($comment ne "" && $comment !~ /^#.+/) ||
3045 ($email_name ne "")) {
3046 my $cur_name = $email_name;
3047 my $new_comment = $comment;
3048 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3050 # Remove brackets enclosing comment text
3051 # and # from start of comments to get comment text
3052 $new_comment =~ s/^\((.*)\)$/$1/;
3053 $new_comment =~ s/^\[(.*)\]$/$1/;
3054 $new_comment =~ s/^[\s\#]+|\s+$//g;
3056 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3057 $new_comment = " # $new_comment" if ($new_comment ne "");
3058 my $new_email = "$email_address$new_comment";
3060 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3061 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3063 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3066 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3067 my $new_comment = $comment;
3069 # Extract comment text from within brackets or
3070 # c89 style /*...*/ comments
3071 $new_comment =~ s/^\[(.*)\]$/$1/;
3072 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3074 $new_comment = trim($new_comment);
3075 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3076 $new_comment = "($new_comment)" if ($new_comment ne "");
3077 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3079 if (WARN("BAD_SIGN_OFF",
3080 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3082 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3087 # Check for duplicate signatures
3088 my $sig_nospace = $line;
3089 $sig_nospace =~ s/\s//g;
3090 $sig_nospace = lc($sig_nospace);
3091 if (defined $signatures{$sig_nospace}) {
3092 WARN("BAD_SIGN_OFF",
3093 "Duplicate signature\n" . $herecurr);
3095 $signatures{$sig_nospace} = 1;
3098 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3099 if ($sign_off =~ /^co-developed-by:$/i) {
3100 if ($email eq $author) {
3101 WARN("BAD_SIGN_OFF",
3102 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3104 if (!defined $lines[$linenr]) {
3105 WARN("BAD_SIGN_OFF",
3106 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3107 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3108 WARN("BAD_SIGN_OFF",
3109 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3110 } elsif ($1 ne $email) {
3111 WARN("BAD_SIGN_OFF",
3112 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3117 # Check email subject for common tools that don't need to be mentioned
3118 if ($in_header_lines &&
3119 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3120 WARN("EMAIL_SUBJECT",
3121 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3124 # Check for Gerrit Change-Ids not in any patch context
3125 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3126 if (ERROR("GERRIT_CHANGE_ID",
3127 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3129 fix_delete_line($fixlinenr, $rawline);
3133 # Check if the commit log is in a possible stack dump
3134 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3135 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3136 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3138 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3139 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3140 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3141 # stack dump address styles
3142 $commit_log_possible_stack_dump = 1;
3145 # Check for line lengths > 75 in commit log, warn once
3146 if ($in_commit_log && !$commit_log_long_line &&
3147 length($line) > 75 &&
3148 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3149 # file delta changes
3150 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
3152 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3153 # A Fixes: or Link: line or signature tag line
3154 $commit_log_possible_stack_dump)) {
3155 WARN("COMMIT_LOG_LONG_LINE",
3156 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3157 $commit_log_long_line = 1;
3160 # Reset possible stack dump if a blank line is found
3161 if ($in_commit_log && $commit_log_possible_stack_dump &&
3163 $commit_log_possible_stack_dump = 0;
3166 # Check for lines starting with a #
3167 if ($in_commit_log && $line =~ /^#/) {
3168 if (WARN("COMMIT_COMMENT_SYMBOL",
3169 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3171 $fixed[$fixlinenr] =~ s/^/ /;
3175 # Check for git id commit length and improperly formed commit descriptions
3176 # A correctly formed commit description is:
3177 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3178 # with the commit subject '("' prefix and '")' suffix
3179 # This is a fairly compilicated block as it tests for what appears to be
3180 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3181 # possible SHA-1 matches.
3182 # A commit match can span multiple lines so this block attempts to find a
3183 # complete typical commit on a maximum of 3 lines
3184 if ($perl_version_ok &&
3185 $in_commit_log && !$commit_log_possible_stack_dump &&
3186 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3187 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3188 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3189 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3190 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3191 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3192 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3193 my $init_char = "c";
3194 my $orig_commit = "";
3199 my $id = '0123456789ab';
3200 my $orig_desc = "commit description";
3201 my $description = "";
3202 my $herectx = $herecurr;
3207 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3208 for (my $n = 0; $n < 2; $n++) {
3209 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3212 # Always strip leading/trailing parens then double quotes if existing
3213 $orig_desc = substr($orig_desc, 1, -1);
3214 if ($orig_desc =~ /^".*"$/) {
3215 $orig_desc = substr($orig_desc, 1, -1);
3220 last if ($#lines < $linenr + $n);
3221 $input .= " " . trim($rawlines[$linenr + $n]);
3222 $herectx .= "$rawlines[$linenr + $n]\n";
3224 $herectx = $herecurr if (!$has_parens);
3227 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3229 $orig_commit = lc($2);
3230 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3231 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3232 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3233 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3234 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3235 $orig_commit = lc($1);
3238 ($id, $description) = git_commit_info($orig_commit,
3242 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3243 $last_git_commit_id_linenr != $linenr - 1) {
3244 ERROR("GIT_COMMIT_ID",
3245 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3247 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3248 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3251 # Check for added, moved or deleted files
3252 if (!$reported_maintainer_file && !$in_commit_log &&
3253 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3254 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3255 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3256 (defined($1) || defined($2))))) {
3258 $reported_maintainer_file = 1;
3259 WARN("FILE_PATH_CHANGES",
3260 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3263 # Check for adding new DT bindings not in schema format
3264 if (!$in_commit_log &&
3265 ($line =~ /^new file mode\s*\d+\s*$/) &&
3266 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3267 WARN("DT_SCHEMA_BINDING_PATCH",
3268 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3271 # Check for wrappage within a valid hunk of the file
3272 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3273 ERROR("CORRUPTED_PATCH",
3274 "patch seems to be corrupt (line wrapped?)\n" .
3275 $herecurr) if (!$emitted_corrupt++);
3278 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3279 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3280 $rawline !~ m/^$UTF8*$/) {
3281 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3283 my $blank = copy_spacing($rawline);
3284 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3285 my $hereptr = "$hereline$ptr\n";
3288 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3291 # Check if it's the start of a commit log
3292 # (not a header line and we haven't seen the patch filename)
3293 if ($in_header_lines && $realfile =~ /^$/ &&
3294 !($rawline =~ /^\s+(?:\S|$)/ ||
3295 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3296 $in_header_lines = 0;
3298 $has_commit_log = 1;
3301 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3302 # declined it, i.e defined some charset where it is missing.
3303 if ($in_header_lines &&
3304 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3306 $non_utf8_charset = 1;
3309 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3310 $rawline =~ /$NON_ASCII_UTF8/) {
3311 WARN("UTF8_BEFORE_PATCH",
3312 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3315 # Check for absolute kernel paths in commit message
3316 if ($tree && $in_commit_log) {
3317 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3320 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3321 check_absolute_file($1, $herecurr)) {
3324 check_absolute_file($file, $herecurr);
3329 # Check for various typo / spelling mistakes
3330 if (defined($misspellings) &&
3331 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3332 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3334 my $blank = copy_spacing($rawline);
3335 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3336 my $hereptr = "$hereline$ptr\n";
3337 my $typo_fix = $spelling_fix{lc($typo)};
3338 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3339 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3340 my $msg_level = \&WARN;
3341 $msg_level = \&CHK if ($file);
3342 if (&{$msg_level}("TYPO_SPELLING",
3343 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3345 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3350 # check for invalid commit id
3351 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3354 ($id, $description) = git_commit_info($2, undef, undef);
3355 if (!defined($id)) {
3356 WARN("UNKNOWN_COMMIT_ID",
3357 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3361 # check for repeated words separated by a single space
3362 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3363 if (($rawline =~ /^\+/ || $in_commit_log) &&
3364 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3365 pos($rawline) = 1 if (!$in_commit_log);
3366 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3370 my $start_pos = $-[1];
3371 my $end_pos = $+[2];
3372 if ($first =~ /(?:struct|union|enum)/) {
3373 pos($rawline) += length($first) + length($second) + 1;
3377 next if (lc($first) ne lc($second));
3378 next if ($first eq 'long');
3380 # check for character before and after the word matches
3381 my $start_char = '';
3383 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3384 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3386 next if ($start_char =~ /^\S$/);
3387 next if (index(" \t.,;?!", $end_char) == -1);
3389 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3390 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3391 next if (!exists($allow_repeated_words{lc($first)}));
3394 if (WARN("REPEATED_WORD",
3395 "Possible repeated word: '$first'\n" . $herecurr) &&
3397 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3401 # if it's a repeated word on consecutive lines in a comment block
3402 if ($prevline =~ /$;+\s*$/ &&
3403 $prevrawline =~ /($word_pattern)\s*$/) {
3405 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3406 if (WARN("REPEATED_WORD",
3407 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3409 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3415 # ignore non-hunk lines and lines being removed
3416 next if (!$hunk_line || $line =~ /^-/);
3418 #trailing whitespace
3419 if ($line =~ /^\+.*\015/) {
3420 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3421 if (ERROR("DOS_LINE_ENDINGS",
3422 "DOS line endings\n" . $herevet) &&
3424 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3426 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3427 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3428 if (ERROR("TRAILING_WHITESPACE",
3429 "trailing whitespace\n" . $herevet) &&
3431 $fixed[$fixlinenr] =~ s/\s+$//;
3437 # Check for FSF mailing addresses.
3438 if ($rawline =~ /\bwrite to the Free/i ||
3439 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3440 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3441 $rawline =~ /\b51\s+Franklin\s+St/i) {
3442 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3443 my $msg_level = \&ERROR;
3444 $msg_level = \&CHK if ($file);
3445 &{$msg_level}("FSF_MAILING_ADDRESS",
3446 "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)
3449 # check for Kconfig help text having a real description
3450 # Only applies when adding the entry originally, after that we do not have
3451 # sufficient context to determine whether it is indeed long enough.
3452 if ($realfile =~ /Kconfig/ &&
3453 # 'choice' is usually the last thing on the line (though
3454 # Kconfig supports named choices), so use a word boundary
3455 # (\b) rather than a whitespace character (\s)
3456 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3459 my $ln = $linenr + 1;
3463 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3464 $f = $lines[$ln - 1];
3465 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3466 $is_end = $lines[$ln - 1] =~ /^\+/;
3468 next if ($f =~ /^-/);
3469 last if (!$file && $f =~ /^\@\@/);
3471 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3473 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3480 next if ($f =~ /^$/);
3482 # This only checks context lines in the patch
3483 # and so hopefully shouldn't trigger false
3484 # positives, even though some of these are
3485 # common words in help texts
3486 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3487 if|endif|menu|endmenu|source)\b/x) {
3493 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3494 WARN("CONFIG_DESCRIPTION",
3495 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3497 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3500 # check MAINTAINERS entries
3501 if ($realfile =~ /^MAINTAINERS$/) {
3502 # check MAINTAINERS entries for the right form
3503 if ($rawline =~ /^\+[A-Z]:/ &&
3504 $rawline !~ /^\+[A-Z]:\t\S/) {
3505 if (WARN("MAINTAINERS_STYLE",
3506 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3508 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3511 # check MAINTAINERS entries for the right ordering too
3512 my $preferred_order = 'MRLSWQBCPTFXNK';
3513 if ($rawline =~ /^\+[A-Z]:/ &&
3514 $prevrawline =~ /^[\+ ][A-Z]:/) {
3515 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3518 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3521 my $curindex = index($preferred_order, $cur);
3522 my $previndex = index($preferred_order, $prev);
3523 if ($curindex < 0) {
3524 WARN("MAINTAINERS_STYLE",
3525 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3527 if ($previndex >= 0 && $curindex < $previndex) {
3528 WARN("MAINTAINERS_STYLE",
3529 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3530 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3531 ($prev eq 'X' && $cur eq 'X')) &&
3532 ($prevval cmp $curval) > 0) {
3533 WARN("MAINTAINERS_STYLE",
3534 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3540 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3541 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3544 'EXTRA_AFLAGS' => 'asflags-y',
3545 'EXTRA_CFLAGS' => 'ccflags-y',
3546 'EXTRA_CPPFLAGS' => 'cppflags-y',
3547 'EXTRA_LDFLAGS' => 'ldflags-y',
3550 WARN("DEPRECATED_VARIABLE",
3551 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3554 # check for DT compatible documentation
3555 if (defined $root &&
3556 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3557 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3559 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3561 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3562 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3564 foreach my $compat (@compats) {
3565 my $compat2 = $compat;
3566 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3567 my $compat3 = $compat;
3568 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3569 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3571 WARN("UNDOCUMENTED_DT_STRING",
3572 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3575 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3577 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3579 WARN("UNDOCUMENTED_DT_STRING",
3580 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3585 # check for using SPDX license tag at beginning of files
3586 if ($realline == $checklicenseline) {
3587 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3588 $checklicenseline = 2;
3589 } elsif ($rawline =~ /^\+/) {
3591 if ($realfile =~ /\.(h|s|S)$/) {
3593 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3595 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3597 } elsif ($realfile =~ /\.rst$/) {
3601 # check SPDX comment style for .[chsS] files
3602 if ($realfile =~ /\.[chsS]$/ &&
3603 $rawline =~ /SPDX-License-Identifier:/ &&
3604 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3605 WARN("SPDX_LICENSE_TAG",
3606 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3609 if ($comment !~ /^$/ &&
3610 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3611 WARN("SPDX_LICENSE_TAG",
3612 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3613 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3614 my $spdx_license = $1;
3615 if (!is_SPDX_License_valid($spdx_license)) {
3616 WARN("SPDX_LICENSE_TAG",
3617 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3619 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3620 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3621 my $msg_level = \&WARN;
3622 $msg_level = \&CHK if ($file);
3623 if (&{$msg_level}("SPDX_LICENSE_TAG",
3625 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3627 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3634 # check for embedded filenames
3635 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3636 WARN("EMBEDDED_FILENAME",
3637 "It's generally not useful to have the filename in the file\n" . $herecurr);
3640 # check we are in a valid source file if not then ignore this hunk
3641 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3643 # check for using SPDX-License-Identifier on the wrong line number
3644 if ($realline != $checklicenseline &&
3645 $rawline =~ /\bSPDX-License-Identifier:/ &&
3646 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3647 WARN("SPDX_LICENSE_TAG",
3648 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3651 # line length limit (with some exclusions)
3653 # There are a few types of lines that may extend beyond $max_line_length:
3654 # logging functions like pr_info that end in a string
3655 # lines with a single string
3656 # #defines that are a single string
3657 # lines with an RFC3986 like URL
3659 # There are 3 different line length message types:
3660 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3661 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3662 # LONG_LINE all other lines longer than $max_line_length
3664 # if LONG_LINE is ignored, the other 2 types are also ignored
3667 if ($line =~ /^\+/ && $length > $max_line_length) {
3668 my $msg_type = "LONG_LINE";
3670 # Check the allowed long line types first
3672 # logging functions that end in a string that starts
3673 # before $max_line_length
3674 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3675 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3678 # lines with only strings (w/ possible termination)
3679 # #defines with only strings
3680 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3681 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3684 # More special cases
3685 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3686 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3689 # URL ($rawline is used in case the URL is in a comment)
3690 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3693 # Otherwise set the alternate message types
3695 # a comment starts before $max_line_length
3696 } elsif ($line =~ /($;[\s$;]*)$/ &&
3697 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3698 $msg_type = "LONG_LINE_COMMENT"
3700 # a quoted string starts before $max_line_length
3701 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3702 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3703 $msg_type = "LONG_LINE_STRING"
3706 if ($msg_type ne "" &&
3707 (show_type("LONG_LINE") || show_type($msg_type))) {
3708 my $msg_level = \&WARN;
3709 $msg_level = \&CHK if ($file);
3710 &{$msg_level}($msg_type,
3711 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3715 # check for adding lines without a newline.
3716 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3717 if (WARN("MISSING_EOF_NEWLINE",
3718 "adding a line without newline at end of file\n" . $herecurr) &&
3720 fix_delete_line($fixlinenr+1, "No newline at end of file");
3724 # check for .L prefix local symbols in .S files
3725 if ($realfile =~ /\.S$/ &&
3726 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3727 WARN("AVOID_L_PREFIX",
3728 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/asm-annotations.rst\n" . $herecurr);
3731 # check we are in a valid source file C or perl if not then ignore this hunk
3732 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3734 # at the beginning of a line any tabs must come first and anything
3735 # more than $tabsize must use tabs.
3736 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3737 $rawline =~ /^\+\s* \s*/) {
3738 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3740 if (ERROR("CODE_INDENT",
3741 "code indent should use tabs where possible\n" . $herevet) &&
3743 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3747 # check for space before tabs.
3748 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3749 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3750 if (WARN("SPACE_BEFORE_TAB",
3751 "please, no space before tabs\n" . $herevet) &&
3753 while ($fixed[$fixlinenr] =~
3754 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3755 while ($fixed[$fixlinenr] =~
3756 s/(^\+.*) +\t/$1\t/) {}
3760 # check for assignments on the start of a line
3761 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3763 if (CHK("ASSIGNMENT_CONTINUATIONS",
3764 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3765 $fix && $prevrawline =~ /^\+/) {
3766 # add assignment operator to the previous line, remove from current line
3767 $fixed[$fixlinenr - 1] .= " $operator";
3768 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3772 # check for && or || at the start of a line
3773 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3775 if (CHK("LOGICAL_CONTINUATIONS",
3776 "Logical continuations should be on the previous line\n" . $hereprev) &&
3777 $fix && $prevrawline =~ /^\+/) {
3778 # insert logical operator at last non-comment, non-whitepsace char on previous line
3779 $prevline =~ /[\s$;]*$/;
3780 my $line_end = substr($prevrawline, $-[0]);
3781 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3782 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3786 # check indentation starts on a tab stop
3787 if ($perl_version_ok &&
3788 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3789 my $indent = length($1);
3790 if ($indent % $tabsize) {
3792 "Statements should start on a tabstop\n" . $herecurr) &&
3794 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3799 # check multi-line statement indentation matches previous line
3800 if ($perl_version_ok &&
3801 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3802 $prevline =~ /^\+(\t*)(.*)$/;
3806 my $pos = pos_last_openparen($rest);
3808 $line =~ /^(\+| )([ \t]*)/;
3811 my $goodtabindent = $oldindent .
3812 "\t" x ($pos / $tabsize) .
3813 " " x ($pos % $tabsize);
3814 my $goodspaceindent = $oldindent . " " x $pos;
3816 if ($newindent ne $goodtabindent &&
3817 $newindent ne $goodspaceindent) {
3819 if (CHK("PARENTHESIS_ALIGNMENT",
3820 "Alignment should match open parenthesis\n" . $hereprev) &&
3821 $fix && $line =~ /^\+/) {
3822 $fixed[$fixlinenr] =~
3823 s/^\+[ \t]*/\+$goodtabindent/;
3829 # check for space after cast like "(int) foo" or "(struct foo) bar"
3830 # avoid checking a few false positives:
3831 # "sizeof(<type>)" or "__alignof__(<type>)"
3832 # function pointer declarations like "(*foo)(int) = bar;"
3833 # structure definitions like "(struct foo) { 0 };"
3834 # multiline macros that define functions
3835 # known attributes or the __attribute__ keyword
3836 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3837 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3839 "No space is necessary after a cast\n" . $herecurr) &&
3841 $fixed[$fixlinenr] =~
3842 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3846 # Block comment styles
3847 # Networking with an initial /*
3848 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3849 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3850 $rawline =~ /^\+[ \t]*\*/ &&
3851 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3852 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3853 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3856 # Block comments use * on subsequent lines
3857 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3858 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3859 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3860 $rawline =~ /^\+/ && #line is new
3861 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3862 WARN("BLOCK_COMMENT_STYLE",
3863 "Block comments use * on subsequent lines\n" . $hereprev);
3866 # Block comments use */ on trailing lines
3867 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3868 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3869 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3870 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3871 WARN("BLOCK_COMMENT_STYLE",
3872 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3875 # Block comment * alignment
3876 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3877 $line =~ /^\+[ \t]*$;/ && #leading comment
3878 $rawline =~ /^\+[ \t]*\*/ && #leading *
3879 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3880 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3881 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3883 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3885 $oldindent = expand_tabs($1);
3887 $prevrawline =~ m@^\+(.*/?)\*@;
3888 $oldindent = expand_tabs($1);
3890 $rawline =~ m@^\+([ \t]*)\*@;
3892 $newindent = expand_tabs($newindent);
3893 if (length($oldindent) ne length($newindent)) {
3894 WARN("BLOCK_COMMENT_STYLE",
3895 "Block comments should align the * on each line\n" . $hereprev);
3899 # check for missing blank lines after struct/union declarations
3900 # with exceptions for various attributes and macros
3901 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3903 !($line =~ /^\+\s*$/ ||
3904 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3905 $line =~ /^\+\s*MODULE_/i ||
3906 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3907 $line =~ /^\+[a-z_]*init/ ||
3908 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3909 $line =~ /^\+\s*DECLARE/ ||
3910 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3911 $line =~ /^\+\s*__setup/)) {
3912 if (CHK("LINE_SPACING",
3913 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3915 fix_insert_line($fixlinenr, "\+");
3919 # check for multiple consecutive blank lines
3920 if ($prevline =~ /^[\+ ]\s*$/ &&
3921 $line =~ /^\+\s*$/ &&
3922 $last_blank_line != ($linenr - 1)) {
3923 if (CHK("LINE_SPACING",
3924 "Please don't use multiple blank lines\n" . $hereprev) &&
3926 fix_delete_line($fixlinenr, $rawline);
3929 $last_blank_line = $linenr;
3932 # check for missing blank lines after declarations
3933 # (declarations must have the same indentation and not be at the start of line)
3934 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3938 # remove $Attribute/$Sparse uses to simplify comparisons
3939 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3940 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3941 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3942 # function pointer declarations
3943 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3944 # foo bar; where foo is some local typedef or #define
3945 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3946 # known declaration macros
3947 $pl =~ /^\+\s+$declaration_macros/) &&
3948 # for "else if" which can look like "$Ident $Ident"
3949 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3950 # other possible extensions of declaration lines
3951 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3952 # not starting a section or a macro "\" extended line
3953 $pl =~ /(?:\{\s*|\\)$/) &&
3954 # looks like a declaration
3955 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3956 # function pointer declarations
3957 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3958 # foo bar; where foo is some local typedef or #define
3959 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3960 # known declaration macros
3961 $sl =~ /^\+\s+$declaration_macros/ ||
3962 # start of struct or union or enum
3963 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3964 # start or end of block or continuation of declaration
3965 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3966 # bitfield continuation
3967 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3968 # other possible extensions of declaration lines
3969 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3970 if (WARN("LINE_SPACING",
3971 "Missing a blank line after declarations\n" . $hereprev) &&
3973 fix_insert_line($fixlinenr, "\+");
3978 # check for spaces at the beginning of a line.
3980 # 1) within comments
3981 # 2) indented preprocessor commands
3983 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3984 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3985 if (WARN("LEADING_SPACE",
3986 "please, no spaces at the start of a line\n" . $herevet) &&
3988 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3992 # check we are in a valid C source file if not then ignore this hunk
3993 next if ($realfile !~ /\.(h|c)$/);
3995 # check for unusual line ending [ or (
3996 if ($line =~ /^\+.*([\[\(])\s*$/) {
3997 CHK("OPEN_ENDED_LINE",
3998 "Lines should not end with a '$1'\n" . $herecurr);
4001 # check if this appears to be the start function declaration, save the name
4002 if ($sline =~ /^\+\{\s*$/ &&
4003 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4004 $context_function = $1;
4007 # check if this appears to be the end of function declaration
4008 if ($sline =~ /^\+\}\s*$/) {
4009 undef $context_function;
4012 # check indentation of any line with a bare else
4013 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4014 # if the previous line is a break or return and is indented 1 tab more...
4015 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4016 my $tabs = length($1) + 1;
4017 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4018 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4019 defined $lines[$linenr] &&
4020 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4021 WARN("UNNECESSARY_ELSE",
4022 "else is not generally useful after a break or return\n" . $hereprev);
4026 # check indentation of a line with a break;
4027 # if the previous line is a goto, return or break
4028 # and is indented the same # of tabs
4029 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4031 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4032 if (WARN("UNNECESSARY_BREAK",
4033 "break is not useful after a $1\n" . $hereprev) &&
4035 fix_delete_line($fixlinenr, $rawline);
4040 # check for RCS/CVS revision markers
4041 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4043 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4046 # check for old HOTPLUG __dev<foo> section markings
4047 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4048 WARN("HOTPLUG_SECTION",
4049 "Using $1 is unnecessary\n" . $herecurr);
4052 # Check for potential 'bare' types
4053 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4055 #print "LINE<$line>\n";
4056 if ($linenr > $suppress_statement &&
4057 $realcnt && $sline =~ /.\s*\S/) {
4058 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4059 ctx_statement_block($linenr, $realcnt, 0);
4060 $stat =~ s/\n./\n /g;
4061 $cond =~ s/\n./\n /g;
4063 #print "linenr<$linenr> <$stat>\n";
4064 # If this statement has no statement boundaries within
4065 # it there is no point in retrying a statement scan
4066 # until we hit end of it.
4067 my $frag = $stat; $frag =~ s/;+\s*$//;
4068 if ($frag !~ /(?:{|;)/) {
4069 #print "skip<$line_nr_next>\n";
4070 $suppress_statement = $line_nr_next;
4073 # Find the real next line.
4074 $realline_next = $line_nr_next;
4075 if (defined $realline_next &&
4076 (!defined $lines[$realline_next - 1] ||
4077 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4084 # Ignore goto labels.
4085 if ($s =~ /$Ident:\*$/s) {
4087 # Ignore functions being called
4088 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4090 } elsif ($s =~ /^.\s*else\b/s) {
4092 # declarations always start with types
4093 } 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) {
4096 possible($type, "A:" . $s);
4098 # definitions in global scope can only start with types
4099 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4100 possible($1, "B:" . $s);
4103 # any (foo ... *) is a pointer cast, and foo is a type
4104 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4105 possible($1, "C:" . $s);
4108 # Check for any sort of function declaration.
4109 # int foo(something bar, other baz);
4110 # void (*store_gdt)(x86_descr_ptr *);
4111 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4112 my ($name_len) = length($1);
4115 substr($ctx, 0, $name_len + 1, '');
4116 $ctx =~ s/\)[^\)]*$//;
4118 for my $arg (split(/\s*,\s*/, $ctx)) {
4119 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4121 possible($1, "D:" . $s);
4129 # Checks which may be anchored in the context.
4132 # Check for switch () and associated case and default
4133 # statements should be at the same indent.
4134 if ($line=~/\bswitch\s*\(.*\)/) {
4137 my @ctx = ctx_block_outer($linenr, $realcnt);
4139 for my $ctx (@ctx) {
4140 my ($clen, $cindent) = line_stats($ctx);
4141 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4142 $indent != $cindent) {
4143 $err .= "$sep$ctx\n";
4150 ERROR("SWITCH_CASE_INDENT_LEVEL",
4151 "switch and case should be at the same indent\n$hereline$err");
4155 # if/while/etc brace do not go on next line, unless defining a do while loop,
4156 # or if that brace on the next line is for something else
4157 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4158 my $pre_ctx = "$1$2";
4160 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4162 if ($line =~ /^\+\t{6,}/) {
4163 WARN("DEEP_INDENTATION",
4164 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4167 my $ctx_cnt = $realcnt - $#ctx - 1;
4168 my $ctx = join("\n", @ctx);
4170 my $ctx_ln = $linenr;
4171 my $ctx_skip = $realcnt;
4173 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4174 defined $lines[$ctx_ln - 1] &&
4175 $lines[$ctx_ln - 1] =~ /^-/)) {
4176 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4177 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4181 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4182 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4184 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4186 "that open brace { should be on the previous line\n" .
4187 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4189 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4190 $ctx =~ /\)\s*\;\s*$/ &&
4191 defined $lines[$ctx_ln - 1])
4193 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4194 if ($nindent > $indent) {
4195 WARN("TRAILING_SEMICOLON",
4196 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4197 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4202 # Check relative indent for conditionals and blocks.
4203 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4204 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4205 ctx_statement_block($linenr, $realcnt, 0)
4206 if (!defined $stat);
4207 my ($s, $c) = ($stat, $cond);
4209 substr($s, 0, length($c), '');
4211 # remove inline comments
4215 # Find out how long the conditional actually is.
4216 my @newlines = ($c =~ /\n/gs);
4217 my $cond_lines = 1 + $#newlines;
4219 # Make sure we remove the line prefixes as we have
4220 # none on the first line, and are going to readd them
4223 while ($s =~ /\n\s+\\\n/) {
4224 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4227 # We want to check the first line inside the block
4228 # starting at the end of the conditional, so remove:
4229 # 1) any blank line termination
4230 # 2) any opening brace { on end of the line
4232 my $continuation = 0;
4234 $s =~ s/^.*\bdo\b//;
4236 if ($s =~ s/^\s*\\//) {
4239 if ($s =~ s/^\s*?\n//) {
4244 # Also ignore a loop construct at the end of a
4245 # preprocessor statement.
4246 if (($prevline =~ /^.\s*#\s*define\s/ ||
4247 $prevline =~ /\\\s*$/) && $continuation == 0) {
4253 while ($cond_ptr != $cond_lines) {
4254 $cond_ptr = $cond_lines;
4256 # If we see an #else/#elif then the code
4258 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4263 # 1) blank lines, they should be at 0,
4264 # 2) preprocessor lines, and
4266 if ($continuation ||
4268 $s =~ /^\s*#\s*?/ ||
4269 $s =~ /^\s*$Ident\s*:/) {
4270 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4271 if ($s =~ s/^.*?\n//) {
4277 my (undef, $sindent) = line_stats("+" . $s);
4278 my $stat_real = raw_line($linenr, $cond_lines);
4280 # Check if either of these lines are modified, else
4281 # this is not this patch's fault.
4282 if (!defined($stat_real) ||
4283 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4286 if (defined($stat_real) && $cond_lines > 1) {
4287 $stat_real = "[...]\n$stat_real";
4290 #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";
4292 if ($check && $s ne '' &&
4293 (($sindent % $tabsize) != 0 ||
4294 ($sindent < $indent) ||
4295 ($sindent == $indent &&
4296 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4297 ($sindent > $indent + $tabsize))) {
4298 WARN("SUSPECT_CODE_INDENT",
4299 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4303 # Track the 'values' across context and added lines.
4304 my $opline = $line; $opline =~ s/^./ /;
4305 my ($curr_values, $curr_vars) =
4306 annotate_values($opline . "\n", $prev_values);
4307 $curr_values = $prev_values . $curr_values;
4309 my $outline = $opline; $outline =~ s/\t/ /g;
4310 print "$linenr > .$outline\n";
4311 print "$linenr > $curr_values\n";
4312 print "$linenr > $curr_vars\n";
4314 $prev_values = substr($curr_values, -1);
4316 #ignore lines not being added
4317 next if ($line =~ /^[^\+]/);
4319 # check for self assignments used to avoid compiler warnings
4320 # e.g.: int foo = foo, *bar = NULL;
4321 # struct foo bar = *(&(bar));
4322 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4324 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4325 WARN("SELF_ASSIGNMENT",
4326 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4330 # check for dereferences that span multiple lines
4331 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4332 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4333 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4335 $line =~ /^.\s*($Lval)/;
4338 WARN("MULTILINE_DEREFERENCE",
4339 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4342 # check for declarations of signed or unsigned without int
4343 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4346 $var = "" if (!defined $var);
4347 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4351 $pointer = "" if (!defined $pointer);
4353 if (WARN("UNSPECIFIED_INT",
4354 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4356 my $decl = trim($sign) . " int ";
4357 my $comp_pointer = $pointer;
4358 $comp_pointer =~ s/\s//g;
4359 $decl .= $comp_pointer;
4360 $decl = rtrim($decl) if ($var eq "");
4361 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4366 # TEST: allow direct testing of the type matcher.
4368 if ($line =~ /^.\s*$Declare\s*$/) {
4370 "TEST: is type\n" . $herecurr);
4371 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4372 ERROR("TEST_NOT_TYPE",
4373 "TEST: is not type ($1 is)\n". $herecurr);
4377 # TEST: allow direct testing of the attribute matcher.
4379 if ($line =~ /^.\s*$Modifier\s*$/) {
4381 "TEST: is attr\n" . $herecurr);
4382 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4383 ERROR("TEST_NOT_ATTR",
4384 "TEST: is not attr ($1 is)\n". $herecurr);
4389 # check for initialisation to aggregates open brace on the next line
4390 if ($line =~ /^.\s*{/ &&
4391 $prevline =~ /(?:^|[^=])=\s*$/) {
4392 if (ERROR("OPEN_BRACE",
4393 "that open brace { should be on the previous line\n" . $hereprev) &&
4394 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4395 fix_delete_line($fixlinenr - 1, $prevrawline);
4396 fix_delete_line($fixlinenr, $rawline);
4397 my $fixedline = $prevrawline;
4398 $fixedline =~ s/\s*=\s*$/ = {/;
4399 fix_insert_line($fixlinenr, $fixedline);
4401 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4402 fix_insert_line($fixlinenr, $fixedline);
4407 # Checks which are anchored on the added line.
4410 # check for malformed paths in #include statements (uses RAW line)
4411 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4413 if ($path =~ m{//}) {
4414 ERROR("MALFORMED_INCLUDE",
4415 "malformed #include filename\n" . $herecurr);
4417 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4418 ERROR("UAPI_INCLUDE",
4419 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4423 # no C99 // comments
4424 if ($line =~ m{//}) {
4425 if (ERROR("C99_COMMENTS",
4426 "do not use C99 // comments\n" . $herecurr) &&
4428 my $line = $fixed[$fixlinenr];
4429 if ($line =~ /\/\/(.*)$/) {
4430 my $comment = trim($1);
4431 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4435 # Remove C99 comments.
4437 $opline =~ s@//.*@@;
4439 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4440 # the whole statement.
4441 #print "APW <$lines[$realline_next - 1]>\n";
4442 if (defined $realline_next &&
4443 exists $lines[$realline_next - 1] &&
4444 !defined $suppress_export{$realline_next} &&
4445 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4446 # Handle definitions which produce identifiers with
4449 # EXPORT_SYMBOL(something_foo);
4451 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4452 $name =~ /^${Ident}_$2/) {
4453 #print "FOO C name<$name>\n";
4454 $suppress_export{$realline_next} = 1;
4456 } elsif ($stat !~ /(?:
4458 ^.DEFINE_$Ident\(\Q$name\E\)|
4459 ^.DECLARE_$Ident\(\Q$name\E\)|
4460 ^.LIST_HEAD\(\Q$name\E\)|
4461 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4462 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4464 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4465 $suppress_export{$realline_next} = 2;
4467 $suppress_export{$realline_next} = 1;
4470 if (!defined $suppress_export{$linenr} &&
4471 $prevline =~ /^.\s*$/ &&
4472 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4473 #print "FOO B <$lines[$linenr - 1]>\n";
4474 $suppress_export{$linenr} = 2;
4476 if (defined $suppress_export{$linenr} &&
4477 $suppress_export{$linenr} == 2) {
4478 WARN("EXPORT_SYMBOL",
4479 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4482 # check for global initialisers.
4483 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4484 !exclude_global_initialisers($realfile)) {
4485 if (ERROR("GLOBAL_INITIALISERS",
4486 "do not initialise globals to $1\n" . $herecurr) &&
4488 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4491 # check for static initialisers.
4492 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4493 if (ERROR("INITIALISED_STATIC",
4494 "do not initialise statics to $1\n" .
4497 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4501 # check for misordered declarations of char/short/int/long with signed/unsigned
4502 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4504 WARN("MISORDERED_TYPE",
4505 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4508 # check for unnecessary <signed> int declarations of short/long/long long
4509 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4510 my $type = trim($1);
4511 next if ($type !~ /\bint\b/);
4512 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4513 my $new_type = $type;
4514 $new_type =~ s/\b\s*int\s*\b/ /;
4515 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4516 $new_type =~ s/^const\s+//;
4517 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4518 $new_type = "const $new_type" if ($type =~ /^const\b/);
4519 $new_type =~ s/\s+/ /g;
4520 $new_type = trim($new_type);
4521 if (WARN("UNNECESSARY_INT",
4522 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4524 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4528 # check for static const char * arrays.
4529 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4530 WARN("STATIC_CONST_CHAR_ARRAY",
4531 "static const char * array should probably be static const char * const\n" .
4535 # check for initialized const char arrays that should be static const
4536 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4537 if (WARN("STATIC_CONST_CHAR_ARRAY",
4538 "const array should probably be static const\n" . $herecurr) &&
4540 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4544 # check for static char foo[] = "bar" declarations.
4545 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4546 WARN("STATIC_CONST_CHAR_ARRAY",
4547 "static char array declaration should probably be static const char\n" .
4551 # check for const <foo> const where <foo> is not a pointer or array type
4552 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4554 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4556 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4557 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4559 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4563 # check for const static or static <non ptr type> const declarations
4564 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4565 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4566 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4567 if (WARN("STATIC_CONST",
4568 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4570 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4571 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4575 # check for non-global char *foo[] = {"bar", ...} declarations.
4576 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4577 WARN("STATIC_CONST_CHAR_ARRAY",
4578 "char * array declaration might be better as static const\n" .
4582 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4583 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4585 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4587 if (WARN("ARRAY_SIZE",
4588 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4590 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4595 # check for function declarations without arguments like "int foo()"
4596 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4597 if (ERROR("FUNCTION_WITHOUT_ARGS",
4598 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4600 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4604 # check for new typedefs, only function parameters and sparse annotations
4606 if ($line =~ /\btypedef\s/ &&
4607 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4608 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4609 $line !~ /\b$typeTypedefs\b/ &&
4610 $line !~ /\b__bitwise\b/) {
4611 WARN("NEW_TYPEDEFS",
4612 "do not add new typedefs\n" . $herecurr);
4615 # * goes on variable not on type
4617 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4619 my ($ident, $from, $to) = ($1, $2, $2);
4621 # Should start with a space.
4622 $to =~ s/^(\S)/ $1/;
4623 # Should not end with a space.
4625 # '*'s should not have spaces between.
4626 while ($to =~ s/\*\s+\*/\*\*/) {
4629 ## print "1: from<$from> to<$to> ident<$ident>\n";
4631 if (ERROR("POINTER_LOCATION",
4632 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4634 my $sub_from = $ident;
4635 my $sub_to = $ident;
4636 $sub_to =~ s/\Q$from\E/$to/;
4637 $fixed[$fixlinenr] =~
4638 s@\Q$sub_from\E@$sub_to@;
4642 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4644 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4646 # Should start with a space.
4647 $to =~ s/^(\S)/ $1/;
4648 # Should not end with a space.
4650 # '*'s should not have spaces between.
4651 while ($to =~ s/\*\s+\*/\*\*/) {
4653 # Modifiers should have spaces.
4654 $to =~ s/(\b$Modifier$)/$1 /;
4656 ## print "2: from<$from> to<$to> ident<$ident>\n";
4657 if ($from ne $to && $ident !~ /^$Modifier$/) {
4658 if (ERROR("POINTER_LOCATION",
4659 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4662 my $sub_from = $match;
4663 my $sub_to = $match;
4664 $sub_to =~ s/\Q$from\E/$to/;
4665 $fixed[$fixlinenr] =~
4666 s@\Q$sub_from\E@$sub_to@;
4671 # avoid BUG() or BUG_ON()
4672 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4673 my $msg_level = \&WARN;
4674 $msg_level = \&CHK if ($file);
4675 &{$msg_level}("AVOID_BUG",
4676 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4679 # avoid LINUX_VERSION_CODE
4680 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4681 WARN("LINUX_VERSION_CODE",
4682 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4685 # check for uses of printk_ratelimit
4686 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4687 WARN("PRINTK_RATELIMITED",
4688 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4691 # printk should use KERN_* levels
4692 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4693 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4694 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4697 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4698 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4702 $modifier = "" if (!defined($modifier));
4703 my $level = lc($orig);
4704 $level = "warn" if ($level eq "warning");
4705 my $level2 = $level;
4706 $level2 = "dbg" if ($level eq "debug");
4707 $level .= $modifier;
4708 $level2 .= $modifier;
4709 WARN("PREFER_PR_LEVEL",
4710 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4713 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4714 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4716 my $level = lc($orig);
4717 $level = "warn" if ($level eq "warning");
4718 $level = "dbg" if ($level eq "debug");
4719 WARN("PREFER_DEV_LEVEL",
4720 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4723 # trace_printk should not be used in production code.
4724 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4725 WARN("TRACE_PRINTK",
4726 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4729 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4730 # number of false positives, but assembly files are not checked, so at
4731 # least the arch entry code will not trigger this warning.
4732 if ($line =~ /\bENOSYS\b/) {
4734 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4737 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4738 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4739 # Similarly to ENOSYS warning a small number of false positives is expected.
4740 if (!$file && $line =~ /\bENOTSUPP\b/) {
4741 if (WARN("ENOTSUPP",
4742 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4744 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4748 # function brace can't be on same line, except for #defines of do while,
4749 # or if closed on same line
4750 if ($perl_version_ok &&
4751 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4752 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4754 if (ERROR("OPEN_BRACE",
4755 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4757 fix_delete_line($fixlinenr, $rawline);
4758 my $fixed_line = $rawline;
4759 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4762 fix_insert_line($fixlinenr, ltrim($line1));
4763 fix_insert_line($fixlinenr, "\+{");
4764 if ($line2 !~ /^\s*$/) {
4765 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4770 # open braces for enum, union and struct go on the same line.
4771 if ($line =~ /^.\s*{/ &&
4772 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4773 if (ERROR("OPEN_BRACE",
4774 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4775 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4776 fix_delete_line($fixlinenr - 1, $prevrawline);
4777 fix_delete_line($fixlinenr, $rawline);
4778 my $fixedline = rtrim($prevrawline) . " {";
4779 fix_insert_line($fixlinenr, $fixedline);
4780 $fixedline = $rawline;
4781 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4782 if ($fixedline !~ /^\+\s*$/) {
4783 fix_insert_line($fixlinenr, $fixedline);
4788 # missing space after union, struct or enum definition
4789 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4791 "missing space after $1 definition\n" . $herecurr) &&
4793 $fixed[$fixlinenr] =~
4794 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4798 # Function pointer declarations
4799 # check spacing between type, funcptr, and args
4800 # canonical declaration is "type (*funcptr)(args...)"
4801 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4803 my $pre_pointer_space = $2;
4804 my $post_pointer_space = $3;
4806 my $post_funcname_space = $5;
4807 my $pre_args_space = $6;
4809 # the $Declare variable will capture all spaces after the type
4810 # so check it for a missing trailing missing space but pointer return types
4811 # don't need a space so don't warn for those.
4812 my $post_declare_space = "";
4813 if ($declare =~ /(\s+)$/) {
4814 $post_declare_space = $1;
4815 $declare = rtrim($declare);
4817 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4819 "missing space after return type\n" . $herecurr);
4820 $post_declare_space = " ";
4823 # unnecessary space "type (*funcptr)(args...)"
4824 # This test is not currently implemented because these declarations are
4826 # int foo(int bar, ...)
4827 # and this is form shouldn't/doesn't generate a checkpatch warning.
4829 # elsif ($declare =~ /\s{2,}$/) {
4831 # "Multiple spaces after return type\n" . $herecurr);
4834 # unnecessary space "type ( *funcptr)(args...)"
4835 if (defined $pre_pointer_space &&
4836 $pre_pointer_space =~ /^\s/) {
4838 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4841 # unnecessary space "type (* funcptr)(args...)"
4842 if (defined $post_pointer_space &&
4843 $post_pointer_space =~ /^\s/) {
4845 "Unnecessary space before function pointer name\n" . $herecurr);
4848 # unnecessary space "type (*funcptr )(args...)"
4849 if (defined $post_funcname_space &&
4850 $post_funcname_space =~ /^\s/) {
4852 "Unnecessary space after function pointer name\n" . $herecurr);
4855 # unnecessary space "type (*funcptr) (args...)"
4856 if (defined $pre_args_space &&
4857 $pre_args_space =~ /^\s/) {
4859 "Unnecessary space before function pointer arguments\n" . $herecurr);
4862 if (show_type("SPACING") && $fix) {
4863 $fixed[$fixlinenr] =~
4864 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4868 # check for spacing round square brackets; allowed:
4869 # 1. with a type on the left -- int [] a;
4870 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4871 # 3. inside a curly brace -- = { [0...10] = 5 }
4872 while ($line =~ /(.*?\s)\[/g) {
4873 my ($where, $prefix) = ($-[1], $1);
4874 if ($prefix !~ /$Type\s+$/ &&
4875 ($where != 0 || $prefix !~ /^.\s+$/) &&
4876 $prefix !~ /[{,:]\s+$/) {
4877 if (ERROR("BRACKET_SPACE",
4878 "space prohibited before open square bracket '['\n" . $herecurr) &&
4880 $fixed[$fixlinenr] =~
4881 s/^(\+.*?)\s+\[/$1\[/;
4886 # check for spaces between functions and their parentheses.
4887 while ($line =~ /($Ident)\s+\(/g) {
4889 my $ctx_before = substr($line, 0, $-[1]);
4890 my $ctx = "$ctx_before$name";
4892 # Ignore those directives where spaces _are_ permitted.
4894 if|for|while|switch|return|case|
4895 volatile|__volatile__|
4896 __attribute__|format|__extension__|
4899 # cpp #define statements have non-optional spaces, ie
4900 # if there is a space between the name and the open
4901 # parenthesis it is simply not a parameter group.
4902 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4904 # cpp #elif statement condition may start with a (
4905 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4907 # If this whole things ends with a type its most
4908 # likely a typedef for a function.
4909 } elsif ($ctx =~ /$Type$/) {
4913 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4915 $fixed[$fixlinenr] =~
4916 s/\b$name\s+\(/$name\(/;
4921 # Check operator spacing.
4922 if (!($line=~/\#\s*include/)) {
4923 my $fixed_line = "";
4927 <<=|>>=|<=|>=|==|!=|
4928 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4929 =>|->|<<|>>|<|>|=|!|~|
4930 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4933 my @elements = split(/($ops|;)/, $opline);
4935 ## print("element count: <" . $#elements . ">\n");
4936 ## foreach my $el (@elements) {
4937 ## print("el: <$el>\n");
4940 my @fix_elements = ();
4943 foreach my $el (@elements) {
4944 push(@fix_elements, substr($rawline, $off, length($el)));
4945 $off += length($el);
4950 my $blank = copy_spacing($opline);
4951 my $last_after = -1;
4953 for (my $n = 0; $n < $#elements; $n += 2) {
4955 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4957 ## print("n: <$n> good: <$good>\n");
4959 $off += length($elements[$n]);
4961 # Pick up the preceding and succeeding characters.
4962 my $ca = substr($opline, 0, $off);
4964 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4965 $cc = substr($opline, $off + length($elements[$n + 1]));
4967 my $cb = "$ca$;$cc";
4970 $a = 'V' if ($elements[$n] ne '');
4971 $a = 'W' if ($elements[$n] =~ /\s$/);
4972 $a = 'C' if ($elements[$n] =~ /$;$/);
4973 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4974 $a = 'O' if ($elements[$n] eq '');
4975 $a = 'E' if ($ca =~ /^\s*$/);
4977 my $op = $elements[$n + 1];
4980 if (defined $elements[$n + 2]) {
4981 $c = 'V' if ($elements[$n + 2] ne '');
4982 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4983 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4984 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4985 $c = 'O' if ($elements[$n + 2] eq '');
4986 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4991 my $ctx = "${a}x${c}";
4993 my $at = "(ctx:$ctx)";
4995 my $ptr = substr($blank, 0, $off) . "^";
4996 my $hereptr = "$hereline$ptr\n";
4998 # Pull out the value of this operator.
4999 my $op_type = substr($curr_values, $off + 1, 1);
5001 # Get the full operator variant.
5002 my $opv = $op . substr($curr_vars, $off, 1);
5004 # Ignore operators passed as parameters.
5005 if ($op_type ne 'V' &&
5006 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5009 # } elsif ($op =~ /^$;+$/) {
5011 # ; should have either the end of line or a space or \ after it
5012 } elsif ($op eq ';') {
5013 if ($ctx !~ /.x[WEBC]/ &&
5014 $cc !~ /^\\/ && $cc !~ /^;/) {
5015 if (ERROR("SPACING",
5016 "space required after that '$op' $at\n" . $hereptr)) {
5017 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5023 } elsif ($op eq '//') {
5025 # : when part of a bitfield
5026 } elsif ($opv eq ':B') {
5027 # skip the bitfield test for now
5031 } elsif ($op eq '->') {
5032 if ($ctx =~ /Wx.|.xW/) {
5033 if (ERROR("SPACING",
5034 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5035 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5036 if (defined $fix_elements[$n + 2]) {
5037 $fix_elements[$n + 2] =~ s/^\s+//;
5043 # , must not have a space before and must have a space on the right.
5044 } elsif ($op eq ',') {
5045 my $rtrim_before = 0;
5046 my $space_after = 0;
5047 if ($ctx =~ /Wx./) {
5048 if (ERROR("SPACING",
5049 "space prohibited before that '$op' $at\n" . $hereptr)) {
5054 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5055 if (ERROR("SPACING",
5056 "space required after that '$op' $at\n" . $hereptr)) {
5062 if ($rtrim_before || $space_after) {
5063 if ($rtrim_before) {
5064 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5066 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5073 # '*' as part of a type definition -- reported already.
5074 } elsif ($opv eq '*_') {
5075 #warn "'*' is part of type\n";
5077 # unary operators should have a space before and
5078 # none after. May be left adjacent to another
5079 # unary operator, or a cast
5080 } elsif ($op eq '!' || $op eq '~' ||
5081 $opv eq '*U' || $opv eq '-U' ||
5082 $opv eq '&U' || $opv eq '&&U') {
5083 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5084 if (ERROR("SPACING",
5085 "space required before that '$op' $at\n" . $hereptr)) {
5086 if ($n != $last_after + 2) {
5087 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5092 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5093 # A unary '*' may be const
5095 } elsif ($ctx =~ /.xW/) {
5096 if (ERROR("SPACING",
5097 "space prohibited after that '$op' $at\n" . $hereptr)) {
5098 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5099 if (defined $fix_elements[$n + 2]) {
5100 $fix_elements[$n + 2] =~ s/^\s+//;
5106 # unary ++ and unary -- are allowed no space on one side.
5107 } elsif ($op eq '++' or $op eq '--') {
5108 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5109 if (ERROR("SPACING",
5110 "space required one side of that '$op' $at\n" . $hereptr)) {
5111 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5115 if ($ctx =~ /Wx[BE]/ ||
5116 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5117 if (ERROR("SPACING",
5118 "space prohibited before that '$op' $at\n" . $hereptr)) {
5119 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5123 if ($ctx =~ /ExW/) {
5124 if (ERROR("SPACING",
5125 "space prohibited after that '$op' $at\n" . $hereptr)) {
5126 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5127 if (defined $fix_elements[$n + 2]) {
5128 $fix_elements[$n + 2] =~ s/^\s+//;
5134 # << and >> may either have or not have spaces both sides
5135 } elsif ($op eq '<<' or $op eq '>>' or
5136 $op eq '&' or $op eq '^' or $op eq '|' or
5137 $op eq '+' or $op eq '-' or
5138 $op eq '*' or $op eq '/' or
5142 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5144 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5145 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5146 $fix_elements[$n + 2] =~ s/^\s+//;
5149 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5151 "space preferred before that '$op' $at\n" . $hereptr)) {
5152 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5156 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5157 if (ERROR("SPACING",
5158 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5159 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5160 if (defined $fix_elements[$n + 2]) {
5161 $fix_elements[$n + 2] =~ s/^\s+//;
5167 # A colon needs no spaces before when it is
5168 # terminating a case value or a label.
5169 } elsif ($opv eq ':C' || $opv eq ':L') {
5170 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5171 if (ERROR("SPACING",
5172 "space prohibited before that '$op' $at\n" . $hereptr)) {
5173 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5178 # All the others need spaces both sides.
5179 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5182 # Ignore email addresses <foo@bar>
5184 $cc =~ /^\S+\@\S+>/) ||
5186 $ca =~ /<\S+\@\S+$/))
5191 # for asm volatile statements
5192 # ignore a colon with another
5193 # colon immediately before or after
5195 ($ca =~ /:$/ || $cc =~ /^:/)) {
5199 # messages are ERROR, but ?: are CHK
5201 my $msg_level = \&ERROR;
5202 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5204 if (&{$msg_level}("SPACING",
5205 "spaces required around that '$op' $at\n" . $hereptr)) {
5206 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5207 if (defined $fix_elements[$n + 2]) {
5208 $fix_elements[$n + 2] =~ s/^\s+//;
5214 $off += length($elements[$n + 1]);
5216 ## print("n: <$n> GOOD: <$good>\n");
5218 $fixed_line = $fixed_line . $good;
5221 if (($#elements % 2) == 0) {
5222 $fixed_line = $fixed_line . $fix_elements[$#elements];
5225 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5226 $fixed[$fixlinenr] = $fixed_line;
5232 # check for whitespace before a non-naked semicolon
5233 if ($line =~ /^\+.*\S\s+;\s*$/) {
5235 "space prohibited before semicolon\n" . $herecurr) &&
5237 1 while $fixed[$fixlinenr] =~
5238 s/^(\+.*\S)\s+;/$1;/;
5242 # check for multiple assignments
5243 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5244 CHK("MULTIPLE_ASSIGNMENTS",
5245 "multiple assignments should be avoided\n" . $herecurr);
5248 ## # check for multiple declarations, allowing for a function declaration
5250 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5251 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5253 ## # Remove any bracketed sections to ensure we do not
5254 ## # falsely report the parameters of functions.
5256 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5258 ## if ($ln =~ /,/) {
5259 ## WARN("MULTIPLE_DECLARATION",
5260 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5264 #need space before brace following if, while, etc
5265 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5266 $line =~ /\b(?:else|do)\{/) {
5267 if (ERROR("SPACING",
5268 "space required before the open brace '{'\n" . $herecurr) &&
5270 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5274 ## # check for blank lines before declarations
5275 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5276 ## $prevrawline =~ /^.\s*$/) {
5278 ## "No blank lines before declarations\n" . $hereprev);
5282 # closing brace should have a space following it when it has anything
5284 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5285 if (ERROR("SPACING",
5286 "space required after that close brace '}'\n" . $herecurr) &&
5288 $fixed[$fixlinenr] =~
5289 s/}((?!(?:,|;|\)))\S)/} $1/;
5293 # check spacing on square brackets
5294 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5295 if (ERROR("SPACING",
5296 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5298 $fixed[$fixlinenr] =~
5302 if ($line =~ /\s\]/) {
5303 if (ERROR("SPACING",
5304 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5306 $fixed[$fixlinenr] =~
5311 # check spacing on parentheses
5312 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5313 $line !~ /for\s*\(\s+;/) {
5314 if (ERROR("SPACING",
5315 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5317 $fixed[$fixlinenr] =~
5321 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5322 $line !~ /for\s*\(.*;\s+\)/ &&
5323 $line !~ /:\s+\)/) {
5324 if (ERROR("SPACING",
5325 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5327 $fixed[$fixlinenr] =~
5332 # check unnecessary parentheses around addressof/dereference single $Lvals
5333 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5335 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5337 if (CHK("UNNECESSARY_PARENTHESES",
5338 "Unnecessary parentheses around $var\n" . $herecurr) &&
5340 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5344 # check for unnecessary parentheses around function pointer uses
5345 # ie: (foo->bar)(); should be foo->bar();
5346 # but not "if (foo->bar) (" to avoid some false positives
5347 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5349 if (CHK("UNNECESSARY_PARENTHESES",
5350 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5352 my $var2 = deparenthesize($var);
5354 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5358 # check for unnecessary parentheses around comparisons in if uses
5359 # when !drivers/staging or command-line uses --strict
5360 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5361 $perl_version_ok && defined($stat) &&
5362 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5364 my $test = substr($2, 1, -1);
5366 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5368 # avoid parentheses around potential macro args
5369 next if ($match =~ /^\s*\w+\s*$/);
5370 if (!defined($herectx)) {
5371 $herectx = $here . "\n";
5372 my $cnt = statement_rawlines($if_stat);
5373 for (my $n = 0; $n < $cnt; $n++) {
5374 my $rl = raw_line($linenr, $n);
5375 $herectx .= $rl . "\n";
5376 last if $rl =~ /^[ \+].*\{/;
5379 CHK("UNNECESSARY_PARENTHESES",
5380 "Unnecessary parentheses around '$match'\n" . $herectx);
5384 # check that goto labels aren't indented (allow a single space indentation)
5385 # and ignore bitfield definitions like foo:1
5386 # Strictly, labels can have whitespace after the identifier and before the :
5387 # but this is not allowed here as many ?: uses would appear to be labels
5388 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5389 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5390 $sline !~ /^.\s+default:/) {
5391 if (WARN("INDENTED_LABEL",
5392 "labels should not be indented\n" . $herecurr) &&
5394 $fixed[$fixlinenr] =~
5399 # check if a statement with a comma should be two statements like:
5400 # foo = bar(), /* comma should be semicolon */
5402 if (defined($stat) &&
5403 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5404 my $cnt = statement_rawlines($stat);
5405 my $herectx = get_stat_here($linenr, $cnt, $here);
5406 WARN("SUSPECT_COMMA_SEMICOLON",
5407 "Possible comma where semicolon could be used\n" . $herectx);
5410 # return is not a function
5411 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5413 if ($perl_version_ok &&
5414 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5416 $value = deparenthesize($value);
5417 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5418 ERROR("RETURN_PARENTHESES",
5419 "return is not a function, parentheses are not required\n" . $herecurr);
5421 } elsif ($spacing !~ /\s+/) {
5423 "space required before the open parenthesis '('\n" . $herecurr);
5427 # unnecessary return in a void function
5428 # at end-of-function, with the previous line a single leading tab, then return;
5429 # and the line before that not a goto label target like "out:"
5430 if ($sline =~ /^[ \+]}\s*$/ &&
5431 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5433 $lines[$linenr - 3] =~ /^[ +]/ &&
5434 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5436 "void function return statements are not generally useful\n" . $hereprev);
5439 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5440 if ($perl_version_ok &&
5441 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5442 my $openparens = $1;
5443 my $count = $openparens =~ tr@\(@\(@;
5445 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5446 my $comp = $4; #Not $1 because of $LvalOrFunc
5447 $msg = " - maybe == should be = ?" if ($comp eq "==");
5448 WARN("UNNECESSARY_PARENTHESES",
5449 "Unnecessary parentheses$msg\n" . $herecurr);
5453 # comparisons with a constant or upper case identifier on the left
5454 # avoid cases like "foo + BAR < baz"
5455 # only fix matches surrounded by parentheses to avoid incorrect
5456 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5457 if ($perl_version_ok &&
5458 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5463 my $newcomp = $comp;
5464 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5465 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5466 WARN("CONSTANT_COMPARISON",
5467 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5471 } elsif ($comp eq "<=") {
5473 } elsif ($comp eq ">") {
5475 } elsif ($comp eq ">=") {
5478 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5482 # Return of what appears to be an errno should normally be negative
5483 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5485 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5486 WARN("USE_NEGATIVE_ERRNO",
5487 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5491 # Need a space before open parenthesis after if, while etc
5492 if ($line =~ /\b(if|while|for|switch)\(/) {
5493 if (ERROR("SPACING",
5494 "space required before the open parenthesis '('\n" . $herecurr) &&
5496 $fixed[$fixlinenr] =~
5497 s/\b(if|while|for|switch)\(/$1 \(/;
5501 # Check for illegal assignment in if conditional -- and check for trailing
5502 # statements after the conditional.
5503 if ($line =~ /do\s*(?!{)/) {
5504 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5505 ctx_statement_block($linenr, $realcnt, 0)
5506 if (!defined $stat);
5507 my ($stat_next) = ctx_statement_block($line_nr_next,
5508 $remain_next, $off_next);
5509 $stat_next =~ s/\n./\n /g;
5510 ##print "stat<$stat> stat_next<$stat_next>\n";
5512 if ($stat_next =~ /^\s*while\b/) {
5513 # If the statement carries leading newlines,
5514 # then count those as offsets.
5516 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5518 statement_rawlines($whitespace) - 1;
5520 $suppress_whiletrailers{$line_nr_next +
5524 if (!defined $suppress_whiletrailers{$linenr} &&
5525 defined($stat) && defined($cond) &&
5526 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5527 my ($s, $c) = ($stat, $cond);
5529 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5530 if (ERROR("ASSIGN_IN_IF",
5531 "do not use assignment in if condition\n" . $herecurr) &&
5532 $fix && $perl_version_ok) {
5533 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5541 fix_delete_line($fixlinenr, $rawline);
5542 fix_insert_line($fixlinenr, "$space$statement;");
5543 my $newline = "${space}if (";
5544 $newline .= '!' if defined($not);
5545 $newline .= '(' if (defined $not && defined($test) && defined($against));
5546 $newline .= "$assigned";
5547 $newline .= " $test $against" if (defined($test) && defined($against));
5548 $newline .= ')' if (defined $not && defined($test) && defined($against));
5550 $newline .= " {" if (defined($brace));
5551 fix_insert_line($fixlinenr + 1, $newline);
5556 # Find out what is on the end of the line after the
5558 substr($s, 0, length($c), '');
5560 $s =~ s/$;//g; # Remove any comments
5561 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5562 $c !~ /}\s*while\s*/)
5564 # Find out how long the conditional actually is.
5565 my @newlines = ($c =~ /\n/gs);
5566 my $cond_lines = 1 + $#newlines;
5569 $stat_real = raw_line($linenr, $cond_lines)
5570 . "\n" if ($cond_lines);
5571 if (defined($stat_real) && $cond_lines > 1) {
5572 $stat_real = "[...]\n$stat_real";
5575 ERROR("TRAILING_STATEMENTS",
5576 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5580 # Check for bitwise tests written as boolean
5592 WARN("HEXADECIMAL_BOOLEAN_TEST",
5593 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5596 # if and else should not have general statements after it
5597 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5599 $s =~ s/$;//g; # Remove any comments
5600 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5601 ERROR("TRAILING_STATEMENTS",
5602 "trailing statements should be on next line\n" . $herecurr);
5605 # if should not continue a brace
5606 if ($line =~ /}\s*if\b/) {
5607 ERROR("TRAILING_STATEMENTS",
5608 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5611 # case and default should not have general statements after them
5612 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5614 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5618 ERROR("TRAILING_STATEMENTS",
5619 "trailing statements should be on next line\n" . $herecurr);
5622 # Check for }<nl>else {, these must be at the same
5623 # indent level to be relevant to each other.
5624 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5625 $previndent == $indent) {
5626 if (ERROR("ELSE_AFTER_BRACE",
5627 "else should follow close brace '}'\n" . $hereprev) &&
5628 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5629 fix_delete_line($fixlinenr - 1, $prevrawline);
5630 fix_delete_line($fixlinenr, $rawline);
5631 my $fixedline = $prevrawline;
5632 $fixedline =~ s/}\s*$//;
5633 if ($fixedline !~ /^\+\s*$/) {
5634 fix_insert_line($fixlinenr, $fixedline);
5636 $fixedline = $rawline;
5637 $fixedline =~ s/^(.\s*)else/$1} else/;
5638 fix_insert_line($fixlinenr, $fixedline);
5642 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5643 $previndent == $indent) {
5644 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5646 # Find out what is on the end of the line after the
5648 substr($s, 0, length($c), '');
5651 if ($s =~ /^\s*;/) {
5652 if (ERROR("WHILE_AFTER_BRACE",
5653 "while should follow close brace '}'\n" . $hereprev) &&
5654 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5655 fix_delete_line($fixlinenr - 1, $prevrawline);
5656 fix_delete_line($fixlinenr, $rawline);
5657 my $fixedline = $prevrawline;
5658 my $trailing = $rawline;
5659 $trailing =~ s/^\+//;
5660 $trailing = trim($trailing);
5661 $fixedline =~ s/}\s*$/} $trailing/;
5662 fix_insert_line($fixlinenr, $fixedline);
5667 #Specific variable tests
5668 while ($line =~ m{($Constant|$Lval)}g) {
5672 if ($var !~ /^$Constant$/ &&
5673 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5674 #Ignore some autogenerated defines and enum values
5675 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5676 #Ignore Page<foo> variants
5677 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5678 #Ignore SI style variants like nS, mV and dB
5679 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5680 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5681 #Ignore some three character SI units explicitly, like MiB and KHz
5682 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5683 while ($var =~ m{($Ident)}g) {
5685 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5687 seed_camelcase_includes();
5688 if (!$file && !$camelcase_file_seeded) {
5689 seed_camelcase_file($realfile);
5690 $camelcase_file_seeded = 1;
5693 if (!defined $camelcase{$word}) {
5694 $camelcase{$word} = 1;
5696 "Avoid CamelCase: <$word>\n" . $herecurr);
5702 #no spaces allowed after \ in define
5703 if ($line =~ /\#\s*define.*\\\s+$/) {
5704 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5705 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5707 $fixed[$fixlinenr] =~ s/\s+$//;
5711 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5712 # itself <asm/foo.h> (uses RAW line)
5713 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5715 my $checkfile = "include/linux/$file";
5716 if (-f "$root/$checkfile" &&
5717 $realfile ne $checkfile &&
5718 $1 !~ /$allowed_asm_includes/)
5720 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5721 if ($asminclude > 0) {
5722 if ($realfile =~ m{^arch/}) {
5723 CHK("ARCH_INCLUDE_LINUX",
5724 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5726 WARN("INCLUDE_LINUX",
5727 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5733 # multi-statement macros should be enclosed in a do while loop, grab the
5734 # first statement and ensure its the whole macro if its not enclosed
5735 # in a known good container
5736 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5737 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5740 my ($off, $dstat, $dcond, $rest);
5742 my $has_flow_statement = 0;
5743 my $has_arg_concat = 0;
5744 ($dstat, $dcond, $ln, $cnt, $off) =
5745 ctx_statement_block($linenr, $realcnt, 0);
5747 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5748 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5750 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5751 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5753 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5754 my $define_args = $1;
5755 my $define_stmt = $dstat;
5758 if (defined $define_args && $define_args ne "") {
5759 $define_args = substr($define_args, 1, length($define_args) - 2);
5760 $define_args =~ s/\s*//g;
5761 $define_args =~ s/\\\+?//g;
5762 @def_args = split(",", $define_args);
5766 $dstat =~ s/\\\n.//g;
5767 $dstat =~ s/^\s*//s;
5768 $dstat =~ s/\s*$//s;
5770 # Flatten any parentheses and braces
5771 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5772 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5773 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5777 # Flatten any obvious string concatenation.
5778 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5779 $dstat =~ s/$Ident\s*($String)/$1/)
5783 # Make asm volatile uses seem like a generic function
5784 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5786 my $exceptions = qr{
5799 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5802 my $stmt_cnt = statement_rawlines($ctx);
5803 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5806 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5807 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5808 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5809 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5810 $dstat !~ /$exceptions/ &&
5811 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5812 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5813 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5814 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5815 $dstat !~ /^for\s*$Constant$/ && # for (...)
5816 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5817 $dstat !~ /^do\s*{/ && # do {...
5818 $dstat !~ /^\(\{/ && # ({...
5819 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5821 if ($dstat =~ /^\s*if\b/) {
5822 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5823 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5824 } elsif ($dstat =~ /;/) {
5825 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5826 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5828 ERROR("COMPLEX_MACRO",
5829 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5834 # Make $define_stmt single line, comment-free, etc
5835 my @stmt_array = split('\n', $define_stmt);
5838 foreach my $l (@stmt_array) {
5843 } elsif ($l =~ /^[\+ ]/) {
5844 $define_stmt .= substr($l, 1);
5847 $define_stmt =~ s/$;//g;
5848 $define_stmt =~ s/\s+/ /g;
5849 $define_stmt = trim($define_stmt);
5851 # check if any macro arguments are reused (ignore '...' and 'type')
5852 foreach my $arg (@def_args) {
5853 next if ($arg =~ /\.\.\./);
5854 next if ($arg =~ /^type$/i);
5855 my $tmp_stmt = $define_stmt;
5856 $tmp_stmt =~ s/\b(__must_be_array|offsetof|sizeof|sizeof_field|__stringify|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5857 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5858 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5859 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5861 CHK("MACRO_ARG_REUSE",
5862 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5864 # check if any macro arguments may have other precedence issues
5865 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5866 ((defined($1) && $1 ne ',') ||
5867 (defined($2) && $2 ne ','))) {
5868 CHK("MACRO_ARG_PRECEDENCE",
5869 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5873 # check for macros with flow control, but without ## concatenation
5874 # ## concatenation is commonly a macro that defines a function so ignore those
5875 if ($has_flow_statement && !$has_arg_concat) {
5876 my $cnt = statement_rawlines($ctx);
5877 my $herectx = get_stat_here($linenr, $cnt, $here);
5879 WARN("MACRO_WITH_FLOW_CONTROL",
5880 "Macros with flow control statements should be avoided\n" . "$herectx");
5883 # check for line continuations outside of #defines, preprocessor #, and asm
5886 if ($prevline !~ /^..*\\$/ &&
5887 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5888 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5889 $line =~ /^\+.*\\$/) {
5890 WARN("LINE_CONTINUATIONS",
5891 "Avoid unnecessary line continuations\n" . $herecurr);
5895 # do {} while (0) macro tests:
5896 # single-statement macros do not need to be enclosed in do while (0) loop,
5897 # macro should not end with a semicolon
5898 if ($perl_version_ok &&
5899 $realfile !~ m@/vmlinux.lds.h$@ &&
5900 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5903 my ($off, $dstat, $dcond, $rest);
5905 ($dstat, $dcond, $ln, $cnt, $off) =
5906 ctx_statement_block($linenr, $realcnt, 0);
5909 $dstat =~ s/\\\n.//g;
5912 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5917 my $cnt = statement_rawlines($ctx);
5918 my $herectx = get_stat_here($linenr, $cnt, $here);
5920 if (($stmts =~ tr/;/;/) == 1 &&
5921 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5922 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5923 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5925 if (defined $semis && $semis ne "") {
5926 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5927 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5929 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5931 my $cnt = statement_rawlines($ctx);
5932 my $herectx = get_stat_here($linenr, $cnt, $here);
5934 WARN("TRAILING_SEMICOLON",
5935 "macros should not use a trailing semicolon\n" . "$herectx");
5939 # check for redundant bracing round if etc
5940 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5941 my ($level, $endln, @chunks) =
5942 ctx_statement_full($linenr, $realcnt, 1);
5943 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5944 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5945 if ($#chunks > 0 && $level == 0) {
5949 my $herectx = $here . "\n";
5950 my $ln = $linenr - 1;
5951 for my $chunk (@chunks) {
5952 my ($cond, $block) = @{$chunk};
5954 # If the condition carries leading newlines, then count those as offsets.
5955 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5956 my $offset = statement_rawlines($whitespace) - 1;
5958 $allowed[$allow] = 0;
5959 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5961 # We have looked at and allowed this specific line.
5962 $suppress_ifbraces{$ln + $offset} = 1;
5964 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5965 $ln += statement_rawlines($block) - 1;
5967 substr($block, 0, length($cond), '');
5969 $seen++ if ($block =~ /^\s*{/);
5971 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5972 if (statement_lines($cond) > 1) {
5973 #print "APW: ALLOWED: cond<$cond>\n";
5974 $allowed[$allow] = 1;
5976 if ($block =~/\b(?:if|for|while)\b/) {
5977 #print "APW: ALLOWED: block<$block>\n";
5978 $allowed[$allow] = 1;
5980 if (statement_block_size($block) > 1) {
5981 #print "APW: ALLOWED: lines block<$block>\n";
5982 $allowed[$allow] = 1;
5987 my $sum_allowed = 0;
5988 foreach (@allowed) {
5991 if ($sum_allowed == 0) {
5993 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5994 } elsif ($sum_allowed != $allow &&
5997 "braces {} should be used on all arms of this statement\n" . $herectx);
6002 if (!defined $suppress_ifbraces{$linenr - 1} &&
6003 $line =~ /\b(if|while|for|else)\b/) {
6006 # Check the pre-context.
6007 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6008 #print "APW: ALLOWED: pre<$1>\n";
6012 my ($level, $endln, @chunks) =
6013 ctx_statement_full($linenr, $realcnt, $-[0]);
6015 # Check the condition.
6016 my ($cond, $block) = @{$chunks[0]};
6017 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6018 if (defined $cond) {
6019 substr($block, 0, length($cond), '');
6021 if (statement_lines($cond) > 1) {
6022 #print "APW: ALLOWED: cond<$cond>\n";
6025 if ($block =~/\b(?:if|for|while)\b/) {
6026 #print "APW: ALLOWED: block<$block>\n";
6029 if (statement_block_size($block) > 1) {
6030 #print "APW: ALLOWED: lines block<$block>\n";
6033 # Check the post-context.
6034 if (defined $chunks[1]) {
6035 my ($cond, $block) = @{$chunks[1]};
6036 if (defined $cond) {
6037 substr($block, 0, length($cond), '');
6039 if ($block =~ /^\s*\{/) {
6040 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6044 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6045 my $cnt = statement_rawlines($block);
6046 my $herectx = get_stat_here($linenr, $cnt, $here);
6049 "braces {} are not necessary for single statement blocks\n" . $herectx);
6053 # check for single line unbalanced braces
6054 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6055 $sline =~ /^.\s*else\s*\{\s*$/) {
6056 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6059 # check for unnecessary blank lines around braces
6060 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6062 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6063 $fix && $prevrawline =~ /^\+/) {
6064 fix_delete_line($fixlinenr - 1, $prevrawline);
6067 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6069 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6071 fix_delete_line($fixlinenr, $rawline);
6075 # no volatiles please
6076 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6077 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6079 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6082 # Check for user-visible strings broken across lines, which breaks the ability
6083 # to grep for the string. Make exceptions when the previous string ends in a
6084 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6085 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6086 if ($line =~ /^\+\s*$String/ &&
6087 $prevline =~ /"\s*$/ &&
6088 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6089 if (WARN("SPLIT_STRING",
6090 "quoted string split across lines\n" . $hereprev) &&
6092 $prevrawline =~ /^\+.*"\s*$/ &&
6093 $last_coalesced_string_linenr != $linenr - 1) {
6094 my $extracted_string = get_quoted_string($line, $rawline);
6095 my $comma_close = "";
6096 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6100 fix_delete_line($fixlinenr - 1, $prevrawline);
6101 fix_delete_line($fixlinenr, $rawline);
6102 my $fixedline = $prevrawline;
6103 $fixedline =~ s/"\s*$//;
6104 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6105 fix_insert_line($fixlinenr - 1, $fixedline);
6106 $fixedline = $rawline;
6107 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6108 if ($fixedline !~ /\+\s*$/) {
6109 fix_insert_line($fixlinenr, $fixedline);
6111 $last_coalesced_string_linenr = $linenr;
6115 # check for missing a space in a string concatenation
6116 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6117 WARN('MISSING_SPACE',
6118 "break quoted strings at a space character\n" . $hereprev);
6121 # check for an embedded function name in a string when the function is known
6122 # This does not work very well for -f --file checking as it depends on patch
6123 # context providing the function name or a single line form for in-file
6124 # function declarations
6125 if ($line =~ /^\+.*$String/ &&
6126 defined($context_function) &&
6127 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6128 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6129 WARN("EMBEDDED_FUNCTION_NAME",
6130 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6133 # check for unnecessary function tracing like uses
6134 # This does not use $logFunctions because there are many instances like
6135 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6136 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6137 if (WARN("TRACING_LOGGING",
6138 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6140 fix_delete_line($fixlinenr, $rawline);
6144 # check for spaces before a quoted newline
6145 if ($rawline =~ /^.*\".*\s\\n/) {
6146 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6147 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6149 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6154 # concatenated string without spaces between elements
6155 if ($line =~ /$String[A-Z_]/ ||
6156 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6157 if (CHK("CONCATENATED_STRING",
6158 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6160 while ($line =~ /($String)/g) {
6161 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6162 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6163 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6168 # uncoalesced string fragments
6169 if ($line =~ /$String\s*[Lu]?"/) {
6170 if (WARN("STRING_FRAGMENTS",
6171 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6173 while ($line =~ /($String)(?=\s*")/g) {
6174 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6175 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6180 # check for non-standard and hex prefixed decimal printf formats
6181 my $show_L = 1; #don't show the same defect twice
6183 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6184 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6185 $string =~ s/%%/__/g;
6187 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6189 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6193 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6195 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6198 # check for 0x<decimal>
6199 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6200 ERROR("PRINTF_0XDECIMAL",
6201 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6205 # check for line continuations in quoted strings with odd counts of "
6206 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6207 WARN("LINE_CONTINUATIONS",
6208 "Avoid line continuations in quoted strings\n" . $herecurr);
6212 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6214 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6218 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6220 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6223 # check for needless "if (<foo>) fn(<foo>)" uses
6224 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6225 my $tested = quotemeta($1);
6226 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6227 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6229 if (WARN('NEEDLESS_IF',
6230 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6233 my $leading_tabs = "";
6234 my $new_leading_tabs = "";
6235 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6240 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6241 $new_leading_tabs = $1;
6242 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6249 fix_delete_line($fixlinenr - 1, $prevrawline);
6250 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6256 # check for unnecessary "Out of Memory" messages
6257 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6258 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6259 (defined $1 || defined $3) &&
6262 my $testline = $lines[$linenr - 3];
6264 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6265 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6267 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6268 $s !~ /\b__GFP_NOWARN\b/ ) {
6270 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6274 # check for logging functions with KERN_<LEVEL>
6275 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6276 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6278 if (WARN("UNNECESSARY_KERN_LEVEL",
6279 "Possible unnecessary $level\n" . $herecurr) &&
6281 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6285 # check for logging continuations
6286 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6287 WARN("LOGGING_CONTINUATION",
6288 "Avoid logging continuation uses where feasible\n" . $herecurr);
6291 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6292 if (defined $stat &&
6293 $line =~ /\b$logFunctions\s*\(/ &&
6294 index($stat, '"') >= 0) {
6295 my $lc = $stat =~ tr@\n@@;
6296 $lc = $lc + $linenr;
6297 my $stat_real = get_stat_real($linenr, $lc);
6298 pos($stat_real) = index($stat_real, '"');
6299 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6302 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6303 if (WARN("UNNECESSARY_MODIFIER",
6304 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6305 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6308 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6313 # check for mask then right shift without a parentheses
6314 if ($perl_version_ok &&
6315 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6316 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6317 WARN("MASK_THEN_SHIFT",
6318 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6321 # check for pointer comparisons to NULL
6322 if ($perl_version_ok) {
6323 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6326 $equal = "" if ($4 eq "!=");
6327 if (CHK("COMPARISON_TO_NULL",
6328 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6330 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6335 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6336 if ($line =~ /(\b$InitAttribute\b)/) {
6338 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6341 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6342 ERROR("MISPLACED_INIT",
6343 "$attr should be placed after $var\n" . $herecurr)) ||
6344 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6345 WARN("MISPLACED_INIT",
6346 "$attr should be placed after $var\n" . $herecurr))) &&
6348 $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;
6353 # check for $InitAttributeData (ie: __initdata) with const
6354 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6356 $attr =~ /($InitAttributePrefix)(.*)/;
6357 my $attr_prefix = $1;
6359 if (ERROR("INIT_ATTRIBUTE",
6360 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6362 $fixed[$fixlinenr] =~
6363 s/$InitAttributeData/${attr_prefix}initconst/;
6367 # check for $InitAttributeConst (ie: __initconst) without const
6368 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6370 if (ERROR("INIT_ATTRIBUTE",
6371 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6373 my $lead = $fixed[$fixlinenr] =~
6374 /(^\+\s*(?:static\s+))/;
6376 $lead = "$lead " if ($lead !~ /^\+$/);
6377 $lead = "${lead}const ";
6378 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6382 # check for __read_mostly with const non-pointer (should just be const)
6383 if ($line =~ /\b__read_mostly\b/ &&
6384 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6385 if (ERROR("CONST_READ_MOSTLY",
6386 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6388 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6392 # don't use __constant_<foo> functions outside of include/uapi/
6393 if ($realfile !~ m@^include/uapi/@ &&
6394 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6395 my $constant_func = $1;
6396 my $func = $constant_func;
6397 $func =~ s/^__constant_//;
6398 if (WARN("CONSTANT_CONVERSION",
6399 "$constant_func should be $func\n" . $herecurr) &&
6401 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6405 # prefer usleep_range over udelay
6406 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6408 # ignore udelay's < 10, however
6409 if (! ($delay < 10) ) {
6411 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6413 if ($delay > 2000) {
6415 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6419 # warn about unexpectedly long msleep's
6420 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6423 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6427 # check for comparisons of jiffies
6428 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6429 WARN("JIFFIES_COMPARISON",
6430 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6433 # check for comparisons of get_jiffies_64()
6434 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6435 WARN("JIFFIES_COMPARISON",
6436 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6439 # warn about #ifdefs in C files
6440 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6441 # print "#ifdef in C files should be avoided\n";
6442 # print "$herecurr";
6446 # warn about spacing in #ifdefs
6447 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6448 if (ERROR("SPACING",
6449 "exactly one space required after that #$1\n" . $herecurr) &&
6451 $fixed[$fixlinenr] =~
6452 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6457 # check for spinlock_t definitions without a comment.
6458 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6459 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6461 if (!ctx_has_comment($first_line, $linenr)) {
6462 CHK("UNCOMMENTED_DEFINITION",
6463 "$1 definition without comment\n" . $herecurr);
6466 # check for memory barriers without a comment.
6473 my $barrier_stems = qr{
6481 my $all_barriers = qr{
6483 smp_(?:$barrier_stems)|
6484 virt_(?:$barrier_stems)
6487 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6488 if (!ctx_has_comment($first_line, $linenr)) {
6489 WARN("MEMORY_BARRIER",
6490 "memory barrier without comment\n" . $herecurr);
6494 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6496 if ($realfile !~ m@^include/asm-generic/@ &&
6497 $realfile !~ m@/barrier\.h$@ &&
6498 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6499 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6500 WARN("MEMORY_BARRIER",
6501 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6504 # check for waitqueue_active without a comment.
6505 if ($line =~ /\bwaitqueue_active\s*\(/) {
6506 if (!ctx_has_comment($first_line, $linenr)) {
6507 WARN("WAITQUEUE_ACTIVE",
6508 "waitqueue_active without comment\n" . $herecurr);
6512 # check for data_race without a comment.
6513 if ($line =~ /\bdata_race\s*\(/) {
6514 if (!ctx_has_comment($first_line, $linenr)) {
6516 "data_race without comment\n" . $herecurr);
6520 # check of hardware specific defines
6521 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6523 "architecture specific defines should be avoided\n" . $herecurr);
6526 # check that the storage class is not after a type
6527 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6528 WARN("STORAGE_CLASS",
6529 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6531 # Check that the storage class is at the beginning of a declaration
6532 if ($line =~ /\b$Storage\b/ &&
6533 $line !~ /^.\s*$Storage/ &&
6534 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6535 $1 !~ /[\,\)]\s*$/) {
6536 WARN("STORAGE_CLASS",
6537 "storage class should be at the beginning of the declaration\n" . $herecurr);
6540 # check the location of the inline attribute, that it is between
6541 # storage class and type.
6542 if ($line =~ /\b$Type\s+$Inline\b/ ||
6543 $line =~ /\b$Inline\s+$Storage\b/) {
6544 ERROR("INLINE_LOCATION",
6545 "inline keyword should sit between storage class and type\n" . $herecurr);
6548 # Check for __inline__ and __inline, prefer inline
6549 if ($realfile !~ m@\binclude/uapi/@ &&
6550 $line =~ /\b(__inline__|__inline)\b/) {
6552 "plain inline is preferred over $1\n" . $herecurr) &&
6554 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6559 # Check for compiler attributes
6560 if ($realfile !~ m@\binclude/uapi/@ &&
6561 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6563 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6566 "alias" => "__alias",
6567 "aligned" => "__aligned",
6568 "always_inline" => "__always_inline",
6569 "assume_aligned" => "__assume_aligned",
6571 "const" => "__attribute_const__",
6573 "designated_init" => "__designated_init",
6574 "externally_visible" => "__visible",
6575 "format" => "printf|scanf",
6576 "gnu_inline" => "__gnu_inline",
6577 "malloc" => "__malloc",
6579 "no_caller_saved_registers" => "__no_caller_saved_registers",
6580 "noclone" => "__noclone",
6581 "noinline" => "noinline",
6582 "nonstring" => "__nonstring",
6583 "noreturn" => "__noreturn",
6584 "packed" => "__packed",
6586 "section" => "__section",
6591 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6594 $params = $2 if defined($2);
6595 my $curr_attr = $orig_attr;
6596 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6597 if (exists($attr_list{$curr_attr})) {
6598 my $new = $attr_list{$curr_attr};
6599 if ($curr_attr eq "format" && $params) {
6600 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6603 $new = "$new$params";
6605 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6606 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6608 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6609 $fixed[$fixlinenr] =~ s/$remove//;
6610 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6611 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6612 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6617 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6618 if ($attr =~ /^_*unused/) {
6619 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6620 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6624 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6625 if ($perl_version_ok &&
6626 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6627 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6628 $line =~ /\b__weak\b/)) {
6629 ERROR("WEAK_DECLARATION",
6630 "Using weak declarations can have unintended link defects\n" . $herecurr);
6633 # check for c99 types like uint8_t used outside of uapi/ and tools/
6634 if ($realfile !~ m@\binclude/uapi/@ &&
6635 $realfile !~ m@\btools/@ &&
6636 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6638 if ($type =~ /\b($typeC99Typedefs)\b/) {
6640 my $kernel_type = 'u';
6641 $kernel_type = 's' if ($type =~ /^_*[si]/);
6644 if (CHK("PREFER_KERNEL_TYPES",
6645 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6647 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6652 # check for cast of C90 native int or longer types constants
6653 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6657 my $newconst = $const;
6658 $newconst =~ s/${Int_type}$//;
6659 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6660 if ($cast =~ /\blong\s+long\b/) {
6662 } elsif ($cast =~ /\blong\b/) {
6665 if (WARN("TYPECAST_INT_CONSTANT",
6666 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6668 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6672 # check for sizeof(&)
6673 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6674 WARN("SIZEOF_ADDRESS",
6675 "sizeof(& should be avoided\n" . $herecurr);
6678 # check for sizeof without parenthesis
6679 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6680 if (WARN("SIZEOF_PARENTHESIS",
6681 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6683 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6687 # check for struct spinlock declarations
6688 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6689 WARN("USE_SPINLOCK_T",
6690 "struct spinlock should be spinlock_t\n" . $herecurr);
6693 # check for seq_printf uses that could be seq_puts
6694 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6695 my $fmt = get_quoted_string($line, $rawline);
6698 if (WARN("PREFER_SEQ_PUTS",
6699 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6701 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6706 # check for vsprintf extension %p<foo> misuses
6707 if ($perl_version_ok &&
6709 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6710 $1 !~ /^_*volatile_*$/) {
6713 my $lc = $stat =~ tr@\n@@;
6714 $lc = $lc + $linenr;
6715 for (my $count = $linenr; $count <= $lc; $count++) {
6719 my $bad_specifier = "";
6720 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6723 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6727 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6728 ($extension eq "f" &&
6729 defined $qualifier && $qualifier !~ /^w/) ||
6730 ($extension eq "4" &&
6731 defined $qualifier && $qualifier !~ /^cc/)) {
6732 $bad_specifier = $specifier;
6735 if ($extension eq "x" && !defined($stat_real)) {
6736 if (!defined($stat_real)) {
6737 $stat_real = get_stat_real($linenr, $lc);
6739 WARN("VSPRINTF_SPECIFIER_PX",
6740 "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");
6743 if ($bad_specifier ne "") {
6744 my $stat_real = get_stat_real($linenr, $lc);
6745 my $ext_type = "Invalid";
6747 if ($bad_specifier =~ /p[Ff]/) {
6748 $use = " - use %pS instead";
6749 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6752 WARN("VSPRINTF_POINTER_EXTENSION",
6753 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6758 # Check for misused memsets
6759 if ($perl_version_ok &&
6761 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6767 if ($ms_size =~ /^(0x|)0$/i) {
6769 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6770 } elsif ($ms_size =~ /^(0x|)1$/i) {
6772 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6776 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6777 # if ($perl_version_ok &&
6779 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6780 # if (WARN("PREFER_ETHER_ADDR_COPY",
6781 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6783 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6787 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6788 # if ($perl_version_ok &&
6790 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6791 # WARN("PREFER_ETHER_ADDR_EQUAL",
6792 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6795 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6796 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6797 # if ($perl_version_ok &&
6799 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6803 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6804 # if (WARN("PREFER_ETH_ZERO_ADDR",
6805 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6807 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6809 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6810 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6811 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6813 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6818 # strlcpy uses that should likely be strscpy
6819 if ($line =~ /\bstrlcpy\s*\(/) {
6821 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6824 # typecasts on min/max could be min_t/max_t
6825 if ($perl_version_ok &&
6827 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6828 if (defined $2 || defined $7) {
6830 my $cast1 = deparenthesize($2);
6832 my $cast2 = deparenthesize($7);
6836 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6837 $cast = "$cast1 or $cast2";
6838 } elsif ($cast1 ne "") {
6844 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6848 # check usleep_range arguments
6849 if ($perl_version_ok &&
6851 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6855 WARN("USLEEP_RANGE",
6856 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6857 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6859 WARN("USLEEP_RANGE",
6860 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6864 # check for naked sscanf
6865 if ($perl_version_ok &&
6867 $line =~ /\bsscanf\b/ &&
6868 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6869 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6870 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6871 my $lc = $stat =~ tr@\n@@;
6872 $lc = $lc + $linenr;
6873 my $stat_real = get_stat_real($linenr, $lc);
6874 WARN("NAKED_SSCANF",
6875 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6878 # check for simple sscanf that should be kstrto<foo>
6879 if ($perl_version_ok &&
6881 $line =~ /\bsscanf\b/) {
6882 my $lc = $stat =~ tr@\n@@;
6883 $lc = $lc + $linenr;
6884 my $stat_real = get_stat_real($linenr, $lc);
6885 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6887 my $count = $format =~ tr@%@%@;
6889 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6890 WARN("SSCANF_TO_KSTRTO",
6891 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6896 # check for new externs in .h files.
6897 if ($realfile =~ /\.h$/ &&
6898 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6899 if (CHK("AVOID_EXTERNS",
6900 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6902 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6906 # check for new externs in .c files.
6907 if ($realfile =~ /\.c$/ && defined $stat &&
6908 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6910 my $function_name = $1;
6911 my $paren_space = $2;
6914 if (defined $cond) {
6915 substr($s, 0, length($cond), '');
6919 WARN("AVOID_EXTERNS",
6920 "externs should be avoided in .c files\n" . $herecurr);
6923 if ($paren_space =~ /\n/) {
6924 WARN("FUNCTION_ARGUMENTS",
6925 "arguments for function declarations should follow identifier\n" . $herecurr);
6928 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6929 $stat =~ /^.\s*extern\s+/)
6931 WARN("AVOID_EXTERNS",
6932 "externs should be avoided in .c files\n" . $herecurr);
6935 # check for function declarations that have arguments without identifier names
6936 if (defined $stat &&
6937 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6939 my $args = trim($1);
6940 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6942 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6943 WARN("FUNCTION_ARGUMENTS",
6944 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6949 # check for function definitions
6950 if ($perl_version_ok &&
6952 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6953 $context_function = $1;
6955 # check for multiline function definition with misplaced open brace
6957 my $cnt = statement_rawlines($stat);
6958 my $herectx = $here . "\n";
6959 for (my $n = 0; $n < $cnt; $n++) {
6960 my $rl = raw_line($linenr, $n);
6961 $herectx .= $rl . "\n";
6962 $ok = 1 if ($rl =~ /^[ \+]\{/);
6963 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6964 last if $rl =~ /^[ \+].*\{/;
6968 "open brace '{' following function definitions go on the next line\n" . $herectx);
6972 # checks for new __setup's
6973 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6976 if (!grep(/$name/, @setup_docs)) {
6977 CHK("UNDOCUMENTED_SETUP",
6978 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6982 # check for pointless casting of alloc functions
6983 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6984 WARN("UNNECESSARY_CASTS",
6985 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6989 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6990 if ($perl_version_ok &&
6991 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6992 CHK("ALLOC_SIZEOF_STRUCT",
6993 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6996 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6997 if ($perl_version_ok &&
6999 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7003 my $newfunc = "kmalloc_array";
7004 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7007 if ($a1 =~ /^sizeof\s*\S/) {
7011 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7012 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7013 my $cnt = statement_rawlines($stat);
7014 my $herectx = get_stat_here($linenr, $cnt, $here);
7016 if (WARN("ALLOC_WITH_MULTIPLY",
7017 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7020 $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;
7025 # check for krealloc arg reuse
7026 if ($perl_version_ok &&
7027 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7029 WARN("KREALLOC_ARG_REUSE",
7030 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7033 # check for alloc argument mismatch
7034 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7035 WARN("ALLOC_ARRAY_ARGS",
7036 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7039 # check for multiple semicolons
7040 if ($line =~ /;\s*;\s*$/) {
7041 if (WARN("ONE_SEMICOLON",
7042 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7044 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7048 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7049 if ($realfile !~ m@^include/uapi/@ &&
7050 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7052 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7053 if (CHK("BIT_MACRO",
7054 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7056 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7060 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7061 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7062 WARN("IS_ENABLED_CONFIG",
7063 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7066 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7067 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7069 if (WARN("PREFER_IS_ENABLED",
7070 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7072 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7076 # check for /* fallthrough */ like comment, prefer fallthrough;
7077 my @fallthroughs = (
7080 'lint -fallthrough[ \t]*',
7081 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7082 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7083 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7084 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7086 if ($raw_comment ne '') {
7087 foreach my $ft (@fallthroughs) {
7088 if ($raw_comment =~ /$ft/) {
7089 my $msg_level = \&WARN;
7090 $msg_level = \&CHK if ($file);
7091 &{$msg_level}("PREFER_FALLTHROUGH",
7092 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7098 # check for switch/default statements without a break;
7099 if ($perl_version_ok &&
7101 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7102 my $cnt = statement_rawlines($stat);
7103 my $herectx = get_stat_here($linenr, $cnt, $here);
7105 WARN("DEFAULT_NO_BREAK",
7106 "switch default: should use break\n" . $herectx);
7109 # check for gcc specific __FUNCTION__
7110 if ($line =~ /\b__FUNCTION__\b/) {
7111 if (WARN("USE_FUNC",
7112 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7114 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7118 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7119 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7121 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7124 # check for use of yield()
7125 if ($line =~ /\byield\s*\(\s*\)/) {
7127 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7130 # check for comparisons against true and false
7131 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7139 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7141 my $type = lc($otype);
7142 if ($type =~ /^(?:true|false)$/) {
7143 if (("$test" eq "==" && "$type" eq "true") ||
7144 ("$test" eq "!=" && "$type" eq "false")) {
7148 CHK("BOOL_COMPARISON",
7149 "Using comparison to $otype is error prone\n" . $herecurr);
7151 ## maybe suggesting a correct construct would better
7152 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7157 # check for semaphores initialized locked
7158 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7159 WARN("CONSIDER_COMPLETION",
7160 "consider using a completion\n" . $herecurr);
7163 # recommend kstrto* over simple_strto* and strict_strto*
7164 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7165 WARN("CONSIDER_KSTRTO",
7166 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7169 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7170 if ($line =~ /^.\s*__initcall\s*\(/) {
7171 WARN("USE_DEVICE_INITCALL",
7172 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7175 # check for spin_is_locked(), suggest lockdep instead
7176 if ($line =~ /\bspin_is_locked\(/) {
7178 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7181 # check for deprecated apis
7182 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7183 my $deprecated_api = $1;
7184 my $new_api = $deprecated_apis{$deprecated_api};
7185 WARN("DEPRECATED_API",
7186 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7189 # check for various structs that are normally const (ops, kgdb, device_tree)
7190 # and avoid what seem like struct definitions 'struct foo {'
7191 if (defined($const_structs) &&
7192 $line !~ /\bconst\b/ &&
7193 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7194 WARN("CONST_STRUCT",
7195 "struct $1 should normally be const\n" . $herecurr);
7198 # use of NR_CPUS is usually wrong
7199 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7200 # ignore designated initializers using NR_CPUS
7201 if ($line =~ /\bNR_CPUS\b/ &&
7202 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7203 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7204 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7205 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7206 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7207 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7210 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7213 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7214 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7215 ERROR("DEFINE_ARCH_HAS",
7216 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7219 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7220 if ($perl_version_ok &&
7221 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7222 WARN("LIKELY_MISUSE",
7223 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7226 # return sysfs_emit(foo, fmt, ...) fmt without newline
7227 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7228 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7229 my $offset = $+[6] - 1;
7230 if (WARN("SYSFS_EMIT",
7231 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7233 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7237 # nested likely/unlikely calls
7238 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7239 WARN("LIKELY_MISUSE",
7240 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7243 # whine mightly about in_atomic
7244 if ($line =~ /\bin_atomic\s*\(/) {
7245 if ($realfile =~ m@^drivers/@) {
7247 "do not use in_atomic in drivers\n" . $herecurr);
7248 } elsif ($realfile !~ m@^kernel/@) {
7250 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7254 # check for lockdep_set_novalidate_class
7255 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7256 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7257 if ($realfile !~ m@^kernel/lockdep@ &&
7258 $realfile !~ m@^include/linux/lockdep@ &&
7259 $realfile !~ m@^drivers/base/core@) {
7261 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7265 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7266 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7267 WARN("EXPORTED_WORLD_WRITABLE",
7268 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7271 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7272 # and whether or not function naming is typical and if
7273 # DEVICE_ATTR permissions uses are unusual too
7274 if ($perl_version_ok &&
7276 $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*\)/) {
7281 my $octal_perms = perms_to_octal($perms);
7282 if ($show =~ /^${var}_show$/ &&
7283 $store =~ /^${var}_store$/ &&
7284 $octal_perms eq "0644") {
7285 if (WARN("DEVICE_ATTR_RW",
7286 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7288 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7290 } elsif ($show =~ /^${var}_show$/ &&
7291 $store =~ /^NULL$/ &&
7292 $octal_perms eq "0444") {
7293 if (WARN("DEVICE_ATTR_RO",
7294 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7296 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7298 } elsif ($show =~ /^NULL$/ &&
7299 $store =~ /^${var}_store$/ &&
7300 $octal_perms eq "0200") {
7301 if (WARN("DEVICE_ATTR_WO",
7302 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7304 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7306 } elsif ($octal_perms eq "0644" ||
7307 $octal_perms eq "0444" ||
7308 $octal_perms eq "0200") {
7309 my $newshow = "$show";
7310 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7311 my $newstore = $store;
7312 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7314 if ($show ne $newshow) {
7315 $rename .= " '$show' to '$newshow'";
7317 if ($store ne $newstore) {
7318 $rename .= " '$store' to '$newstore'";
7320 WARN("DEVICE_ATTR_FUNCTIONS",
7321 "Consider renaming function(s)$rename\n" . $herecurr);
7323 WARN("DEVICE_ATTR_PERMS",
7324 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7328 # Mode permission misuses where it seems decimal should be octal
7329 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7330 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7331 # specific definition of not visible in sysfs.
7332 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7333 # use the default permissions
7334 if ($perl_version_ok &&
7336 $line =~ /$mode_perms_search/) {
7337 foreach my $entry (@mode_permission_funcs) {
7338 my $func = $entry->[0];
7339 my $arg_pos = $entry->[1];
7341 my $lc = $stat =~ tr@\n@@;
7342 $lc = $lc + $linenr;
7343 my $stat_real = get_stat_real($linenr, $lc);
7348 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7350 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7351 if ($stat =~ /$test/) {
7353 $val = $6 if ($skip_args ne "");
7354 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7355 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7356 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7357 ERROR("NON_OCTAL_PERMISSIONS",
7358 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7360 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7361 ERROR("EXPORTED_WORLD_WRITABLE",
7362 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7368 # check for uses of S_<PERMS> that could be octal for readability
7369 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7371 my $octal = perms_to_octal($oval);
7372 if (WARN("SYMBOLIC_PERMS",
7373 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7375 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7379 # validate content of MODULE_LICENSE against list from include/linux/module.h
7380 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7381 my $extracted_string = get_quoted_string($line, $rawline);
7382 my $valid_licenses = qr{
7385 GPL\ and\ additional\ rights|
7391 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7392 WARN("MODULE_LICENSE",
7393 "unknown module license " . $extracted_string . "\n" . $herecurr);
7397 # check for sysctl duplicate constants
7398 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7399 WARN("DUPLICATED_SYSCTL_CONST",
7400 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7404 # If we have no input at all, then there is nothing to report on
7405 # so just keep quiet.
7406 if ($#rawlines == -1) {
7410 # In mailback mode only produce a report in the negative, for
7411 # things that appear to be patches.
7412 if ($mailback && ($clean == 1 || !$is_patch)) {
7416 # This is not a patch, and we are in 'no-patch' mode so
7418 if (!$chk_patch && !$is_patch) {
7422 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7423 ERROR("NOT_UNIFIED_DIFF",
7424 "Does not appear to be a unified-diff format patch\n");
7426 if ($is_patch && $has_commit_log && $chk_signoff) {
7427 if ($signoff == 0) {
7428 ERROR("MISSING_SIGN_OFF",
7429 "Missing Signed-off-by: line(s)\n");
7430 } elsif ($authorsignoff != 1) {
7431 # authorsignoff values:
7432 # 0 -> missing sign off
7433 # 1 -> sign off identical
7434 # 2 -> names and addresses match, comments mismatch
7435 # 3 -> addresses match, names different
7436 # 4 -> names match, addresses different
7437 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7439 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7441 if ($authorsignoff == 0) {
7442 ERROR("NO_AUTHOR_SIGN_OFF",
7443 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7444 } elsif ($authorsignoff == 2) {
7445 CHK("FROM_SIGN_OFF_MISMATCH",
7446 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7447 } elsif ($authorsignoff == 3) {
7448 WARN("FROM_SIGN_OFF_MISMATCH",
7449 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7450 } elsif ($authorsignoff == 4) {
7451 WARN("FROM_SIGN_OFF_MISMATCH",
7452 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7453 } elsif ($authorsignoff == 5) {
7454 WARN("FROM_SIGN_OFF_MISMATCH",
7455 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7460 print report_dump();
7461 if ($summary && !($clean == 1 && $quiet == 1)) {
7462 print "$filename " if ($summary_file);
7463 print "total: $cnt_error errors, $cnt_warn warnings, " .
7464 (($check)? "$cnt_chk checks, " : "") .
7465 "$cnt_lines lines checked\n";
7469 # If there were any defects found and not already fixing them
7470 if (!$clean and !$fix) {
7473 NOTE: For some of the reported defects, checkpatch may be able to
7474 mechanically convert to the typical style using --fix or --fix-inplace.
7477 # If there were whitespace errors which cleanpatch can fix
7478 # then suggest that.
7479 if ($rpt_cleaners) {
7483 NOTE: Whitespace errors detected.
7484 You may wish to use scripts/cleanpatch or scripts/cleanfile
7489 if ($clean == 0 && $fix &&
7490 ("@rawlines" ne "@fixed" ||
7491 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7492 my $newfile = $filename;
7493 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7497 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7499 open($f, '>', $newfile)
7500 or die "$P: Can't open $newfile for write\n";
7501 foreach my $fixed_line (@fixed) {
7504 if ($linecount > 3) {
7505 $fixed_line =~ s/^\+//;
7506 print $f $fixed_line . "\n";
7509 print $f $fixed_line . "\n";
7517 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7519 Do _NOT_ trust the results written to this file.
7520 Do _NOT_ submit these changes without inspecting them for correctness.
7522 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7523 No warranties, expressed or implied...
7531 print "$vname has no obvious style problems and is ready for submission.\n";
7533 print "$vname has style problems, please review.\n";