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 $user_codespellfile = "";
67 my $conststructsfile = "$D/const_structs.checkpatch";
68 my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
71 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
72 # git output parsing needs US English output, so first set backtick child process LANGUAGE
73 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
75 my ${CONFIG_} = "CONFIG_";
81 Usage: $P [OPTION]... [FILE]...
86 -v, --verbose verbose mode
87 --no-tree run without a kernel tree
88 --no-signoff do not check for 'Signed-off-by' line
89 --patch treat FILE as patchfile (default)
90 --emacs emacs compile window format
91 --terse one line per report
92 --showfile emit diffed file position, not input file position
93 -g, --git treat FILE as a single commit or git revision range
94 single git commit with:
98 multiple git commits with:
102 git merges are ignored
103 -f, --file treat FILE as regular source file
104 --subjective, --strict enable more subjective tests
105 --list-types list the possible message types
106 --types TYPE(,TYPE2...) show only these comma separated message types
107 --ignore TYPE(,TYPE2...) ignore various comma separated message types
108 --show-types show the specific message type in the output
109 --max-line-length=n set the maximum line length, (default $max_line_length)
110 if exceeded, warn on patches
111 requires --strict for use with --file
112 --min-conf-desc-length=n set the min description length, if shorter, warn
113 --tab-size=n set the number of spaces for tab (default $tabsize)
114 --root=PATH PATH to the kernel tree root
115 --no-summary suppress the per-file summary
116 --mailback only produce a report in case of warnings/errors
117 --summary-file include the filename in summary
118 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
119 'values', 'possible', 'type', and 'attr' (default
121 --test-only=WORD report only warnings/errors containing WORD
123 --fix EXPERIMENTAL - may create horrible results
124 If correctable single-line errors exist, create
125 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
126 with potential errors corrected to the preferred
128 --fix-inplace EXPERIMENTAL - may create horrible results
129 Is the same as --fix, but overwrites the input
130 file. It's your fault if there's no backup or git
131 --ignore-perl-version override checking of perl version. expect
133 --codespell Use the codespell dictionary for spelling/typos
134 (default:$codespellfile)
135 --codespellfile Use this codespell dictionary
136 --typedefsfile Read additional types from this file
137 --color[=WHEN] Use colors 'always', 'never', or only when output
138 is a terminal ('auto'). Default is 'auto'.
139 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
141 -h, --help, --version display this help and exit
143 When FILE is - read standard input.
151 return grep { !$seen{$_}++ } @_;
161 open(my $script, '<', abs_path($P)) or
162 die "$P: Can't read '$P' $!\n";
164 my $text = <$script>;
168 # Also catch when type or level is passed through a variable
169 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
171 if (exists($types{$2})) {
172 $types{$2} .= ",$1" if ($types{$2} ne $1);
177 $types{$2} = "UNDETERMINED";
181 print("#\tMessage type\n\n");
183 print(" ( Color coding: ");
184 print(RED . "ERROR" . RESET);
186 print(YELLOW . "WARNING" . RESET);
188 print(GREEN . "CHECK" . RESET);
190 print("Multiple levels / Undetermined");
194 foreach my $type (sort keys %types) {
195 my $orig_type = $type;
197 my $level = $types{$type};
198 if ($level eq "ERROR") {
199 $type = RED . $type . RESET;
200 } elsif ($level eq "WARN") {
201 $type = YELLOW . $type . RESET;
202 } elsif ($level eq "CHK") {
203 $type = GREEN . $type . RESET;
206 print(++$count . "\t" . $type . "\n");
207 if ($verbose && exists($verbose_messages{$orig_type})) {
208 my $message = $verbose_messages{$orig_type};
209 $message =~ s/\n/\n\t/g;
210 print("\t" . $message . "\n\n");
217 my $conf = which_conf($configuration_file);
220 open(my $conffile, '<', "$conf")
221 or warn "$P: Can't find a readable $configuration_file file $!\n";
223 while (<$conffile>) {
226 $line =~ s/\s*\n?$//g;
230 next if ($line =~ m/^\s*#/);
231 next if ($line =~ m/^\s*$/);
233 my @words = split(" ", $line);
234 foreach my $word (@words) {
235 last if ($word =~ m/^#/);
236 push (@conf_args, $word);
240 unshift(@ARGV, @conf_args) if @conf_args;
244 open(my $docs, '<', "$docsfile")
245 or warn "$P: Can't read the documentation file $docsfile $!\n";
256 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
258 $verbose_messages{$type} = trim($desc);
264 if ($line =~ /^(?:\s{4,}|$)/) {
269 $verbose_messages{$type} = trim($desc);
278 $verbose_messages{$type} = trim($desc);
283 # Perl's Getopt::Long allows options to take optional arguments after a space.
284 # Prevent --color by itself from consuming other arguments
286 if ($_ eq "--color" || $_ eq "-color") {
287 $_ = "--color=$color";
292 'q|quiet+' => \$quiet,
293 'v|verbose!' => \$verbose,
295 'signoff!' => \$chk_signoff,
296 'patch!' => \$chk_patch,
299 'showfile!' => \$showfile,
302 'subjective!' => \$check,
303 'strict!' => \$check,
304 'ignore=s' => \@ignore,
306 'show-types!' => \$show_types,
307 'list-types!' => \$list_types,
308 'max-line-length=i' => \$max_line_length,
309 'min-conf-desc-length=i' => \$min_conf_desc_length,
310 'tab-size=i' => \$tabsize,
312 'summary!' => \$summary,
313 'mailback!' => \$mailback,
314 'summary-file!' => \$summary_file,
316 'fix-inplace!' => \$fix_inplace,
317 'ignore-perl-version!' => \$ignore_perl_version,
318 'debug=s' => \%debug,
319 'test-only=s' => \$tst_only,
320 'codespell!' => \$codespell,
321 'codespellfile=s' => \$user_codespellfile,
322 'typedefsfile=s' => \$typedefsfile,
323 'color=s' => \$color,
324 'no-color' => \$color, #keep old behaviors of -nocolor
325 'nocolor' => \$color, #keep old behaviors of -nocolor
326 'kconfig-prefix=s' => \${CONFIG_},
331 if ($user_codespellfile) {
332 # Use the user provided codespell file unconditionally
333 $codespellfile = $user_codespellfile;
334 } elsif (!(-f $codespellfile)) {
335 # If /usr/share/codespell/dictionary.txt is not present, try to find it
336 # under codespell's install directory: <codespell_root>/data/dictionary.txt
337 if (($codespell || $help) && which("python3") ne "") {
338 my $python_codespell_dict = << "EOF";
342 codespell_dir = op.dirname(codespell_lib.__file__)
343 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
344 print(codespell_file, end='')
347 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
348 $codespellfile = $codespell_dict if (-f $codespell_dict);
352 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
353 # $help is 2 if invalid option is passed - exitcode: 1
354 help($help - 1) if ($help);
356 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
357 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
359 if ($color =~ /^[01]$/) {
361 } elsif ($color =~ /^always$/i) {
363 } elsif ($color =~ /^never$/i) {
365 } elsif ($color =~ /^auto$/i) {
366 $color = (-t STDOUT);
368 die "$P: Invalid color mode: $color\n";
371 load_docs() if ($verbose);
372 list_types(0) if ($list_types);
374 $fix = 1 if ($fix_inplace);
375 $check_orig = $check;
379 my $perl_version_ok = 1;
380 if ($^V && $^V lt $minimum_perl_version) {
381 $perl_version_ok = 0;
382 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
383 exit(1) if (!$ignore_perl_version);
386 #if no filenames are given, push '-' to read patch from stdin
391 # skip TAB size 1 to avoid additional checks on $tabsize - 1
392 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
394 sub hash_save_array_words {
395 my ($hashRef, $arrayRef) = @_;
397 my @array = split(/,/, join(',', @$arrayRef));
398 foreach my $word (@array) {
399 $word =~ s/\s*\n?$//g;
402 $word =~ tr/[a-z]/[A-Z]/;
404 next if ($word =~ m/^\s*#/);
405 next if ($word =~ m/^\s*$/);
411 sub hash_show_words {
412 my ($hashRef, $prefix) = @_;
414 if (keys %$hashRef) {
415 print "\nNOTE: $prefix message types:";
416 foreach my $word (sort keys %$hashRef) {
423 hash_save_array_words(\%ignore_type, \@ignore);
424 hash_save_array_words(\%use_type, \@use);
427 my $dbg_possible = 0;
430 for my $key (keys %debug) {
432 eval "\${dbg_$key} = '$debug{$key}';";
436 my $rpt_cleaners = 0;
445 if (!top_of_kernel_tree($root)) {
446 die "$P: $root: --root does not point at a valid tree\n";
449 if (top_of_kernel_tree('.')) {
451 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
452 top_of_kernel_tree($1)) {
457 if (!defined $root) {
458 print "Must be run from the top-level dir. of a kernel tree\n";
463 my $emitted_corrupt = 0;
466 [A-Za-z_][A-Za-z\d_]*
467 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
469 our $Storage = qr{extern|static|asmlinkage};
483 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
484 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
485 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
486 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
487 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
489 # Notes to $Attribute:
490 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
513 ____cacheline_aligned|
514 ____cacheline_aligned_in_smp|
515 ____cacheline_internodealigned_in_smp|
517 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
520 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
521 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
522 our $Lval = qr{$Ident(?:$Member)*};
524 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
525 our $Binary = qr{(?i)0b[01]+$Int_type?};
526 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
527 our $Int = qr{[0-9]+$Int_type?};
528 our $Octal = qr{0[0-7]+$Int_type?};
529 our $String = qr{(?:\b[Lu])?"[X\t]*"};
530 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
531 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
532 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
533 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
534 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
535 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
536 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
537 our $Arithmetic = qr{\+|-|\*|\/|%};
541 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
544 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
548 our $NonptrTypeMisordered;
549 our $NonptrTypeWithAttr;
553 our $DeclareMisordered;
555 our $NON_ASCII_UTF8 = qr{
556 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
557 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
558 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
559 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
560 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
561 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
562 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
566 [\x09\x0A\x0D\x20-\x7E] # ASCII
570 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
571 our $typeOtherOSTypedefs = qr{(?x:
572 u_(?:char|short|int|long) | # bsd
573 u(?:nchar|short|int|long) # sysv
575 our $typeKernelTypedefs = qr{(?x:
576 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
579 our $typeStdioTypedefs = qr{(?x:
582 our $typeTypedefs = qr{(?x:
584 $typeOtherOSTypedefs\b|
585 $typeKernelTypedefs\b|
589 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
591 our $logFunctions = qr{(?x:
592 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
593 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
595 WARN(?:_RATELIMIT|_ONCE|)|
598 seq_vprintf|seq_printf|seq_puts
601 our $allocFunctions = qr{(?x:
603 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
606 (?:\w+)?alloc_skb(?:_ip_align)? |
607 # dev_alloc_skb/netdev_alloc_skb, et al
611 our $signature_tags = qr{(?xi:
623 our @link_tags = qw(Link Closes);
625 #Create a search and print patterns for all these strings to be used directly below
626 our $link_tags_search = "";
627 our $link_tags_print = "";
628 foreach my $entry (@link_tags) {
629 if ($link_tags_search ne "") {
630 $link_tags_search .= '|';
631 $link_tags_print .= ' or ';
634 $link_tags_search .= $entry;
635 $link_tags_print .= "'$entry'";
637 $link_tags_search = "(?:${link_tags_search})";
639 our $tracing_logging_tags = qr{(?xi:
663 sub edit_distance_min {
665 my $len = scalar @arr;
666 if ((scalar @arr) < 1) {
667 # if underflow, return
671 for my $i (0 .. ($len-1)) {
672 if ($arr[$i] < $min) {
679 sub get_edit_distance {
680 my ($str1, $str2) = @_;
685 my $len1 = length($str1);
686 my $len2 = length($str2);
687 # two dimensional array storing minimum edit distance
689 for my $i (0 .. $len1) {
690 for my $j (0 .. $len2) {
692 $distance[$i][$j] = $j;
694 $distance[$i][$j] = $i;
695 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
696 $distance[$i][$j] = $distance[$i - 1][$j - 1];
698 my $dist1 = $distance[$i][$j - 1]; #insert distance
699 my $dist2 = $distance[$i - 1][$j]; # remove
700 my $dist3 = $distance[$i - 1][$j - 1]; #replace
701 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
705 return $distance[$len1][$len2];
708 sub find_standard_signature {
710 my @standard_signature_tags = (
711 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
712 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
714 foreach my $signature (@standard_signature_tags) {
715 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
721 our $obsolete_archives = qr{(?xi:
722 \Qfreedesktop.org/archives/dri-devel\E |
723 \Qlists.infradead.org\E |
725 \Qmail-archive.com\E |
726 \Qmailman.alsa-project.org/pipermail\E |
728 \Qozlabs.org/pipermail\E |
732 our @typeListMisordered = (
733 qr{char\s+(?:un)?signed},
734 qr{int\s+(?:(?:un)?signed\s+)?short\s},
735 qr{int\s+short(?:\s+(?:un)?signed)},
736 qr{short\s+int(?:\s+(?:un)?signed)},
737 qr{(?:un)?signed\s+int\s+short},
738 qr{short\s+(?:un)?signed},
739 qr{long\s+int\s+(?:un)?signed},
740 qr{int\s+long\s+(?:un)?signed},
741 qr{long\s+(?:un)?signed\s+int},
742 qr{int\s+(?:un)?signed\s+long},
743 qr{int\s+(?:un)?signed},
744 qr{int\s+long\s+long\s+(?:un)?signed},
745 qr{long\s+long\s+int\s+(?:un)?signed},
746 qr{long\s+long\s+(?:un)?signed\s+int},
747 qr{long\s+long\s+(?:un)?signed},
748 qr{long\s+(?:un)?signed},
753 qr{(?:(?:un)?signed\s+)?char},
754 qr{(?:(?:un)?signed\s+)?short\s+int},
755 qr{(?:(?:un)?signed\s+)?short},
756 qr{(?:(?:un)?signed\s+)?int},
757 qr{(?:(?:un)?signed\s+)?long\s+int},
758 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
759 qr{(?:(?:un)?signed\s+)?long\s+long},
760 qr{(?:(?:un)?signed\s+)?long},
769 qr{${Ident}_handler},
770 qr{${Ident}_handler_fn},
774 our $C90_int_types = qr{(?x:
775 long\s+long\s+int\s+(?:un)?signed|
776 long\s+long\s+(?:un)?signed\s+int|
777 long\s+long\s+(?:un)?signed|
778 (?:(?:un)?signed\s+)?long\s+long\s+int|
779 (?:(?:un)?signed\s+)?long\s+long|
780 int\s+long\s+long\s+(?:un)?signed|
781 int\s+(?:(?:un)?signed\s+)?long\s+long|
783 long\s+int\s+(?:un)?signed|
784 long\s+(?:un)?signed\s+int|
785 long\s+(?:un)?signed|
786 (?:(?:un)?signed\s+)?long\s+int|
787 (?:(?:un)?signed\s+)?long|
788 int\s+long\s+(?:un)?signed|
789 int\s+(?:(?:un)?signed\s+)?long|
792 (?:(?:un)?signed\s+)?int
795 our @typeListFile = ();
796 our @typeListWithAttr = (
798 qr{struct\s+$InitAttribute\s+$Ident},
799 qr{union\s+$InitAttribute\s+$Ident},
802 our @modifierList = (
805 our @modifierListFile = ();
807 our @mode_permission_funcs = (
809 ["module_param_(?:array|named|string)", 4],
810 ["module_param_array_named", 5],
811 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
812 ["proc_create(?:_data|)", 2],
813 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
814 ["IIO_DEV_ATTR_[A-Z_]+", 1],
815 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
816 ["SENSOR_TEMPLATE(?:_2|)", 3],
820 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
822 #Create a search pattern for all these functions to speed up a loop below
823 our $mode_perms_search = "";
824 foreach my $entry (@mode_permission_funcs) {
825 $mode_perms_search .= '|' if ($mode_perms_search ne "");
826 $mode_perms_search .= $entry->[0];
828 $mode_perms_search = "(?:${mode_perms_search})";
830 our %deprecated_apis = (
831 "synchronize_rcu_bh" => "synchronize_rcu",
832 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
833 "call_rcu_bh" => "call_rcu",
834 "rcu_barrier_bh" => "rcu_barrier",
835 "synchronize_sched" => "synchronize_rcu",
836 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
837 "call_rcu_sched" => "call_rcu",
838 "rcu_barrier_sched" => "rcu_barrier",
839 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
840 "cond_synchronize_sched" => "cond_synchronize_rcu",
841 "kmap" => "kmap_local_page",
842 "kunmap" => "kunmap_local",
843 "kmap_atomic" => "kmap_local_page",
844 "kunmap_atomic" => "kunmap_local",
847 #Create a search pattern for all these strings to speed up a loop below
848 our $deprecated_apis_search = "";
849 foreach my $entry (keys %deprecated_apis) {
850 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
851 $deprecated_apis_search .= $entry;
853 $deprecated_apis_search = "(?:${deprecated_apis_search})";
855 our $mode_perms_world_writable = qr{
863 our %mode_permission_string_types = (
882 #Create a search pattern for all these strings to speed up a loop below
883 our $mode_perms_string_search = "";
884 foreach my $entry (keys %mode_permission_string_types) {
885 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
886 $mode_perms_string_search .= $entry;
888 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
889 our $multi_mode_perms_string_search = qr{
890 ${single_mode_perms_string_search}
891 (?:\s*\|\s*${single_mode_perms_string_search})*
897 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
904 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
905 $curpos = pos($string);
908 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
910 $to |= $mode_permission_string_types{$match};
911 $val .= '\s*\|\s*' if ($val ne "");
915 $oval =~ s/^\s*\|\s*//;
916 $oval =~ s/\s*\|\s*$//;
917 return sprintf("%04o", $to);
920 our $allowed_asm_includes = qr{(?x:
926 # memory.h: ARM has a custom one
928 # Load common spelling mistakes and build regular expression list.
932 if (open(my $spelling, '<', $spelling_file)) {
933 while (<$spelling>) {
936 $line =~ s/\s*\n?$//g;
939 next if ($line =~ m/^\s*#/);
940 next if ($line =~ m/^\s*$/);
942 my ($suspect, $fix) = split(/\|\|/, $line);
944 $spelling_fix{$suspect} = $fix;
948 warn "No typos will be found - file '$spelling_file': $!\n";
952 if (open(my $spelling, '<', $codespellfile)) {
953 while (<$spelling>) {
956 $line =~ s/\s*\n?$//g;
959 next if ($line =~ m/^\s*#/);
960 next if ($line =~ m/^\s*$/);
961 next if ($line =~ m/, disabled/i);
965 my ($suspect, $fix) = split(/->/, $line);
967 $spelling_fix{$suspect} = $fix;
971 warn "No codespell typos will be found - file '$codespellfile': $!\n";
975 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
978 my ($wordsRef, $file) = @_;
980 if (open(my $words, '<', $file)) {
984 $line =~ s/\s*\n?$//g;
987 next if ($line =~ m/^\s*#/);
988 next if ($line =~ m/^\s*$/);
990 print("$file: '$line' invalid - ignored\n");
994 $$wordsRef .= '|' if (defined $$wordsRef);
1005 if (show_type("CONST_STRUCT")) {
1006 read_words(\$const_structs, $conststructsfile)
1007 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1010 if (defined($typedefsfile)) {
1011 my $typeOtherTypedefs;
1012 read_words(\$typeOtherTypedefs, $typedefsfile)
1013 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
1014 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1018 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1019 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1020 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
1021 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1022 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1024 (?:$typeTypedefs\b)|
1028 (?:$Modifier\s+|const\s+)*
1030 (?:typeof|__typeof__)\s*\([^\)]*\)|
1031 (?:$typeTypedefs\b)|
1034 (?:\s+$Modifier|\s+const)*
1036 $NonptrTypeMisordered = qr{
1037 (?:$Modifier\s+|const\s+)*
1041 (?:\s+$Modifier|\s+const)*
1043 $NonptrTypeWithAttr = qr{
1044 (?:$Modifier\s+|const\s+)*
1046 (?:typeof|__typeof__)\s*\([^\)]*\)|
1047 (?:$typeTypedefs\b)|
1048 (?:${allWithAttr}\b)
1050 (?:\s+$Modifier|\s+const)*
1054 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1055 (?:\s+$Inline|\s+$Modifier)*
1057 $TypeMisordered = qr{
1058 $NonptrTypeMisordered
1059 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1060 (?:\s+$Inline|\s+$Modifier)*
1062 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1063 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1067 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1069 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1070 # requires at least perl version v5.10.0
1071 # Any use must be runtime checked with $^V
1073 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1074 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1075 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1077 our $declaration_macros = qr{(?x:
1078 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1079 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1080 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1081 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1084 our %allow_repeated_words = (
1091 sub deparenthesize {
1093 return "" if (!defined($string));
1095 while ($string =~ /^\s*\(.*\)\s*$/) {
1096 $string =~ s@^\s*\(\s*@@;
1097 $string =~ s@\s*\)\s*$@@;
1100 $string =~ s@\s+@ @g;
1105 sub seed_camelcase_file {
1108 return if (!(-f $file));
1112 open(my $include_file, '<', "$file")
1113 or warn "$P: Can't read '$file' $!\n";
1114 my $text = <$include_file>;
1115 close($include_file);
1117 my @lines = split('\n', $text);
1119 foreach my $line (@lines) {
1120 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1121 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1123 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1125 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1131 our %maintained_status = ();
1133 sub is_maintained_obsolete {
1134 my ($filename) = @_;
1136 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1138 if (!exists($maintained_status{$filename})) {
1139 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1142 return $maintained_status{$filename} =~ /obsolete/i;
1145 sub is_SPDX_License_valid {
1148 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1150 my $root_path = abs_path($root);
1151 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1152 return 0 if ($status ne "");
1156 my $camelcase_seeded = 0;
1157 sub seed_camelcase_includes {
1158 return if ($camelcase_seeded);
1161 my $camelcase_cache = "";
1162 my @include_files = ();
1164 $camelcase_seeded = 1;
1166 if (-e "$gitroot") {
1167 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1168 chomp $git_last_include_commit;
1169 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1171 my $last_mod_date = 0;
1172 $files = `find $root/include -name "*.h"`;
1173 @include_files = split('\n', $files);
1174 foreach my $file (@include_files) {
1175 my $date = POSIX::strftime("%Y%m%d%H%M",
1176 localtime((stat $file)[9]));
1177 $last_mod_date = $date if ($last_mod_date < $date);
1179 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1182 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1183 open(my $camelcase_file, '<', "$camelcase_cache")
1184 or warn "$P: Can't read '$camelcase_cache' $!\n";
1185 while (<$camelcase_file>) {
1189 close($camelcase_file);
1194 if (-e "$gitroot") {
1195 $files = `${git_command} ls-files "include/*.h"`;
1196 @include_files = split('\n', $files);
1199 foreach my $file (@include_files) {
1200 seed_camelcase_file($file);
1203 if ($camelcase_cache ne "") {
1204 unlink glob ".checkpatch-camelcase.*";
1205 open(my $camelcase_file, '>', "$camelcase_cache")
1206 or warn "$P: Can't write '$camelcase_cache' $!\n";
1207 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1208 print $camelcase_file ("$_\n");
1210 close($camelcase_file);
1214 sub git_is_single_file {
1215 my ($filename) = @_;
1217 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1219 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1220 my $count = $output =~ tr/\n//;
1221 return $count eq 1 && $output =~ m{^${filename}$};
1224 sub git_commit_info {
1225 my ($commit, $id, $desc) = @_;
1227 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1229 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1230 $output =~ s/^\s*//gm;
1231 my @lines = split("\n", $output);
1233 return ($id, $desc) if ($#lines < 0);
1235 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1236 # Maybe one day convert this block of bash into something that returns
1237 # all matching commit ids, but it's very slow...
1239 # echo "checking commits $1..."
1240 # git rev-list --remotes | grep -i "^$1" |
1241 # while read line ; do
1242 # git log --format='%H %s' -1 $line |
1243 # echo "commit $(cut -c 1-12,41-)"
1245 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1246 $lines[0] =~ /^fatal: bad object $commit/) {
1249 $id = substr($lines[0], 0, 12);
1250 $desc = substr($lines[0], 41);
1253 return ($id, $desc);
1256 $chk_signoff = 0 if ($file);
1261 my @fixed_inserted = ();
1262 my @fixed_deleted = ();
1265 # If input is git commits, extract all commits from the commit expressions.
1266 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1267 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1271 foreach my $commit_expr (@ARGV) {
1273 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1274 $git_range = "-$2 $1";
1275 } elsif ($commit_expr =~ m/\.\./) {
1276 $git_range = "$commit_expr";
1278 $git_range = "-1 $commit_expr";
1280 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1281 foreach my $line (split(/\n/, $lines)) {
1282 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1283 next if (!defined($1) || !defined($2));
1286 unshift(@commits, $sha1);
1287 $git_commits{$sha1} = $subject;
1290 die "$P: no git commits after extraction!\n" if (@commits == 0);
1295 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1296 for my $filename (@ARGV) {
1298 my $is_git_file = git_is_single_file($filename);
1299 my $oldfile = $file;
1300 $file = 1 if ($is_git_file);
1302 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1303 die "$P: $filename: git format-patch failed - $!\n";
1305 open($FILE, '-|', "diff -u /dev/null $filename") ||
1306 die "$P: $filename: diff failed - $!\n";
1307 } elsif ($filename eq '-') {
1308 open($FILE, '<&STDIN');
1310 open($FILE, '<', "$filename") ||
1311 die "$P: $filename: open failed - $!\n";
1313 if ($filename eq '-') {
1314 $vname = 'Your patch';
1316 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1322 push(@rawlines, $_);
1323 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1327 if ($#ARGV > 0 && $quiet == 0) {
1328 print '-' x length($vname) . "\n";
1330 print '-' x length($vname) . "\n";
1333 if (!process($filename)) {
1339 @fixed_inserted = ();
1340 @fixed_deleted = ();
1342 @modifierListFile = ();
1345 $file = $oldfile if ($is_git_file);
1349 hash_show_words(\%use_type, "Used");
1350 hash_show_words(\%ignore_type, "Ignored");
1352 if (!$perl_version_ok) {
1355 NOTE: perl $^V is not modern enough to detect all possible issues.
1356 An upgrade to at least perl $minimum_perl_version is suggested.
1362 NOTE: If any of the errors are false positives, please report
1363 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1370 sub top_of_kernel_tree {
1374 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1375 "README", "Documentation", "arch", "include", "drivers",
1376 "fs", "init", "ipc", "kernel", "lib", "scripts",
1379 foreach my $check (@tree_check) {
1380 if (! -e $root . '/' . $check) {
1388 my ($formatted_email) = @_;
1392 my $name_comment = "";
1396 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1399 $comment = $3 if defined $3;
1400 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1402 $comment = $2 if defined $2;
1403 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1405 $comment = $2 if defined $2;
1406 $formatted_email =~ s/\Q$address\E.*$//;
1407 $name = $formatted_email;
1408 $name = trim($name);
1409 $name =~ s/^\"|\"$//g;
1410 # If there's a name left after stripping spaces and
1411 # leading quotes, and the address doesn't have both
1412 # leading and trailing angle brackets, the address
1414 # "joe smith joe@smith.com" bad
1415 # "joe smith <joe@smith.com" bad
1416 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1423 # Extract comments from names excluding quoted parts
1424 # "John D. (Doe)" - Do not extract
1425 if ($name =~ s/\"(.+)\"//) {
1428 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1429 $name_comment .= trim($1);
1431 $name =~ s/^[ \"]+|[ \"]+$//g;
1432 $name = trim("$quoted $name");
1434 $address = trim($address);
1435 $address =~ s/^\<|\>$//g;
1436 $comment = trim($comment);
1438 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1439 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1440 $name = "\"$name\"";
1443 return ($name, $name_comment, $address, $comment);
1447 my ($name, $name_comment, $address, $comment) = @_;
1449 my $formatted_email;
1451 $name =~ s/^[ \"]+|[ \"]+$//g;
1452 $address = trim($address);
1453 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1455 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1456 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1457 $name = "\"$name\"";
1460 $name_comment = trim($name_comment);
1461 $name_comment = " $name_comment" if ($name_comment ne "");
1462 $comment = trim($comment);
1463 $comment = " $comment" if ($comment ne "");
1465 if ("$name" eq "") {
1466 $formatted_email = "$address";
1468 $formatted_email = "$name$name_comment <$address>";
1470 $formatted_email .= "$comment";
1471 return $formatted_email;
1474 sub reformat_email {
1477 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1478 return format_email($email_name, $name_comment, $email_address, $comment);
1481 sub same_email_addresses {
1482 my ($email1, $email2) = @_;
1484 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1485 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1487 return $email1_name eq $email2_name &&
1488 $email1_address eq $email2_address &&
1489 $name1_comment eq $name2_comment &&
1490 $comment1 eq $comment2;
1496 foreach my $path (split(/:/, $ENV{PATH})) {
1497 if (-e "$path/$bin") {
1498 return "$path/$bin";
1508 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1509 if (-e "$path/$conf") {
1510 return "$path/$conf";
1522 for my $c (split(//, $str)) {
1526 for (; ($n % $tabsize) != 0; $n++) {
1538 (my $res = shift) =~ tr/\t/ /c;
1545 # Drop the diff line leader and expand tabs
1547 $line = expand_tabs($line);
1549 # Pick the indent from the front of the line.
1550 my ($white) = ($line =~ /^(\s*)/);
1552 return (length($line), length($white));
1555 my $sanitise_quote = '';
1557 sub sanitise_line_reset {
1558 my ($in_comment) = @_;
1561 $sanitise_quote = '*/';
1563 $sanitise_quote = '';
1576 # Always copy over the diff marker.
1577 $res = substr($line, 0, 1);
1579 for ($off = 1; $off < length($line); $off++) {
1580 $c = substr($line, $off, 1);
1582 # Comments we are whacking completely including the begin
1583 # and end, all to $;.
1584 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1585 $sanitise_quote = '*/';
1587 substr($res, $off, 2, "$;$;");
1591 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1592 $sanitise_quote = '';
1593 substr($res, $off, 2, "$;$;");
1597 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1598 $sanitise_quote = '//';
1600 substr($res, $off, 2, $sanitise_quote);
1605 # A \ in a string means ignore the next character.
1606 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1608 substr($res, $off, 2, 'XX');
1613 if ($c eq "'" || $c eq '"') {
1614 if ($sanitise_quote eq '') {
1615 $sanitise_quote = $c;
1617 substr($res, $off, 1, $c);
1619 } elsif ($sanitise_quote eq $c) {
1620 $sanitise_quote = '';
1624 #print "c<$c> SQ<$sanitise_quote>\n";
1625 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1626 substr($res, $off, 1, $;);
1627 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1628 substr($res, $off, 1, $;);
1629 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1630 substr($res, $off, 1, 'X');
1632 substr($res, $off, 1, $c);
1636 if ($sanitise_quote eq '//') {
1637 $sanitise_quote = '';
1640 # The pathname on a #include may be surrounded by '<' and '>'.
1641 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1642 my $clean = 'X' x length($1);
1643 $res =~ s@\<.*\>@<$clean>@;
1645 # The whole of a #error is a string.
1646 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1647 my $clean = 'X' x length($1);
1648 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1651 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1653 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1659 sub get_quoted_string {
1660 my ($line, $rawline) = @_;
1662 return "" if (!defined($line) || !defined($rawline));
1663 return "" if ($line !~ m/($String)/g);
1664 return substr($rawline, $-[0], $+[0] - $-[0]);
1667 sub ctx_statement_block {
1668 my ($linenr, $remain, $off) = @_;
1669 my $line = $linenr - 1;
1672 my $coff = $off - 1;
1686 @stack = (['', 0]) if ($#stack == -1);
1688 #warn "CSB: blk<$blk> remain<$remain>\n";
1689 # If we are about to drop off the end, pull in more
1692 for (; $remain > 0; $line++) {
1693 last if (!defined $lines[$line]);
1694 next if ($lines[$line] =~ /^-/);
1697 $blk .= $lines[$line] . "\n";
1698 $len = length($blk);
1702 # Bail if there is no further context.
1703 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1707 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1713 $c = substr($blk, $off, 1);
1714 $remainder = substr($blk, $off);
1716 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1718 # Handle nested #if/#else.
1719 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1720 push(@stack, [ $type, $level ]);
1721 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1722 ($type, $level) = @{$stack[$#stack - 1]};
1723 } elsif ($remainder =~ /^#\s*endif\b/) {
1724 ($type, $level) = @{pop(@stack)};
1727 # Statement ends at the ';' or a close '}' at the
1729 if ($level == 0 && $c eq ';') {
1733 # An else is really a conditional as long as its not else if
1734 if ($level == 0 && $coff_set == 0 &&
1735 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1736 $remainder =~ /^(else)(?:\s|{)/ &&
1737 $remainder !~ /^else\s+if\b/) {
1738 $coff = $off + length($1) - 1;
1740 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1741 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1744 if (($type eq '' || $type eq '(') && $c eq '(') {
1748 if ($type eq '(' && $c eq ')') {
1750 $type = ($level != 0)? '(' : '';
1752 if ($level == 0 && $coff < $soff) {
1755 #warn "CSB: mark coff<$coff>\n";
1758 if (($type eq '' || $type eq '{') && $c eq '{') {
1762 if ($type eq '{' && $c eq '}') {
1764 $type = ($level != 0)? '{' : '';
1767 if (substr($blk, $off + 1, 1) eq ';') {
1773 # Preprocessor commands end at the newline unless escaped.
1774 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1782 # We are truly at the end, so shuffle to the next line.
1789 my $statement = substr($blk, $soff, $off - $soff + 1);
1790 my $condition = substr($blk, $soff, $coff - $soff + 1);
1792 #warn "STATEMENT<$statement>\n";
1793 #warn "CONDITION<$condition>\n";
1795 #print "coff<$coff> soff<$off> loff<$loff>\n";
1797 return ($statement, $condition,
1798 $line, $remain + 1, $off - $loff + 1, $level);
1801 sub statement_lines {
1804 # Strip the diff line prefixes and rip blank lines at start and end.
1805 $stmt =~ s/(^|\n)./$1/g;
1809 my @stmt_lines = ($stmt =~ /\n/g);
1811 return $#stmt_lines + 2;
1814 sub statement_rawlines {
1817 my @stmt_lines = ($stmt =~ /\n/g);
1819 return $#stmt_lines + 2;
1822 sub statement_block_size {
1825 $stmt =~ s/(^|\n)./$1/g;
1831 my @stmt_lines = ($stmt =~ /\n/g);
1832 my @stmt_statements = ($stmt =~ /;/g);
1834 my $stmt_lines = $#stmt_lines + 2;
1835 my $stmt_statements = $#stmt_statements + 1;
1837 if ($stmt_lines > $stmt_statements) {
1840 return $stmt_statements;
1844 sub ctx_statement_full {
1845 my ($linenr, $remain, $off) = @_;
1846 my ($statement, $condition, $level);
1850 # Grab the first conditional/block pair.
1851 ($statement, $condition, $linenr, $remain, $off, $level) =
1852 ctx_statement_block($linenr, $remain, $off);
1853 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1854 push(@chunks, [ $condition, $statement ]);
1855 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1856 return ($level, $linenr, @chunks);
1859 # Pull in the following conditional/block pairs and see if they
1860 # could continue the statement.
1862 ($statement, $condition, $linenr, $remain, $off, $level) =
1863 ctx_statement_block($linenr, $remain, $off);
1864 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1865 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1867 push(@chunks, [ $condition, $statement ]);
1870 return ($level, $linenr, @chunks);
1874 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1876 my $start = $linenr - 1;
1883 my @stack = ($level);
1884 for ($line = $start; $remain > 0; $line++) {
1885 next if ($rawlines[$line] =~ /^-/);
1888 $blk .= $rawlines[$line];
1890 # Handle nested #if/#else.
1891 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1892 push(@stack, $level);
1893 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1894 $level = $stack[$#stack - 1];
1895 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1896 $level = pop(@stack);
1899 foreach my $c (split(//, $lines[$line])) {
1900 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1906 if ($c eq $close && $level > 0) {
1908 last if ($level == 0);
1909 } elsif ($c eq $open) {
1914 if (!$outer || $level <= 1) {
1915 push(@res, $rawlines[$line]);
1918 last if ($level == 0);
1921 return ($level, @res);
1923 sub ctx_block_outer {
1924 my ($linenr, $remain) = @_;
1926 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1930 my ($linenr, $remain) = @_;
1932 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1936 my ($linenr, $remain, $off) = @_;
1938 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1941 sub ctx_block_level {
1942 my ($linenr, $remain) = @_;
1944 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1946 sub ctx_statement_level {
1947 my ($linenr, $remain, $off) = @_;
1949 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1952 sub ctx_locate_comment {
1953 my ($first_line, $end_line) = @_;
1955 # If c99 comment on the current line, or the line before or after
1956 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1957 return $current_comment if (defined $current_comment);
1958 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1959 return $current_comment if (defined $current_comment);
1960 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1961 return $current_comment if (defined $current_comment);
1963 # Catch a comment on the end of the line itself.
1964 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1965 return $current_comment if (defined $current_comment);
1967 # Look through the context and try and figure out if there is a
1970 $current_comment = '';
1971 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1972 my $line = $rawlines[$linenr - 1];
1974 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1977 if ($line =~ m@/\*@) {
1980 if (!$in_comment && $current_comment ne '') {
1981 $current_comment = '';
1983 $current_comment .= $line . "\n" if ($in_comment);
1984 if ($line =~ m@\*/@) {
1989 chomp($current_comment);
1990 return($current_comment);
1992 sub ctx_has_comment {
1993 my ($first_line, $end_line) = @_;
1994 my $cmt = ctx_locate_comment($first_line, $end_line);
1996 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1997 ##print "CMMT: $cmt\n";
1999 return ($cmt ne '');
2003 my ($linenr, $cnt) = @_;
2005 my $offset = $linenr - 1;
2010 $line = $rawlines[$offset++];
2011 next if (defined($line) && $line =~ /^-/);
2019 my ($linenr, $lc) = @_;
2021 my $stat_real = raw_line($linenr, 0);
2022 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2023 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2030 my ($linenr, $cnt, $here) = @_;
2032 my $herectx = $here . "\n";
2033 for (my $n = 0; $n < $cnt; $n++) {
2034 $herectx .= raw_line($linenr, $n) . "\n";
2045 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2048 $coded = sprintf("^%c", unpack('C', $2) + 64);
2057 my $av_preprocessor = 0;
2062 sub annotate_reset {
2063 $av_preprocessor = 0;
2065 @av_paren_type = ('E');
2066 $av_pend_colon = 'O';
2069 sub annotate_values {
2070 my ($stream, $type) = @_;
2073 my $var = '_' x length($stream);
2076 print "$stream\n" if ($dbg_values > 1);
2078 while (length($cur)) {
2079 @av_paren_type = ('E') if ($#av_paren_type < 0);
2080 print " <" . join('', @av_paren_type) .
2081 "> <$type> <$av_pending>" if ($dbg_values > 1);
2082 if ($cur =~ /^(\s+)/o) {
2083 print "WS($1)\n" if ($dbg_values > 1);
2084 if ($1 =~ /\n/ && $av_preprocessor) {
2085 $type = pop(@av_paren_type);
2086 $av_preprocessor = 0;
2089 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2090 print "CAST($1)\n" if ($dbg_values > 1);
2091 push(@av_paren_type, $type);
2094 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2095 print "DECLARE($1)\n" if ($dbg_values > 1);
2098 } elsif ($cur =~ /^($Modifier)\s*/) {
2099 print "MODIFIER($1)\n" if ($dbg_values > 1);
2102 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2103 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2104 $av_preprocessor = 1;
2105 push(@av_paren_type, $type);
2111 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2112 print "UNDEF($1)\n" if ($dbg_values > 1);
2113 $av_preprocessor = 1;
2114 push(@av_paren_type, $type);
2116 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2117 print "PRE_START($1)\n" if ($dbg_values > 1);
2118 $av_preprocessor = 1;
2120 push(@av_paren_type, $type);
2121 push(@av_paren_type, $type);
2124 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2125 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2126 $av_preprocessor = 1;
2128 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2132 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2133 print "PRE_END($1)\n" if ($dbg_values > 1);
2135 $av_preprocessor = 1;
2137 # Assume all arms of the conditional end as this
2138 # one does, and continue as if the #endif was not here.
2139 pop(@av_paren_type);
2140 push(@av_paren_type, $type);
2143 } elsif ($cur =~ /^(\\\n)/o) {
2144 print "PRECONT($1)\n" if ($dbg_values > 1);
2146 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2147 print "ATTR($1)\n" if ($dbg_values > 1);
2148 $av_pending = $type;
2151 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2152 print "SIZEOF($1)\n" if ($dbg_values > 1);
2158 } elsif ($cur =~ /^(if|while|for)\b/o) {
2159 print "COND($1)\n" if ($dbg_values > 1);
2163 } elsif ($cur =~/^(case)/o) {
2164 print "CASE($1)\n" if ($dbg_values > 1);
2165 $av_pend_colon = 'C';
2168 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2169 print "KEYWORD($1)\n" if ($dbg_values > 1);
2172 } elsif ($cur =~ /^(\()/o) {
2173 print "PAREN('$1')\n" if ($dbg_values > 1);
2174 push(@av_paren_type, $av_pending);
2178 } elsif ($cur =~ /^(\))/o) {
2179 my $new_type = pop(@av_paren_type);
2180 if ($new_type ne '_') {
2182 print "PAREN('$1') -> $type\n"
2183 if ($dbg_values > 1);
2185 print "PAREN('$1')\n" if ($dbg_values > 1);
2188 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2189 print "FUNC($1)\n" if ($dbg_values > 1);
2193 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2194 if (defined $2 && $type eq 'C' || $type eq 'T') {
2195 $av_pend_colon = 'B';
2196 } elsif ($type eq 'E') {
2197 $av_pend_colon = 'L';
2199 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2202 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2203 print "IDENT($1)\n" if ($dbg_values > 1);
2206 } elsif ($cur =~ /^($Assignment)/o) {
2207 print "ASSIGN($1)\n" if ($dbg_values > 1);
2210 } elsif ($cur =~/^(;|{|})/) {
2211 print "END($1)\n" if ($dbg_values > 1);
2213 $av_pend_colon = 'O';
2215 } elsif ($cur =~/^(,)/) {
2216 print "COMMA($1)\n" if ($dbg_values > 1);
2219 } elsif ($cur =~ /^(\?)/o) {
2220 print "QUESTION($1)\n" if ($dbg_values > 1);
2223 } elsif ($cur =~ /^(:)/o) {
2224 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2226 substr($var, length($res), 1, $av_pend_colon);
2227 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2232 $av_pend_colon = 'O';
2234 } elsif ($cur =~ /^(\[)/o) {
2235 print "CLOSE($1)\n" if ($dbg_values > 1);
2238 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2241 print "OPV($1)\n" if ($dbg_values > 1);
2248 substr($var, length($res), 1, $variant);
2251 } elsif ($cur =~ /^($Operators)/o) {
2252 print "OP($1)\n" if ($dbg_values > 1);
2253 if ($1 ne '++' && $1 ne '--') {
2257 } elsif ($cur =~ /(^.)/o) {
2258 print "C($1)\n" if ($dbg_values > 1);
2261 $cur = substr($cur, length($1));
2262 $res .= $type x length($1);
2266 return ($res, $var);
2270 my ($possible, $line) = @_;
2271 my $notPermitted = qr{(?:
2288 ^(?:typedef|struct|enum)\b
2290 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2291 if ($possible !~ $notPermitted) {
2292 # Check for modifiers.
2293 $possible =~ s/\s*$Storage\s*//g;
2294 $possible =~ s/\s*$Sparse\s*//g;
2295 if ($possible =~ /^\s*$/) {
2297 } elsif ($possible =~ /\s/) {
2298 $possible =~ s/\s*$Type\s*//g;
2299 for my $modifier (split(' ', $possible)) {
2300 if ($modifier !~ $notPermitted) {
2301 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2302 push(@modifierListFile, $modifier);
2307 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2308 push(@typeListFile, $possible);
2312 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2321 $type =~ tr/[a-z]/[A-Z]/;
2323 return defined $use_type{$type} if (scalar keys %use_type > 0);
2325 return !defined $ignore_type{$type};
2329 my ($level, $type, $msg) = @_;
2331 if (!show_type($type) ||
2332 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2337 if ($level eq 'ERROR') {
2339 } elsif ($level eq 'WARNING') {
2345 $output .= $prefix . $level . ':';
2347 $output .= BLUE if ($color);
2348 $output .= "$type:";
2350 $output .= RESET if ($color);
2351 $output .= ' ' . $msg . "\n";
2354 my @lines = split("\n", $output, -1);
2355 splice(@lines, 1, 1);
2356 $output = join("\n", @lines);
2360 $output = (split('\n', $output))[0] . "\n";
2363 if ($verbose && exists($verbose_messages{$type}) &&
2364 !exists($verbose_emitted{$type})) {
2365 $output .= $verbose_messages{$type} . "\n\n";
2366 $verbose_emitted{$type} = 1;
2369 push(our @report, $output);
2378 sub fixup_current_range {
2379 my ($lineRef, $offset, $length) = @_;
2381 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2384 my $no = $o + $offset;
2385 my $nl = $l + $length;
2386 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2390 sub fix_inserted_deleted_lines {
2391 my ($linesRef, $insertedRef, $deletedRef) = @_;
2393 my $range_last_linenr = 0;
2394 my $delta_offset = 0;
2399 my $next_insert = 0;
2400 my $next_delete = 0;
2404 my $inserted = @{$insertedRef}[$next_insert++];
2405 my $deleted = @{$deletedRef}[$next_delete++];
2407 foreach my $old_line (@{$linesRef}) {
2409 my $line = $old_line; #don't modify the array
2410 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2412 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2413 $range_last_linenr = $new_linenr;
2414 fixup_current_range(\$line, $delta_offset, 0);
2417 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2418 $deleted = @{$deletedRef}[$next_delete++];
2420 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2423 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2424 push(@lines, ${$inserted}{'LINE'});
2425 $inserted = @{$insertedRef}[$next_insert++];
2427 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2431 push(@lines, $line);
2441 sub fix_insert_line {
2442 my ($linenr, $line) = @_;
2448 push(@fixed_inserted, $inserted);
2451 sub fix_delete_line {
2452 my ($linenr, $line) = @_;
2459 push(@fixed_deleted, $deleted);
2463 my ($type, $msg) = @_;
2465 if (report("ERROR", $type, $msg)) {
2473 my ($type, $msg) = @_;
2475 if (report("WARNING", $type, $msg)) {
2483 my ($type, $msg) = @_;
2485 if ($check && report("CHECK", $type, $msg)) {
2493 sub check_absolute_file {
2494 my ($absolute, $herecurr) = @_;
2495 my $file = $absolute;
2497 ##print "absolute<$absolute>\n";
2499 # See if any suffix of this path is a path within the tree.
2500 while ($file =~ s@^[^/]*/@@) {
2501 if (-f "$root/$file") {
2502 ##print "file<$file>\n";
2510 # It is, so see if the prefix is acceptable.
2511 my $prefix = $absolute;
2512 substr($prefix, -length($file)) = '';
2514 ##print "prefix<$prefix>\n";
2515 if ($prefix ne ".../") {
2516 WARN("USE_RELATIVE_PATH",
2517 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2524 $string =~ s/^\s+|\s+$//g;
2532 $string =~ s/^\s+//;
2540 $string =~ s/\s+$//;
2545 sub string_find_replace {
2546 my ($string, $find, $replace) = @_;
2548 $string =~ s/$find/$replace/g;
2556 my $source_indent = $tabsize;
2557 my $max_spaces_before_tab = $source_indent - 1;
2558 my $spaces_to_tab = " " x $source_indent;
2560 #convert leading spaces to tabs
2561 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2562 #Remove spaces before a tab
2563 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2568 sub pos_last_openparen {
2573 my $opens = $line =~ tr/\(/\(/;
2574 my $closes = $line =~ tr/\)/\)/;
2576 my $last_openparen = 0;
2578 if (($opens == 0) || ($closes >= $opens)) {
2582 my $len = length($line);
2584 for ($pos = 0; $pos < $len; $pos++) {
2585 my $string = substr($line, $pos);
2586 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2587 $pos += length($1) - 1;
2588 } elsif (substr($line, $pos, 1) eq '(') {
2589 $last_openparen = $pos;
2590 } elsif (index($string, '(') == -1) {
2595 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2598 sub get_raw_comment {
2599 my ($line, $rawline) = @_;
2602 for my $i (0 .. (length($line) - 1)) {
2603 if (substr($line, $i, 1) eq "$;") {
2604 $comment .= substr($rawline, $i, 1);
2611 sub exclude_global_initialisers {
2612 my ($realfile) = @_;
2614 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2615 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2616 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2617 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2621 my $filename = shift;
2627 my $stashrawline="";
2637 my $authorsignoff = 0;
2638 my $author_sob = '';
2640 my $is_binding_patch = -1;
2641 my $in_header_lines = $file ? 0 : 1;
2642 my $in_commit_log = 0; #Scanning lines before patch
2643 my $has_patch_separator = 0; #Found a --- line
2644 my $has_commit_log = 0; #Encountered lines before patch
2645 my $commit_log_lines = 0; #Number of commit log lines
2646 my $commit_log_possible_stack_dump = 0;
2647 my $commit_log_long_line = 0;
2648 my $commit_log_has_diff = 0;
2649 my $reported_maintainer_file = 0;
2650 my $non_utf8_charset = 0;
2652 my $last_git_commit_id_linenr = -1;
2654 my $last_blank_line = 0;
2655 my $last_coalesced_string_linenr = -1;
2663 # Trace the real file/line as we go.
2668 my $context_function; #undef'd unless there's a known function
2670 my $comment_edge = 0;
2674 my $prev_values = 'E';
2677 my %suppress_ifbraces;
2678 my %suppress_whiletrailers;
2679 my %suppress_export;
2680 my $suppress_statement = 0;
2682 my %signatures = ();
2684 # Pre-scan the patch sanitizing the lines.
2685 # Pre-scan the patch looking for any __setup documentation.
2687 my @setup_docs = ();
2690 my $camelcase_file_seeded = 0;
2692 my $checklicenseline = 1;
2694 sanitise_line_reset();
2696 foreach my $rawline (@rawlines) {
2700 push(@fixed, $rawline) if ($fix);
2702 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2704 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2709 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2718 # Guestimate if this is a continuing comment. Run
2719 # the context looking for a comment "edge". If this
2720 # edge is a close comment then we must be in a comment
2724 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2725 next if (defined $rawlines[$ln - 1] &&
2726 $rawlines[$ln - 1] =~ /^-/);
2728 #print "RAW<$rawlines[$ln - 1]>\n";
2729 last if (!defined $rawlines[$ln - 1]);
2730 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2731 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2736 if (defined $edge && $edge eq '*/') {
2740 # Guestimate if this is a continuing comment. If this
2741 # is the start of a diff block and this line starts
2742 # ' *' then it is very likely a comment.
2743 if (!defined $edge &&
2744 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2749 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2750 sanitise_line_reset($in_comment);
2752 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2753 # Standardise the strings and chars within the input to
2754 # simplify matching -- only bother with positive lines.
2755 $line = sanitise_line($rawline);
2757 push(@lines, $line);
2760 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2765 #print "==>$rawline\n";
2766 #print "-->$line\n";
2768 if ($setup_docs && $line =~ /^\+/) {
2769 push(@setup_docs, $line);
2778 foreach my $line (@lines) {
2781 my $sline = $line; #copy of $line
2782 $sline =~ s/$;/ /g; #with comments as spaces
2784 my $rawline = $rawlines[$linenr - 1];
2785 my $raw_comment = get_raw_comment($line, $rawline);
2787 # check if it's a mode change, rename or start of a patch
2788 if (!$in_commit_log &&
2789 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2790 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2791 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2795 #extract the line range in the file after the patch is applied
2796 if (!$in_commit_log &&
2797 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2800 $first_line = $linenr + 1;
2810 %suppress_ifbraces = ();
2811 %suppress_whiletrailers = ();
2812 %suppress_export = ();
2813 $suppress_statement = 0;
2814 if ($context =~ /\b(\w+)\s*\(/) {
2815 $context_function = $1;
2817 undef $context_function;
2821 # track the line number as we move through the hunk, note that
2822 # new versions of GNU diff omit the leading space on completely
2823 # blank context lines so we need to count that too.
2824 } elsif ($line =~ /^( |\+|$)/) {
2826 $realcnt-- if ($realcnt != 0);
2828 # Measure the line length and indent.
2829 ($length, $indent) = line_stats($rawline);
2831 # Track the previous line.
2832 ($prevline, $stashline) = ($stashline, $line);
2833 ($previndent, $stashindent) = ($stashindent, $indent);
2834 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2836 #warn "line<$line>\n";
2838 } elsif ($realcnt == 1) {
2842 my $hunk_line = ($realcnt != 0);
2844 $here = "#$linenr: " if (!$file);
2845 $here = "#$realline: " if ($file);
2848 # extract the filename as it passes
2849 if ($line =~ /^diff --git.*?(\S+)$/) {
2851 $realfile =~ s@^([^/]*)/@@ if (!$file);
2854 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2856 $realfile =~ s@^([^/]*)/@@ if (!$file);
2860 if (!$file && $tree && $p1_prefix ne '' &&
2861 -e "$root/$p1_prefix") {
2862 WARN("PATCH_PREFIX",
2863 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2866 if ($realfile =~ m@^include/asm/@) {
2867 ERROR("MODIFIED_INCLUDE_ASM",
2868 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2873 #make up the handle for any error we report on this line
2875 $prefix = "$realfile:$realline: "
2878 $prefix = "$filename:$realline: ";
2880 $prefix = "$filename:$linenr: ";
2885 if (is_maintained_obsolete($realfile)) {
2887 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2889 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2892 $check = $check_orig;
2894 $checklicenseline = 1;
2896 if ($realfile !~ /^MAINTAINERS/) {
2897 my $last_binding_patch = $is_binding_patch;
2899 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2901 if (($last_binding_patch != -1) &&
2902 ($last_binding_patch ^ $is_binding_patch)) {
2903 WARN("DT_SPLIT_BINDING_PATCH",
2904 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2911 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2913 my $hereline = "$here\n$rawline\n";
2914 my $herecurr = "$here\n$rawline\n";
2915 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2917 $cnt_lines++ if ($realcnt != 0);
2919 # Verify the existence of a commit log if appropriate
2920 # 2 is used because a $signature is counted in $commit_log_lines
2921 if ($in_commit_log) {
2922 if ($line !~ /^\s*$/) {
2923 $commit_log_lines++; #could be a $signature
2925 } elsif ($has_commit_log && $commit_log_lines < 2) {
2926 WARN("COMMIT_MESSAGE",
2927 "Missing commit description - Add an appropriate one\n");
2928 $commit_log_lines = 2; #warn only once
2931 # Check if the commit log has what seems like a diff which can confuse patch
2932 if ($in_commit_log && !$commit_log_has_diff &&
2933 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2934 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2935 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2936 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2937 ERROR("DIFF_IN_COMMIT_MSG",
2938 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2939 $commit_log_has_diff = 1;
2942 # Check for incorrect file permissions
2943 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2944 my $permhere = $here . "FILE: $realfile\n";
2945 if ($realfile !~ m@scripts/@ &&
2946 $realfile !~ /\.(py|pl|awk|sh)$/) {
2947 ERROR("EXECUTE_PERMISSIONS",
2948 "do not set execute permissions for source files\n" . $permhere);
2952 # Check the patch for a From:
2953 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2955 my $curline = $linenr;
2956 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2959 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2961 $author = reformat_email($author);
2964 # Check the patch for a signoff:
2965 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2968 if ($author ne '' && $authorsignoff != 1) {
2969 if (same_email_addresses($1, $author)) {
2973 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2974 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2976 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2979 } elsif (lc $email_address eq lc $author_address) {
2982 } elsif ($email_name eq $author_name) {
2986 my $address1 = $email_address;
2987 my $address2 = $author_address;
2989 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2992 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2995 if ($address1 eq $address2) {
3003 # Check for patch separator
3004 if ($line =~ /^---$/) {
3005 $has_patch_separator = 1;
3009 # Check if MAINTAINERS is being updated. If so, there's probably no need to
3010 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
3011 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3012 $reported_maintainer_file = 1;
3015 # Check signature styles
3016 if (!$in_header_lines &&
3017 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3018 my $space_before = $1;
3020 my $space_after = $3;
3022 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3024 if ($sign_off !~ /$signature_tags/) {
3025 my $suggested_signature = find_standard_signature($sign_off);
3026 if ($suggested_signature eq "") {
3027 WARN("BAD_SIGN_OFF",
3028 "Non-standard signature: $sign_off\n" . $herecurr);
3030 if (WARN("BAD_SIGN_OFF",
3031 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3033 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3037 if (defined $space_before && $space_before ne "") {
3038 if (WARN("BAD_SIGN_OFF",
3039 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3041 $fixed[$fixlinenr] =
3042 "$ucfirst_sign_off $email";
3045 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3046 if (WARN("BAD_SIGN_OFF",
3047 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3049 $fixed[$fixlinenr] =
3050 "$ucfirst_sign_off $email";
3054 if (!defined $space_after || $space_after ne " ") {
3055 if (WARN("BAD_SIGN_OFF",
3056 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3058 $fixed[$fixlinenr] =
3059 "$ucfirst_sign_off $email";
3063 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3064 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3065 if ($suggested_email eq "") {
3066 ERROR("BAD_SIGN_OFF",
3067 "Unrecognized email address: '$email'\n" . $herecurr);
3069 my $dequoted = $suggested_email;
3070 $dequoted =~ s/^"//;
3071 $dequoted =~ s/" </ </;
3072 # Don't force email to have quotes
3073 # Allow just an angle bracketed address
3074 if (!same_email_addresses($email, $suggested_email)) {
3075 if (WARN("BAD_SIGN_OFF",
3076 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3078 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3082 # Address part shouldn't have comments
3083 my $stripped_address = $email_address;
3084 $stripped_address =~ s/\([^\(\)]*\)//g;
3085 if ($email_address ne $stripped_address) {
3086 if (WARN("BAD_SIGN_OFF",
3087 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3089 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3093 # Only one name comment should be allowed
3094 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3095 if ($comment_count > 1) {
3096 WARN("BAD_SIGN_OFF",
3097 "Use a single name comment in email: '$email'\n" . $herecurr);
3101 # stable@vger.kernel.org or stable@kernel.org shouldn't
3102 # have an email name. In addition comments should strictly
3104 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3105 if (($comment ne "" && $comment !~ /^#.+/) ||
3106 ($email_name ne "")) {
3107 my $cur_name = $email_name;
3108 my $new_comment = $comment;
3109 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3111 # Remove brackets enclosing comment text
3112 # and # from start of comments to get comment text
3113 $new_comment =~ s/^\((.*)\)$/$1/;
3114 $new_comment =~ s/^\[(.*)\]$/$1/;
3115 $new_comment =~ s/^[\s\#]+|\s+$//g;
3117 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3118 $new_comment = " # $new_comment" if ($new_comment ne "");
3119 my $new_email = "$email_address$new_comment";
3121 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3122 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3124 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3127 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3128 my $new_comment = $comment;
3130 # Extract comment text from within brackets or
3131 # c89 style /*...*/ comments
3132 $new_comment =~ s/^\[(.*)\]$/$1/;
3133 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3135 $new_comment = trim($new_comment);
3136 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3137 $new_comment = "($new_comment)" if ($new_comment ne "");
3138 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3140 if (WARN("BAD_SIGN_OFF",
3141 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3143 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3148 # Check for duplicate signatures
3149 my $sig_nospace = $line;
3150 $sig_nospace =~ s/\s//g;
3151 $sig_nospace = lc($sig_nospace);
3152 if (defined $signatures{$sig_nospace}) {
3153 WARN("BAD_SIGN_OFF",
3154 "Duplicate signature\n" . $herecurr);
3156 $signatures{$sig_nospace} = 1;
3159 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3160 if ($sign_off =~ /^co-developed-by:$/i) {
3161 if ($email eq $author) {
3162 WARN("BAD_SIGN_OFF",
3163 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
3165 if (!defined $lines[$linenr]) {
3166 WARN("BAD_SIGN_OFF",
3167 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3168 } elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
3169 WARN("BAD_SIGN_OFF",
3170 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
3171 } elsif ($1 ne $email) {
3172 WARN("BAD_SIGN_OFF",
3173 "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
3177 # check if Reported-by: is followed by a Closes: tag
3178 if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3179 if (!defined $lines[$linenr]) {
3180 WARN("BAD_REPORTED_BY_LINK",
3181 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
3182 } elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
3183 WARN("BAD_REPORTED_BY_LINK",
3184 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
3190 # Check Fixes: styles is correct
3191 if (!$in_header_lines &&
3192 $line =~ /^\s*fixes:?\s*(?:commit\s*)?[0-9a-f]{5,}\b/i) {
3193 my $orig_commit = "";
3194 my $id = "0123456789ab";
3195 my $title = "commit title";
3200 my $title_has_quotes = 0;
3202 if ($line =~ /(\s*fixes:?)\s+([0-9a-f]{5,})\s+($balanced_parens)/i) {
3207 $tag_case = 0 if $tag eq "Fixes:";
3208 $tag_space = 0 if ($line =~ /^fixes:? [0-9a-f]{5,} ($balanced_parens)/i);
3210 $id_length = 0 if ($orig_commit =~ /^[0-9a-f]{12}$/i);
3211 $id_case = 0 if ($orig_commit !~ /[A-F]/);
3213 # Always strip leading/trailing parens then double quotes if existing
3214 $title = substr($title, 1, -1);
3215 if ($title =~ /^".*"$/) {
3216 $title = substr($title, 1, -1);
3217 $title_has_quotes = 1;
3221 my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3224 if ($ctitle ne $title || $tag_case || $tag_space ||
3225 $id_length || $id_case || !$title_has_quotes) {
3226 if (WARN("BAD_FIXES_TAG",
3227 "Please use correct Fixes: style 'Fixes: <12 chars of sha1> (\"<title line>\")' - ie: 'Fixes: $cid (\"$ctitle\")'\n" . $herecurr) &&
3229 $fixed[$fixlinenr] = "Fixes: $cid (\"$ctitle\")";
3234 # Check email subject for common tools that don't need to be mentioned
3235 if ($in_header_lines &&
3236 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3237 WARN("EMAIL_SUBJECT",
3238 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3241 # Check for Gerrit Change-Ids not in any patch context
3242 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3243 if (ERROR("GERRIT_CHANGE_ID",
3244 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3246 fix_delete_line($fixlinenr, $rawline);
3250 # Check if the commit log is in a possible stack dump
3251 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3252 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3253 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3255 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3256 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3257 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3258 # stack dump address styles
3259 $commit_log_possible_stack_dump = 1;
3262 # Check for line lengths > 75 in commit log, warn once
3263 if ($in_commit_log && !$commit_log_long_line &&
3264 length($line) > 75 &&
3265 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3266 # file delta changes
3267 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3269 $line =~ /^\s*(?:Fixes:|$link_tags_search|$signature_tags)/i ||
3270 # A Fixes:, link or signature tag line
3271 $commit_log_possible_stack_dump)) {
3272 WARN("COMMIT_LOG_LONG_LINE",
3273 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3274 $commit_log_long_line = 1;
3277 # Reset possible stack dump if a blank line is found
3278 if ($in_commit_log && $commit_log_possible_stack_dump &&
3280 $commit_log_possible_stack_dump = 0;
3283 # Check for odd tags before a URI/URL
3284 if ($in_commit_log &&
3285 $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
3286 if ($1 =~ /^v(?:ersion)?\d+/i) {
3287 WARN("COMMIT_LOG_VERSIONING",
3288 "Patch version information should be after the --- line\n" . $herecurr);
3290 WARN("COMMIT_LOG_USE_LINK",
3291 "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
3295 # Check for misuse of the link tags
3296 if ($in_commit_log &&
3297 $line =~ /^\s*(\w+:)\s*(\S+)/) {
3300 if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3301 WARN("COMMIT_LOG_WRONG_LINK",
3302 "'$tag' should be followed by a public http(s) link\n" . $herecurr);
3306 # Check for lines starting with a #
3307 if ($in_commit_log && $line =~ /^#/) {
3308 if (WARN("COMMIT_COMMENT_SYMBOL",
3309 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3311 $fixed[$fixlinenr] =~ s/^/ /;
3315 # Check for git id commit length and improperly formed commit descriptions
3316 # A correctly formed commit description is:
3317 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3318 # with the commit subject '("' prefix and '")' suffix
3319 # This is a fairly compilicated block as it tests for what appears to be
3320 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3321 # possible SHA-1 matches.
3322 # A commit match can span multiple lines so this block attempts to find a
3323 # complete typical commit on a maximum of 3 lines
3324 if ($perl_version_ok &&
3325 $in_commit_log && !$commit_log_possible_stack_dump &&
3326 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3327 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3328 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3329 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3330 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3331 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3332 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3333 my $init_char = "c";
3334 my $orig_commit = "";
3339 my $id = '0123456789ab';
3340 my $orig_desc = "commit description";
3341 my $description = "";
3342 my $herectx = $herecurr;
3347 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3348 for (my $n = 0; $n < 2; $n++) {
3349 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3352 # Always strip leading/trailing parens then double quotes if existing
3353 $orig_desc = substr($orig_desc, 1, -1);
3354 if ($orig_desc =~ /^".*"$/) {
3355 $orig_desc = substr($orig_desc, 1, -1);
3360 last if ($#lines < $linenr + $n);
3361 $input .= " " . trim($rawlines[$linenr + $n]);
3362 $herectx .= "$rawlines[$linenr + $n]\n";
3364 $herectx = $herecurr if (!$has_parens);
3367 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3369 $orig_commit = lc($2);
3370 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3371 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3372 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3373 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3374 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3375 $orig_commit = lc($1);
3378 ($id, $description) = git_commit_info($orig_commit,
3382 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3383 $last_git_commit_id_linenr != $linenr - 1) {
3384 ERROR("GIT_COMMIT_ID",
3385 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3387 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3388 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3391 # Check for mailing list archives other than lore.kernel.org
3392 if ($rawline =~ m{http.*\b$obsolete_archives}) {
3393 WARN("PREFER_LORE_ARCHIVE",
3394 "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3397 # Check for added, moved or deleted files
3398 if (!$reported_maintainer_file && !$in_commit_log &&
3399 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3400 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3401 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3402 (defined($1) || defined($2))))) {
3404 $reported_maintainer_file = 1;
3405 WARN("FILE_PATH_CHANGES",
3406 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3409 # Check for adding new DT bindings not in schema format
3410 if (!$in_commit_log &&
3411 ($line =~ /^new file mode\s*\d+\s*$/) &&
3412 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3413 WARN("DT_SCHEMA_BINDING_PATCH",
3414 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3417 # Check for wrappage within a valid hunk of the file
3418 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3419 ERROR("CORRUPTED_PATCH",
3420 "patch seems to be corrupt (line wrapped?)\n" .
3421 $herecurr) if (!$emitted_corrupt++);
3424 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3425 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3426 $rawline !~ m/^$UTF8*$/) {
3427 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3429 my $blank = copy_spacing($rawline);
3430 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3431 my $hereptr = "$hereline$ptr\n";
3434 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3437 # Check if it's the start of a commit log
3438 # (not a header line and we haven't seen the patch filename)
3439 if ($in_header_lines && $realfile =~ /^$/ &&
3440 !($rawline =~ /^\s+(?:\S|$)/ ||
3441 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3442 $in_header_lines = 0;
3444 $has_commit_log = 1;
3447 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3448 # declined it, i.e defined some charset where it is missing.
3449 if ($in_header_lines &&
3450 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3452 $non_utf8_charset = 1;
3455 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3456 $rawline =~ /$NON_ASCII_UTF8/) {
3457 WARN("UTF8_BEFORE_PATCH",
3458 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3461 # Check for absolute kernel paths in commit message
3462 if ($tree && $in_commit_log) {
3463 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3466 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3467 check_absolute_file($1, $herecurr)) {
3470 check_absolute_file($file, $herecurr);
3475 # Check for various typo / spelling mistakes
3476 if (defined($misspellings) &&
3477 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3478 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3480 my $blank = copy_spacing($rawline);
3481 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3482 my $hereptr = "$hereline$ptr\n";
3483 my $typo_fix = $spelling_fix{lc($typo)};
3484 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3485 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3486 my $msg_level = \&WARN;
3487 $msg_level = \&CHK if ($file);
3488 if (&{$msg_level}("TYPO_SPELLING",
3489 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3491 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3496 # check for invalid commit id
3497 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3500 ($id, $description) = git_commit_info($2, undef, undef);
3501 if (!defined($id)) {
3502 WARN("UNKNOWN_COMMIT_ID",
3503 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3507 # check for repeated words separated by a single space
3508 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3509 if (($rawline =~ /^\+/ || $in_commit_log) &&
3510 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3511 pos($rawline) = 1 if (!$in_commit_log);
3512 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3516 my $start_pos = $-[1];
3517 my $end_pos = $+[2];
3518 if ($first =~ /(?:struct|union|enum)/) {
3519 pos($rawline) += length($first) + length($second) + 1;
3523 next if (lc($first) ne lc($second));
3524 next if ($first eq 'long');
3526 # check for character before and after the word matches
3527 my $start_char = '';
3529 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3530 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3532 next if ($start_char =~ /^\S$/);
3533 next if (index(" \t.,;?!", $end_char) == -1);
3535 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3536 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3537 next if (!exists($allow_repeated_words{lc($first)}));
3540 if (WARN("REPEATED_WORD",
3541 "Possible repeated word: '$first'\n" . $herecurr) &&
3543 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3547 # if it's a repeated word on consecutive lines in a comment block
3548 if ($prevline =~ /$;+\s*$/ &&
3549 $prevrawline =~ /($word_pattern)\s*$/) {
3551 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3552 if (WARN("REPEATED_WORD",
3553 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3555 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3561 # ignore non-hunk lines and lines being removed
3562 next if (!$hunk_line || $line =~ /^-/);
3564 #trailing whitespace
3565 if ($line =~ /^\+.*\015/) {
3566 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3567 if (ERROR("DOS_LINE_ENDINGS",
3568 "DOS line endings\n" . $herevet) &&
3570 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3572 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3573 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3574 if (ERROR("TRAILING_WHITESPACE",
3575 "trailing whitespace\n" . $herevet) &&
3577 $fixed[$fixlinenr] =~ s/\s+$//;
3583 # Check for FSF mailing addresses.
3584 if ($rawline =~ /\bwrite to the Free/i ||
3585 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3586 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3587 $rawline =~ /\b51\s+Franklin\s+St/i) {
3588 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3589 my $msg_level = \&ERROR;
3590 $msg_level = \&CHK if ($file);
3591 &{$msg_level}("FSF_MAILING_ADDRESS",
3592 "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)
3595 # check for Kconfig help text having a real description
3596 # Only applies when adding the entry originally, after that we do not have
3597 # sufficient context to determine whether it is indeed long enough.
3598 if ($realfile =~ /Kconfig/ &&
3599 # 'choice' is usually the last thing on the line (though
3600 # Kconfig supports named choices), so use a word boundary
3601 # (\b) rather than a whitespace character (\s)
3602 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3606 my $help_length = 0;
3607 while (defined $lines[$ln]) {
3608 my $f = $lines[$ln++];
3610 next if ($f =~ /^-/);
3611 last if ($f !~ /^[\+ ]/); # !patch context
3613 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3617 if ($f =~ /^\+\s*help\s*$/) {
3622 $f =~ s/^.//; # strip patch context [+ ]
3623 $f =~ s/#.*//; # strip # directives
3624 $f =~ s/^\s+//; # strip leading blanks
3625 next if ($f =~ /^$/); # skip blank lines
3627 # At the end of this Kconfig block:
3628 # This only checks context lines in the patch
3629 # and so hopefully shouldn't trigger false
3630 # positives, even though some of these are
3631 # common words in help texts
3632 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3633 if|endif|menu|endmenu|source)\b/x) {
3636 $help_length++ if ($has_help);
3639 $help_length < $min_conf_desc_length) {
3640 my $stat_real = get_stat_real($linenr, $ln - 1);
3641 WARN("CONFIG_DESCRIPTION",
3642 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3646 # check MAINTAINERS entries
3647 if ($realfile =~ /^MAINTAINERS$/) {
3648 # check MAINTAINERS entries for the right form
3649 if ($rawline =~ /^\+[A-Z]:/ &&
3650 $rawline !~ /^\+[A-Z]:\t\S/) {
3651 if (WARN("MAINTAINERS_STYLE",
3652 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3654 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3657 # check MAINTAINERS entries for the right ordering too
3658 my $preferred_order = 'MRLSWQBCPTFXNK';
3659 if ($rawline =~ /^\+[A-Z]:/ &&
3660 $prevrawline =~ /^[\+ ][A-Z]:/) {
3661 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3664 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3667 my $curindex = index($preferred_order, $cur);
3668 my $previndex = index($preferred_order, $prev);
3669 if ($curindex < 0) {
3670 WARN("MAINTAINERS_STYLE",
3671 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3673 if ($previndex >= 0 && $curindex < $previndex) {
3674 WARN("MAINTAINERS_STYLE",
3675 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3676 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3677 ($prev eq 'X' && $cur eq 'X')) &&
3678 ($prevval cmp $curval) > 0) {
3679 WARN("MAINTAINERS_STYLE",
3680 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3686 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3687 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3690 'EXTRA_AFLAGS' => 'asflags-y',
3691 'EXTRA_CFLAGS' => 'ccflags-y',
3692 'EXTRA_CPPFLAGS' => 'cppflags-y',
3693 'EXTRA_LDFLAGS' => 'ldflags-y',
3696 WARN("DEPRECATED_VARIABLE",
3697 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3700 # check for DT compatible documentation
3701 if (defined $root &&
3702 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3703 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3705 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3707 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3708 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3710 foreach my $compat (@compats) {
3711 my $compat2 = $compat;
3712 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3713 my $compat3 = $compat;
3714 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3715 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3717 WARN("UNDOCUMENTED_DT_STRING",
3718 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3721 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3723 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3725 WARN("UNDOCUMENTED_DT_STRING",
3726 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3731 # check for using SPDX license tag at beginning of files
3732 if ($realline == $checklicenseline) {
3733 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3734 $checklicenseline = 2;
3735 } elsif ($rawline =~ /^\+/) {
3737 if ($realfile =~ /\.(h|s|S)$/) {
3739 } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3741 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3743 } elsif ($realfile =~ /\.rst$/) {
3747 # check SPDX comment style for .[chsS] files
3748 if ($realfile =~ /\.[chsS]$/ &&
3749 $rawline =~ /SPDX-License-Identifier:/ &&
3750 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3751 WARN("SPDX_LICENSE_TAG",
3752 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3755 if ($comment !~ /^$/ &&
3756 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3757 WARN("SPDX_LICENSE_TAG",
3758 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3759 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3760 my $spdx_license = $1;
3761 if (!is_SPDX_License_valid($spdx_license)) {
3762 WARN("SPDX_LICENSE_TAG",
3763 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3765 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3766 $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
3767 my $msg_level = \&WARN;
3768 $msg_level = \&CHK if ($file);
3769 if (&{$msg_level}("SPDX_LICENSE_TAG",
3771 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3773 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3776 if ($realfile =~ m@^include/dt-bindings/@ &&
3777 $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3778 WARN("SPDX_LICENSE_TAG",
3779 "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3785 # check for embedded filenames
3786 if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
3787 WARN("EMBEDDED_FILENAME",
3788 "It's generally not useful to have the filename in the file\n" . $herecurr);
3791 # check we are in a valid source file if not then ignore this hunk
3792 next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3794 # check for using SPDX-License-Identifier on the wrong line number
3795 if ($realline != $checklicenseline &&
3796 $rawline =~ /\bSPDX-License-Identifier:/ &&
3797 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3798 WARN("SPDX_LICENSE_TAG",
3799 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3802 # line length limit (with some exclusions)
3804 # There are a few types of lines that may extend beyond $max_line_length:
3805 # logging functions like pr_info that end in a string
3806 # lines with a single string
3807 # #defines that are a single string
3808 # lines with an RFC3986 like URL
3810 # There are 3 different line length message types:
3811 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3812 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3813 # LONG_LINE all other lines longer than $max_line_length
3815 # if LONG_LINE is ignored, the other 2 types are also ignored
3818 if ($line =~ /^\+/ && $length > $max_line_length) {
3819 my $msg_type = "LONG_LINE";
3821 # Check the allowed long line types first
3823 # logging functions that end in a string that starts
3824 # before $max_line_length
3825 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3826 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3829 # lines with only strings (w/ possible termination)
3830 # #defines with only strings
3831 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3832 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3835 # More special cases
3836 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3837 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3840 # URL ($rawline is used in case the URL is in a comment)
3841 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3844 # Otherwise set the alternate message types
3846 # a comment starts before $max_line_length
3847 } elsif ($line =~ /($;[\s$;]*)$/ &&
3848 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3849 $msg_type = "LONG_LINE_COMMENT"
3851 # a quoted string starts before $max_line_length
3852 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3853 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3854 $msg_type = "LONG_LINE_STRING"
3857 if ($msg_type ne "" &&
3858 (show_type("LONG_LINE") || show_type($msg_type))) {
3859 my $msg_level = \&WARN;
3860 $msg_level = \&CHK if ($file);
3861 &{$msg_level}($msg_type,
3862 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3866 # check for adding lines without a newline.
3867 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3868 if (WARN("MISSING_EOF_NEWLINE",
3869 "adding a line without newline at end of file\n" . $herecurr) &&
3871 fix_delete_line($fixlinenr+1, "No newline at end of file");
3875 # check for .L prefix local symbols in .S files
3876 if ($realfile =~ /\.S$/ &&
3877 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3878 WARN("AVOID_L_PREFIX",
3879 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr);
3882 # check we are in a valid source file C or perl if not then ignore this hunk
3883 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3885 # at the beginning of a line any tabs must come first and anything
3886 # more than $tabsize must use tabs.
3887 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3888 $rawline =~ /^\+\s* \s*/) {
3889 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3891 if (ERROR("CODE_INDENT",
3892 "code indent should use tabs where possible\n" . $herevet) &&
3894 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3898 # check for space before tabs.
3899 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3900 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3901 if (WARN("SPACE_BEFORE_TAB",
3902 "please, no space before tabs\n" . $herevet) &&
3904 while ($fixed[$fixlinenr] =~
3905 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3906 while ($fixed[$fixlinenr] =~
3907 s/(^\+.*) +\t/$1\t/) {}
3911 # check for assignments on the start of a line
3912 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3914 if (CHK("ASSIGNMENT_CONTINUATIONS",
3915 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3916 $fix && $prevrawline =~ /^\+/) {
3917 # add assignment operator to the previous line, remove from current line
3918 $fixed[$fixlinenr - 1] .= " $operator";
3919 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3923 # check for && or || at the start of a line
3924 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3926 if (CHK("LOGICAL_CONTINUATIONS",
3927 "Logical continuations should be on the previous line\n" . $hereprev) &&
3928 $fix && $prevrawline =~ /^\+/) {
3929 # insert logical operator at last non-comment, non-whitepsace char on previous line
3930 $prevline =~ /[\s$;]*$/;
3931 my $line_end = substr($prevrawline, $-[0]);
3932 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3933 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3937 # check indentation starts on a tab stop
3938 if ($perl_version_ok &&
3939 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3940 my $indent = length($1);
3941 if ($indent % $tabsize) {
3943 "Statements should start on a tabstop\n" . $herecurr) &&
3945 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3950 # check multi-line statement indentation matches previous line
3951 if ($perl_version_ok &&
3952 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3953 $prevline =~ /^\+(\t*)(.*)$/;
3957 my $pos = pos_last_openparen($rest);
3959 $line =~ /^(\+| )([ \t]*)/;
3962 my $goodtabindent = $oldindent .
3963 "\t" x ($pos / $tabsize) .
3964 " " x ($pos % $tabsize);
3965 my $goodspaceindent = $oldindent . " " x $pos;
3967 if ($newindent ne $goodtabindent &&
3968 $newindent ne $goodspaceindent) {
3970 if (CHK("PARENTHESIS_ALIGNMENT",
3971 "Alignment should match open parenthesis\n" . $hereprev) &&
3972 $fix && $line =~ /^\+/) {
3973 $fixed[$fixlinenr] =~
3974 s/^\+[ \t]*/\+$goodtabindent/;
3980 # check for space after cast like "(int) foo" or "(struct foo) bar"
3981 # avoid checking a few false positives:
3982 # "sizeof(<type>)" or "__alignof__(<type>)"
3983 # function pointer declarations like "(*foo)(int) = bar;"
3984 # structure definitions like "(struct foo) { 0 };"
3985 # multiline macros that define functions
3986 # known attributes or the __attribute__ keyword
3987 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3988 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3990 "No space is necessary after a cast\n" . $herecurr) &&
3992 $fixed[$fixlinenr] =~
3993 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3997 # Block comment styles
3998 # Networking with an initial /*
3999 if ($realfile =~ m@^(drivers/net/|net/)@ &&
4000 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
4001 $rawline =~ /^\+[ \t]*\*/ &&
4002 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
4003 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
4004 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
4007 # Block comments use * on subsequent lines
4008 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4009 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
4010 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
4011 $rawline =~ /^\+/ && #line is new
4012 $rawline !~ /^\+[ \t]*\*/) { #no leading *
4013 WARN("BLOCK_COMMENT_STYLE",
4014 "Block comments use * on subsequent lines\n" . $hereprev);
4017 # Block comments use */ on trailing lines
4018 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
4019 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
4020 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
4021 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
4022 WARN("BLOCK_COMMENT_STYLE",
4023 "Block comments use a trailing */ on a separate line\n" . $herecurr);
4026 # Block comment * alignment
4027 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4028 $line =~ /^\+[ \t]*$;/ && #leading comment
4029 $rawline =~ /^\+[ \t]*\*/ && #leading *
4030 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
4031 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
4032 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4034 $prevrawline =~ m@^\+([ \t]*/?)\*@;
4036 $oldindent = expand_tabs($1);
4038 $prevrawline =~ m@^\+(.*/?)\*@;
4039 $oldindent = expand_tabs($1);
4041 $rawline =~ m@^\+([ \t]*)\*@;
4043 $newindent = expand_tabs($newindent);
4044 if (length($oldindent) ne length($newindent)) {
4045 WARN("BLOCK_COMMENT_STYLE",
4046 "Block comments should align the * on each line\n" . $hereprev);
4050 # check for missing blank lines after struct/union declarations
4051 # with exceptions for various attributes and macros
4052 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4054 !($line =~ /^\+\s*$/ ||
4055 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
4056 $line =~ /^\+\s*MODULE_/i ||
4057 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4058 $line =~ /^\+[a-z_]*init/ ||
4059 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4060 $line =~ /^\+\s*DECLARE/ ||
4061 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4062 $line =~ /^\+\s*__setup/)) {
4063 if (CHK("LINE_SPACING",
4064 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4066 fix_insert_line($fixlinenr, "\+");
4070 # check for multiple consecutive blank lines
4071 if ($prevline =~ /^[\+ ]\s*$/ &&
4072 $line =~ /^\+\s*$/ &&
4073 $last_blank_line != ($linenr - 1)) {
4074 if (CHK("LINE_SPACING",
4075 "Please don't use multiple blank lines\n" . $hereprev) &&
4077 fix_delete_line($fixlinenr, $rawline);
4080 $last_blank_line = $linenr;
4083 # check for missing blank lines after declarations
4084 # (declarations must have the same indentation and not be at the start of line)
4085 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4089 # remove $Attribute/$Sparse uses to simplify comparisons
4090 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4091 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4092 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4093 # function pointer declarations
4094 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4095 # foo bar; where foo is some local typedef or #define
4096 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4097 # known declaration macros
4098 $pl =~ /^\+\s+$declaration_macros/) &&
4099 # for "else if" which can look like "$Ident $Ident"
4100 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4101 # other possible extensions of declaration lines
4102 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4103 # not starting a section or a macro "\" extended line
4104 $pl =~ /(?:\{\s*|\\)$/) &&
4105 # looks like a declaration
4106 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4107 # function pointer declarations
4108 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4109 # foo bar; where foo is some local typedef or #define
4110 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4111 # known declaration macros
4112 $sl =~ /^\+\s+$declaration_macros/ ||
4113 # start of struct or union or enum
4114 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4115 # start or end of block or continuation of declaration
4116 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4117 # bitfield continuation
4118 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4119 # other possible extensions of declaration lines
4120 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4121 if (WARN("LINE_SPACING",
4122 "Missing a blank line after declarations\n" . $hereprev) &&
4124 fix_insert_line($fixlinenr, "\+");
4129 # check for spaces at the beginning of a line.
4131 # 1) within comments
4132 # 2) indented preprocessor commands
4134 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4135 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4136 if (WARN("LEADING_SPACE",
4137 "please, no spaces at the start of a line\n" . $herevet) &&
4139 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4143 # check we are in a valid C source file if not then ignore this hunk
4144 next if ($realfile !~ /\.(h|c)$/);
4146 # check for unusual line ending [ or (
4147 if ($line =~ /^\+.*([\[\(])\s*$/) {
4148 CHK("OPEN_ENDED_LINE",
4149 "Lines should not end with a '$1'\n" . $herecurr);
4152 # check if this appears to be the start function declaration, save the name
4153 if ($sline =~ /^\+\{\s*$/ &&
4154 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4155 $context_function = $1;
4158 # check if this appears to be the end of function declaration
4159 if ($sline =~ /^\+\}\s*$/) {
4160 undef $context_function;
4163 # check indentation of any line with a bare else
4164 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4165 # if the previous line is a break or return and is indented 1 tab more...
4166 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4167 my $tabs = length($1) + 1;
4168 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4169 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4170 defined $lines[$linenr] &&
4171 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4172 WARN("UNNECESSARY_ELSE",
4173 "else is not generally useful after a break or return\n" . $hereprev);
4177 # check indentation of a line with a break;
4178 # if the previous line is a goto, return or break
4179 # and is indented the same # of tabs
4180 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4182 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4183 if (WARN("UNNECESSARY_BREAK",
4184 "break is not useful after a $1\n" . $hereprev) &&
4186 fix_delete_line($fixlinenr, $rawline);
4191 # check for RCS/CVS revision markers
4192 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4194 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4197 # check for old HOTPLUG __dev<foo> section markings
4198 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4199 WARN("HOTPLUG_SECTION",
4200 "Using $1 is unnecessary\n" . $herecurr);
4203 # Check for potential 'bare' types
4204 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4206 #print "LINE<$line>\n";
4207 if ($linenr > $suppress_statement &&
4208 $realcnt && $sline =~ /.\s*\S/) {
4209 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4210 ctx_statement_block($linenr, $realcnt, 0);
4211 $stat =~ s/\n./\n /g;
4212 $cond =~ s/\n./\n /g;
4214 #print "linenr<$linenr> <$stat>\n";
4215 # If this statement has no statement boundaries within
4216 # it there is no point in retrying a statement scan
4217 # until we hit end of it.
4218 my $frag = $stat; $frag =~ s/;+\s*$//;
4219 if ($frag !~ /(?:{|;)/) {
4220 #print "skip<$line_nr_next>\n";
4221 $suppress_statement = $line_nr_next;
4224 # Find the real next line.
4225 $realline_next = $line_nr_next;
4226 if (defined $realline_next &&
4227 (!defined $lines[$realline_next - 1] ||
4228 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4235 # Ignore goto labels.
4236 if ($s =~ /$Ident:\*$/s) {
4238 # Ignore functions being called
4239 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4241 } elsif ($s =~ /^.\s*else\b/s) {
4243 # declarations always start with types
4244 } 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) {
4247 possible($type, "A:" . $s);
4249 # definitions in global scope can only start with types
4250 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4251 possible($1, "B:" . $s);
4254 # any (foo ... *) is a pointer cast, and foo is a type
4255 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4256 possible($1, "C:" . $s);
4259 # Check for any sort of function declaration.
4260 # int foo(something bar, other baz);
4261 # void (*store_gdt)(x86_descr_ptr *);
4262 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4263 my ($name_len) = length($1);
4266 substr($ctx, 0, $name_len + 1, '');
4267 $ctx =~ s/\)[^\)]*$//;
4269 for my $arg (split(/\s*,\s*/, $ctx)) {
4270 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4272 possible($1, "D:" . $s);
4280 # Checks which may be anchored in the context.
4283 # Check for switch () and associated case and default
4284 # statements should be at the same indent.
4285 if ($line=~/\bswitch\s*\(.*\)/) {
4288 my @ctx = ctx_block_outer($linenr, $realcnt);
4290 for my $ctx (@ctx) {
4291 my ($clen, $cindent) = line_stats($ctx);
4292 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4293 $indent != $cindent) {
4294 $err .= "$sep$ctx\n";
4301 ERROR("SWITCH_CASE_INDENT_LEVEL",
4302 "switch and case should be at the same indent\n$hereline$err");
4306 # if/while/etc brace do not go on next line, unless defining a do while loop,
4307 # or if that brace on the next line is for something else
4308 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4309 my $pre_ctx = "$1$2";
4311 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4313 if ($line =~ /^\+\t{6,}/) {
4314 WARN("DEEP_INDENTATION",
4315 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4318 my $ctx_cnt = $realcnt - $#ctx - 1;
4319 my $ctx = join("\n", @ctx);
4321 my $ctx_ln = $linenr;
4322 my $ctx_skip = $realcnt;
4324 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4325 defined $lines[$ctx_ln - 1] &&
4326 $lines[$ctx_ln - 1] =~ /^-/)) {
4327 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4328 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4332 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4333 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4335 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4337 "that open brace { should be on the previous line\n" .
4338 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4340 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4341 $ctx =~ /\)\s*\;\s*$/ &&
4342 defined $lines[$ctx_ln - 1])
4344 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4345 if ($nindent > $indent) {
4346 WARN("TRAILING_SEMICOLON",
4347 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4348 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4353 # Check relative indent for conditionals and blocks.
4354 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4355 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4356 ctx_statement_block($linenr, $realcnt, 0)
4357 if (!defined $stat);
4358 my ($s, $c) = ($stat, $cond);
4360 substr($s, 0, length($c), '');
4362 # remove inline comments
4366 # Find out how long the conditional actually is.
4367 my @newlines = ($c =~ /\n/gs);
4368 my $cond_lines = 1 + $#newlines;
4370 # Make sure we remove the line prefixes as we have
4371 # none on the first line, and are going to readd them
4374 while ($s =~ /\n\s+\\\n/) {
4375 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4378 # We want to check the first line inside the block
4379 # starting at the end of the conditional, so remove:
4380 # 1) any blank line termination
4381 # 2) any opening brace { on end of the line
4383 my $continuation = 0;
4385 $s =~ s/^.*\bdo\b//;
4387 if ($s =~ s/^\s*\\//) {
4390 if ($s =~ s/^\s*?\n//) {
4395 # Also ignore a loop construct at the end of a
4396 # preprocessor statement.
4397 if (($prevline =~ /^.\s*#\s*define\s/ ||
4398 $prevline =~ /\\\s*$/) && $continuation == 0) {
4404 while ($cond_ptr != $cond_lines) {
4405 $cond_ptr = $cond_lines;
4407 # If we see an #else/#elif then the code
4409 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4414 # 1) blank lines, they should be at 0,
4415 # 2) preprocessor lines, and
4417 if ($continuation ||
4419 $s =~ /^\s*#\s*?/ ||
4420 $s =~ /^\s*$Ident\s*:/) {
4421 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4422 if ($s =~ s/^.*?\n//) {
4428 my (undef, $sindent) = line_stats("+" . $s);
4429 my $stat_real = raw_line($linenr, $cond_lines);
4431 # Check if either of these lines are modified, else
4432 # this is not this patch's fault.
4433 if (!defined($stat_real) ||
4434 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4437 if (defined($stat_real) && $cond_lines > 1) {
4438 $stat_real = "[...]\n$stat_real";
4441 #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";
4443 if ($check && $s ne '' &&
4444 (($sindent % $tabsize) != 0 ||
4445 ($sindent < $indent) ||
4446 ($sindent == $indent &&
4447 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4448 ($sindent > $indent + $tabsize))) {
4449 WARN("SUSPECT_CODE_INDENT",
4450 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4454 # Track the 'values' across context and added lines.
4455 my $opline = $line; $opline =~ s/^./ /;
4456 my ($curr_values, $curr_vars) =
4457 annotate_values($opline . "\n", $prev_values);
4458 $curr_values = $prev_values . $curr_values;
4460 my $outline = $opline; $outline =~ s/\t/ /g;
4461 print "$linenr > .$outline\n";
4462 print "$linenr > $curr_values\n";
4463 print "$linenr > $curr_vars\n";
4465 $prev_values = substr($curr_values, -1);
4467 #ignore lines not being added
4468 next if ($line =~ /^[^\+]/);
4470 # check for self assignments used to avoid compiler warnings
4471 # e.g.: int foo = foo, *bar = NULL;
4472 # struct foo bar = *(&(bar));
4473 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4475 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4476 WARN("SELF_ASSIGNMENT",
4477 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4481 # check for dereferences that span multiple lines
4482 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4483 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4484 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4486 $line =~ /^.\s*($Lval)/;
4489 WARN("MULTILINE_DEREFERENCE",
4490 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4493 # check for declarations of signed or unsigned without int
4494 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4497 $var = "" if (!defined $var);
4498 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4502 $pointer = "" if (!defined $pointer);
4504 if (WARN("UNSPECIFIED_INT",
4505 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4507 my $decl = trim($sign) . " int ";
4508 my $comp_pointer = $pointer;
4509 $comp_pointer =~ s/\s//g;
4510 $decl .= $comp_pointer;
4511 $decl = rtrim($decl) if ($var eq "");
4512 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4517 # TEST: allow direct testing of the type matcher.
4519 if ($line =~ /^.\s*$Declare\s*$/) {
4521 "TEST: is type\n" . $herecurr);
4522 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4523 ERROR("TEST_NOT_TYPE",
4524 "TEST: is not type ($1 is)\n". $herecurr);
4528 # TEST: allow direct testing of the attribute matcher.
4530 if ($line =~ /^.\s*$Modifier\s*$/) {
4532 "TEST: is attr\n" . $herecurr);
4533 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4534 ERROR("TEST_NOT_ATTR",
4535 "TEST: is not attr ($1 is)\n". $herecurr);
4540 # check for initialisation to aggregates open brace on the next line
4541 if ($line =~ /^.\s*{/ &&
4542 $prevline =~ /(?:^|[^=])=\s*$/) {
4543 if (ERROR("OPEN_BRACE",
4544 "that open brace { should be on the previous line\n" . $hereprev) &&
4545 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4546 fix_delete_line($fixlinenr - 1, $prevrawline);
4547 fix_delete_line($fixlinenr, $rawline);
4548 my $fixedline = $prevrawline;
4549 $fixedline =~ s/\s*=\s*$/ = {/;
4550 fix_insert_line($fixlinenr, $fixedline);
4552 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4553 fix_insert_line($fixlinenr, $fixedline);
4558 # Checks which are anchored on the added line.
4561 # check for malformed paths in #include statements (uses RAW line)
4562 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4564 if ($path =~ m{//}) {
4565 ERROR("MALFORMED_INCLUDE",
4566 "malformed #include filename\n" . $herecurr);
4568 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4569 ERROR("UAPI_INCLUDE",
4570 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4574 # no C99 // comments
4575 if ($line =~ m{//}) {
4576 if (ERROR("C99_COMMENTS",
4577 "do not use C99 // comments\n" . $herecurr) &&
4579 my $line = $fixed[$fixlinenr];
4580 if ($line =~ /\/\/(.*)$/) {
4581 my $comment = trim($1);
4582 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4586 # Remove C99 comments.
4588 $opline =~ s@//.*@@;
4590 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4591 # the whole statement.
4592 #print "APW <$lines[$realline_next - 1]>\n";
4593 if (defined $realline_next &&
4594 exists $lines[$realline_next - 1] &&
4595 !defined $suppress_export{$realline_next} &&
4596 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4597 # Handle definitions which produce identifiers with
4600 # EXPORT_SYMBOL(something_foo);
4602 $name =~ s/^\s*($Ident).*/$1/;
4603 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4604 $name =~ /^${Ident}_$2/) {
4605 #print "FOO C name<$name>\n";
4606 $suppress_export{$realline_next} = 1;
4608 } elsif ($stat !~ /(?:
4610 ^.DEFINE_$Ident\(\Q$name\E\)|
4611 ^.DECLARE_$Ident\(\Q$name\E\)|
4612 ^.LIST_HEAD\(\Q$name\E\)|
4613 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4614 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4616 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4617 $suppress_export{$realline_next} = 2;
4619 $suppress_export{$realline_next} = 1;
4622 if (!defined $suppress_export{$linenr} &&
4623 $prevline =~ /^.\s*$/ &&
4624 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4625 #print "FOO B <$lines[$linenr - 1]>\n";
4626 $suppress_export{$linenr} = 2;
4628 if (defined $suppress_export{$linenr} &&
4629 $suppress_export{$linenr} == 2) {
4630 WARN("EXPORT_SYMBOL",
4631 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4634 # check for global initialisers.
4635 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4636 !exclude_global_initialisers($realfile)) {
4637 if (ERROR("GLOBAL_INITIALISERS",
4638 "do not initialise globals to $1\n" . $herecurr) &&
4640 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4643 # check for static initialisers.
4644 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4645 if (ERROR("INITIALISED_STATIC",
4646 "do not initialise statics to $1\n" .
4649 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4653 # check for misordered declarations of char/short/int/long with signed/unsigned
4654 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4656 WARN("MISORDERED_TYPE",
4657 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4660 # check for unnecessary <signed> int declarations of short/long/long long
4661 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4662 my $type = trim($1);
4663 next if ($type !~ /\bint\b/);
4664 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4665 my $new_type = $type;
4666 $new_type =~ s/\b\s*int\s*\b/ /;
4667 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4668 $new_type =~ s/^const\s+//;
4669 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4670 $new_type = "const $new_type" if ($type =~ /^const\b/);
4671 $new_type =~ s/\s+/ /g;
4672 $new_type = trim($new_type);
4673 if (WARN("UNNECESSARY_INT",
4674 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4676 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4680 # check for static const char * arrays.
4681 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4682 WARN("STATIC_CONST_CHAR_ARRAY",
4683 "static const char * array should probably be static const char * const\n" .
4687 # check for initialized const char arrays that should be static const
4688 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4689 if (WARN("STATIC_CONST_CHAR_ARRAY",
4690 "const array should probably be static const\n" . $herecurr) &&
4692 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4696 # check for static char foo[] = "bar" declarations.
4697 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4698 WARN("STATIC_CONST_CHAR_ARRAY",
4699 "static char array declaration should probably be static const char\n" .
4703 # check for const <foo> const where <foo> is not a pointer or array type
4704 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4706 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4708 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4709 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4711 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4715 # check for const static or static <non ptr type> const declarations
4716 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4717 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4718 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4719 if (WARN("STATIC_CONST",
4720 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4722 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4723 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4727 # check for non-global char *foo[] = {"bar", ...} declarations.
4728 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4729 WARN("STATIC_CONST_CHAR_ARRAY",
4730 "char * array declaration might be better as static const\n" .
4734 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4735 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4737 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4739 if (WARN("ARRAY_SIZE",
4740 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4742 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4747 # check for function declarations without arguments like "int foo()"
4748 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4749 if (ERROR("FUNCTION_WITHOUT_ARGS",
4750 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4752 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4756 # check for new typedefs, only function parameters and sparse annotations
4758 if ($line =~ /\btypedef\s/ &&
4759 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4760 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4761 $line !~ /\b$typeTypedefs\b/ &&
4762 $line !~ /\b__bitwise\b/) {
4763 WARN("NEW_TYPEDEFS",
4764 "do not add new typedefs\n" . $herecurr);
4767 # * goes on variable not on type
4769 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4771 my ($ident, $from, $to) = ($1, $2, $2);
4773 # Should start with a space.
4774 $to =~ s/^(\S)/ $1/;
4775 # Should not end with a space.
4777 # '*'s should not have spaces between.
4778 while ($to =~ s/\*\s+\*/\*\*/) {
4781 ## print "1: from<$from> to<$to> ident<$ident>\n";
4783 if (ERROR("POINTER_LOCATION",
4784 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4786 my $sub_from = $ident;
4787 my $sub_to = $ident;
4788 $sub_to =~ s/\Q$from\E/$to/;
4789 $fixed[$fixlinenr] =~
4790 s@\Q$sub_from\E@$sub_to@;
4794 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4796 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4798 # Should start with a space.
4799 $to =~ s/^(\S)/ $1/;
4800 # Should not end with a space.
4802 # '*'s should not have spaces between.
4803 while ($to =~ s/\*\s+\*/\*\*/) {
4805 # Modifiers should have spaces.
4806 $to =~ s/(\b$Modifier$)/$1 /;
4808 ## print "2: from<$from> to<$to> ident<$ident>\n";
4809 if ($from ne $to && $ident !~ /^$Modifier$/) {
4810 if (ERROR("POINTER_LOCATION",
4811 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4814 my $sub_from = $match;
4815 my $sub_to = $match;
4816 $sub_to =~ s/\Q$from\E/$to/;
4817 $fixed[$fixlinenr] =~
4818 s@\Q$sub_from\E@$sub_to@;
4823 # do not use BUG() or variants
4824 if ($line =~ /\b(?!AA_|BUILD_|DCCP_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4825 my $msg_level = \&WARN;
4826 $msg_level = \&CHK if ($file);
4827 &{$msg_level}("AVOID_BUG",
4828 "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr);
4831 # avoid LINUX_VERSION_CODE
4832 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4833 WARN("LINUX_VERSION_CODE",
4834 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4837 # check for uses of printk_ratelimit
4838 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4839 WARN("PRINTK_RATELIMITED",
4840 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4843 # printk should use KERN_* levels
4844 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4845 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4846 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4849 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4850 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4854 $modifier = "" if (!defined($modifier));
4855 my $level = lc($orig);
4856 $level = "warn" if ($level eq "warning");
4857 my $level2 = $level;
4858 $level2 = "dbg" if ($level eq "debug");
4859 $level .= $modifier;
4860 $level2 .= $modifier;
4861 WARN("PREFER_PR_LEVEL",
4862 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4865 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4866 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4868 my $level = lc($orig);
4869 $level = "warn" if ($level eq "warning");
4870 $level = "dbg" if ($level eq "debug");
4871 WARN("PREFER_DEV_LEVEL",
4872 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4875 # trace_printk should not be used in production code.
4876 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4877 WARN("TRACE_PRINTK",
4878 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4881 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4882 # number of false positives, but assembly files are not checked, so at
4883 # least the arch entry code will not trigger this warning.
4884 if ($line =~ /\bENOSYS\b/) {
4886 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4889 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4890 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4891 # Similarly to ENOSYS warning a small number of false positives is expected.
4892 if (!$file && $line =~ /\bENOTSUPP\b/) {
4893 if (WARN("ENOTSUPP",
4894 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4896 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4900 # function brace can't be on same line, except for #defines of do while,
4901 # or if closed on same line
4902 if ($perl_version_ok &&
4903 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4904 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4906 if (ERROR("OPEN_BRACE",
4907 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4909 fix_delete_line($fixlinenr, $rawline);
4910 my $fixed_line = $rawline;
4911 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4914 fix_insert_line($fixlinenr, ltrim($line1));
4915 fix_insert_line($fixlinenr, "\+{");
4916 if ($line2 !~ /^\s*$/) {
4917 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4922 # open braces for enum, union and struct go on the same line.
4923 if ($line =~ /^.\s*{/ &&
4924 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4925 if (ERROR("OPEN_BRACE",
4926 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4927 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4928 fix_delete_line($fixlinenr - 1, $prevrawline);
4929 fix_delete_line($fixlinenr, $rawline);
4930 my $fixedline = rtrim($prevrawline) . " {";
4931 fix_insert_line($fixlinenr, $fixedline);
4932 $fixedline = $rawline;
4933 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4934 if ($fixedline !~ /^\+\s*$/) {
4935 fix_insert_line($fixlinenr, $fixedline);
4940 # missing space after union, struct or enum definition
4941 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4943 "missing space after $1 definition\n" . $herecurr) &&
4945 $fixed[$fixlinenr] =~
4946 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4950 # Function pointer declarations
4951 # check spacing between type, funcptr, and args
4952 # canonical declaration is "type (*funcptr)(args...)"
4953 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4955 my $pre_pointer_space = $2;
4956 my $post_pointer_space = $3;
4958 my $post_funcname_space = $5;
4959 my $pre_args_space = $6;
4961 # the $Declare variable will capture all spaces after the type
4962 # so check it for a missing trailing missing space but pointer return types
4963 # don't need a space so don't warn for those.
4964 my $post_declare_space = "";
4965 if ($declare =~ /(\s+)$/) {
4966 $post_declare_space = $1;
4967 $declare = rtrim($declare);
4969 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4971 "missing space after return type\n" . $herecurr);
4972 $post_declare_space = " ";
4975 # unnecessary space "type (*funcptr)(args...)"
4976 # This test is not currently implemented because these declarations are
4978 # int foo(int bar, ...)
4979 # and this is form shouldn't/doesn't generate a checkpatch warning.
4981 # elsif ($declare =~ /\s{2,}$/) {
4983 # "Multiple spaces after return type\n" . $herecurr);
4986 # unnecessary space "type ( *funcptr)(args...)"
4987 if (defined $pre_pointer_space &&
4988 $pre_pointer_space =~ /^\s/) {
4990 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4993 # unnecessary space "type (* funcptr)(args...)"
4994 if (defined $post_pointer_space &&
4995 $post_pointer_space =~ /^\s/) {
4997 "Unnecessary space before function pointer name\n" . $herecurr);
5000 # unnecessary space "type (*funcptr )(args...)"
5001 if (defined $post_funcname_space &&
5002 $post_funcname_space =~ /^\s/) {
5004 "Unnecessary space after function pointer name\n" . $herecurr);
5007 # unnecessary space "type (*funcptr) (args...)"
5008 if (defined $pre_args_space &&
5009 $pre_args_space =~ /^\s/) {
5011 "Unnecessary space before function pointer arguments\n" . $herecurr);
5014 if (show_type("SPACING") && $fix) {
5015 $fixed[$fixlinenr] =~
5016 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5020 # check for spacing round square brackets; allowed:
5021 # 1. with a type on the left -- int [] a;
5022 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5023 # 3. inside a curly brace -- = { [0...10] = 5 }
5024 while ($line =~ /(.*?\s)\[/g) {
5025 my ($where, $prefix) = ($-[1], $1);
5026 if ($prefix !~ /$Type\s+$/ &&
5027 ($where != 0 || $prefix !~ /^.\s+$/) &&
5028 $prefix !~ /[{,:]\s+$/) {
5029 if (ERROR("BRACKET_SPACE",
5030 "space prohibited before open square bracket '['\n" . $herecurr) &&
5032 $fixed[$fixlinenr] =~
5033 s/^(\+.*?)\s+\[/$1\[/;
5038 # check for spaces between functions and their parentheses.
5039 while ($line =~ /($Ident)\s+\(/g) {
5041 my $ctx_before = substr($line, 0, $-[1]);
5042 my $ctx = "$ctx_before$name";
5044 # Ignore those directives where spaces _are_ permitted.
5046 if|for|while|switch|return|case|
5047 volatile|__volatile__|
5048 __attribute__|format|__extension__|
5049 asm|__asm__|scoped_guard)$/x)
5051 # cpp #define statements have non-optional spaces, ie
5052 # if there is a space between the name and the open
5053 # parenthesis it is simply not a parameter group.
5054 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5056 # cpp #elif statement condition may start with a (
5057 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5059 # If this whole things ends with a type its most
5060 # likely a typedef for a function.
5061 } elsif ($ctx =~ /$Type$/) {
5065 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5067 $fixed[$fixlinenr] =~
5068 s/\b$name\s+\(/$name\(/;
5073 # Check operator spacing.
5074 if (!($line=~/\#\s*include/)) {
5075 my $fixed_line = "";
5079 <<=|>>=|<=|>=|==|!=|
5080 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5081 =>|->|<<|>>|<|>|=|!|~|
5082 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5085 my @elements = split(/($ops|;)/, $opline);
5087 ## print("element count: <" . $#elements . ">\n");
5088 ## foreach my $el (@elements) {
5089 ## print("el: <$el>\n");
5092 my @fix_elements = ();
5095 foreach my $el (@elements) {
5096 push(@fix_elements, substr($rawline, $off, length($el)));
5097 $off += length($el);
5102 my $blank = copy_spacing($opline);
5103 my $last_after = -1;
5105 for (my $n = 0; $n < $#elements; $n += 2) {
5107 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5109 ## print("n: <$n> good: <$good>\n");
5111 $off += length($elements[$n]);
5113 # Pick up the preceding and succeeding characters.
5114 my $ca = substr($opline, 0, $off);
5116 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5117 $cc = substr($opline, $off + length($elements[$n + 1]));
5119 my $cb = "$ca$;$cc";
5122 $a = 'V' if ($elements[$n] ne '');
5123 $a = 'W' if ($elements[$n] =~ /\s$/);
5124 $a = 'C' if ($elements[$n] =~ /$;$/);
5125 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5126 $a = 'O' if ($elements[$n] eq '');
5127 $a = 'E' if ($ca =~ /^\s*$/);
5129 my $op = $elements[$n + 1];
5132 if (defined $elements[$n + 2]) {
5133 $c = 'V' if ($elements[$n + 2] ne '');
5134 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5135 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5136 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5137 $c = 'O' if ($elements[$n + 2] eq '');
5138 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5143 my $ctx = "${a}x${c}";
5145 my $at = "(ctx:$ctx)";
5147 my $ptr = substr($blank, 0, $off) . "^";
5148 my $hereptr = "$hereline$ptr\n";
5150 # Pull out the value of this operator.
5151 my $op_type = substr($curr_values, $off + 1, 1);
5153 # Get the full operator variant.
5154 my $opv = $op . substr($curr_vars, $off, 1);
5156 # Ignore operators passed as parameters.
5157 if ($op_type ne 'V' &&
5158 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5161 # } elsif ($op =~ /^$;+$/) {
5163 # ; should have either the end of line or a space or \ after it
5164 } elsif ($op eq ';') {
5165 if ($ctx !~ /.x[WEBC]/ &&
5166 $cc !~ /^\\/ && $cc !~ /^;/) {
5167 if (ERROR("SPACING",
5168 "space required after that '$op' $at\n" . $hereptr)) {
5169 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5175 } elsif ($op eq '//') {
5177 # : when part of a bitfield
5178 } elsif ($opv eq ':B') {
5179 # skip the bitfield test for now
5183 } elsif ($op eq '->') {
5184 if ($ctx =~ /Wx.|.xW/) {
5185 if (ERROR("SPACING",
5186 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5187 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5188 if (defined $fix_elements[$n + 2]) {
5189 $fix_elements[$n + 2] =~ s/^\s+//;
5195 # , must not have a space before and must have a space on the right.
5196 } elsif ($op eq ',') {
5197 my $rtrim_before = 0;
5198 my $space_after = 0;
5199 if ($ctx =~ /Wx./) {
5200 if (ERROR("SPACING",
5201 "space prohibited before that '$op' $at\n" . $hereptr)) {
5206 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5207 if (ERROR("SPACING",
5208 "space required after that '$op' $at\n" . $hereptr)) {
5214 if ($rtrim_before || $space_after) {
5215 if ($rtrim_before) {
5216 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5218 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5225 # '*' as part of a type definition -- reported already.
5226 } elsif ($opv eq '*_') {
5227 #warn "'*' is part of type\n";
5229 # unary operators should have a space before and
5230 # none after. May be left adjacent to another
5231 # unary operator, or a cast
5232 } elsif ($op eq '!' || $op eq '~' ||
5233 $opv eq '*U' || $opv eq '-U' ||
5234 $opv eq '&U' || $opv eq '&&U') {
5235 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5236 if (ERROR("SPACING",
5237 "space required before that '$op' $at\n" . $hereptr)) {
5238 if ($n != $last_after + 2) {
5239 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5244 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5245 # A unary '*' may be const
5247 } elsif ($ctx =~ /.xW/) {
5248 if (ERROR("SPACING",
5249 "space prohibited after that '$op' $at\n" . $hereptr)) {
5250 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5251 if (defined $fix_elements[$n + 2]) {
5252 $fix_elements[$n + 2] =~ s/^\s+//;
5258 # unary ++ and unary -- are allowed no space on one side.
5259 } elsif ($op eq '++' or $op eq '--') {
5260 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5261 if (ERROR("SPACING",
5262 "space required one side of that '$op' $at\n" . $hereptr)) {
5263 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5267 if ($ctx =~ /Wx[BE]/ ||
5268 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5269 if (ERROR("SPACING",
5270 "space prohibited before that '$op' $at\n" . $hereptr)) {
5271 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5275 if ($ctx =~ /ExW/) {
5276 if (ERROR("SPACING",
5277 "space prohibited after that '$op' $at\n" . $hereptr)) {
5278 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5279 if (defined $fix_elements[$n + 2]) {
5280 $fix_elements[$n + 2] =~ s/^\s+//;
5286 # << and >> may either have or not have spaces both sides
5287 } elsif ($op eq '<<' or $op eq '>>' or
5288 $op eq '&' or $op eq '^' or $op eq '|' or
5289 $op eq '+' or $op eq '-' or
5290 $op eq '*' or $op eq '/' or
5294 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5296 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5297 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5298 $fix_elements[$n + 2] =~ s/^\s+//;
5301 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5303 "space preferred before that '$op' $at\n" . $hereptr)) {
5304 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5308 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5309 if (ERROR("SPACING",
5310 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5311 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5312 if (defined $fix_elements[$n + 2]) {
5313 $fix_elements[$n + 2] =~ s/^\s+//;
5319 # A colon needs no spaces before when it is
5320 # terminating a case value or a label.
5321 } elsif ($opv eq ':C' || $opv eq ':L') {
5322 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5323 if (ERROR("SPACING",
5324 "space prohibited before that '$op' $at\n" . $hereptr)) {
5325 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5330 # All the others need spaces both sides.
5331 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5334 # Ignore email addresses <foo@bar>
5336 $cc =~ /^\S+\@\S+>/) ||
5338 $ca =~ /<\S+\@\S+$/))
5343 # for asm volatile statements
5344 # ignore a colon with another
5345 # colon immediately before or after
5347 ($ca =~ /:$/ || $cc =~ /^:/)) {
5351 # messages are ERROR, but ?: are CHK
5353 my $msg_level = \&ERROR;
5354 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5356 if (&{$msg_level}("SPACING",
5357 "spaces required around that '$op' $at\n" . $hereptr)) {
5358 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5359 if (defined $fix_elements[$n + 2]) {
5360 $fix_elements[$n + 2] =~ s/^\s+//;
5366 $off += length($elements[$n + 1]);
5368 ## print("n: <$n> GOOD: <$good>\n");
5370 $fixed_line = $fixed_line . $good;
5373 if (($#elements % 2) == 0) {
5374 $fixed_line = $fixed_line . $fix_elements[$#elements];
5377 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5378 $fixed[$fixlinenr] = $fixed_line;
5384 # check for whitespace before a non-naked semicolon
5385 if ($line =~ /^\+.*\S\s+;\s*$/) {
5387 "space prohibited before semicolon\n" . $herecurr) &&
5389 1 while $fixed[$fixlinenr] =~
5390 s/^(\+.*\S)\s+;/$1;/;
5394 # check for multiple assignments
5395 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5396 CHK("MULTIPLE_ASSIGNMENTS",
5397 "multiple assignments should be avoided\n" . $herecurr);
5400 ## # check for multiple declarations, allowing for a function declaration
5402 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5403 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5405 ## # Remove any bracketed sections to ensure we do not
5406 ## # falsely report the parameters of functions.
5408 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5410 ## if ($ln =~ /,/) {
5411 ## WARN("MULTIPLE_DECLARATION",
5412 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5416 #need space before brace following if, while, etc
5417 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5418 $line =~ /\b(?:else|do)\{/) {
5419 if (ERROR("SPACING",
5420 "space required before the open brace '{'\n" . $herecurr) &&
5422 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5426 ## # check for blank lines before declarations
5427 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5428 ## $prevrawline =~ /^.\s*$/) {
5430 ## "No blank lines before declarations\n" . $hereprev);
5434 # closing brace should have a space following it when it has anything
5436 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5437 if (ERROR("SPACING",
5438 "space required after that close brace '}'\n" . $herecurr) &&
5440 $fixed[$fixlinenr] =~
5441 s/}((?!(?:,|;|\)))\S)/} $1/;
5445 # check spacing on square brackets
5446 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5447 if (ERROR("SPACING",
5448 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5450 $fixed[$fixlinenr] =~
5454 if ($line =~ /\s\]/) {
5455 if (ERROR("SPACING",
5456 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5458 $fixed[$fixlinenr] =~
5463 # check spacing on parentheses
5464 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5465 $line !~ /for\s*\(\s+;/) {
5466 if (ERROR("SPACING",
5467 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5469 $fixed[$fixlinenr] =~
5473 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5474 $line !~ /for\s*\(.*;\s+\)/ &&
5475 $line !~ /:\s+\)/) {
5476 if (ERROR("SPACING",
5477 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5479 $fixed[$fixlinenr] =~
5484 # check unnecessary parentheses around addressof/dereference single $Lvals
5485 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5487 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5489 if (CHK("UNNECESSARY_PARENTHESES",
5490 "Unnecessary parentheses around $var\n" . $herecurr) &&
5492 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5496 # check for unnecessary parentheses around function pointer uses
5497 # ie: (foo->bar)(); should be foo->bar();
5498 # but not "if (foo->bar) (" to avoid some false positives
5499 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5501 if (CHK("UNNECESSARY_PARENTHESES",
5502 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5504 my $var2 = deparenthesize($var);
5506 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5510 # check for unnecessary parentheses around comparisons in if uses
5511 # when !drivers/staging or command-line uses --strict
5512 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5513 $perl_version_ok && defined($stat) &&
5514 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5516 my $test = substr($2, 1, -1);
5518 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5520 # avoid parentheses around potential macro args
5521 next if ($match =~ /^\s*\w+\s*$/);
5522 if (!defined($herectx)) {
5523 $herectx = $here . "\n";
5524 my $cnt = statement_rawlines($if_stat);
5525 for (my $n = 0; $n < $cnt; $n++) {
5526 my $rl = raw_line($linenr, $n);
5527 $herectx .= $rl . "\n";
5528 last if $rl =~ /^[ \+].*\{/;
5531 CHK("UNNECESSARY_PARENTHESES",
5532 "Unnecessary parentheses around '$match'\n" . $herectx);
5536 # check that goto labels aren't indented (allow a single space indentation)
5537 # and ignore bitfield definitions like foo:1
5538 # Strictly, labels can have whitespace after the identifier and before the :
5539 # but this is not allowed here as many ?: uses would appear to be labels
5540 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5541 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5542 $sline !~ /^.\s+default:/) {
5543 if (WARN("INDENTED_LABEL",
5544 "labels should not be indented\n" . $herecurr) &&
5546 $fixed[$fixlinenr] =~
5551 # check if a statement with a comma should be two statements like:
5552 # foo = bar(), /* comma should be semicolon */
5554 if (defined($stat) &&
5555 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5556 my $cnt = statement_rawlines($stat);
5557 my $herectx = get_stat_here($linenr, $cnt, $here);
5558 WARN("SUSPECT_COMMA_SEMICOLON",
5559 "Possible comma where semicolon could be used\n" . $herectx);
5562 # return is not a function
5563 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5565 if ($perl_version_ok &&
5566 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5568 $value = deparenthesize($value);
5569 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5570 ERROR("RETURN_PARENTHESES",
5571 "return is not a function, parentheses are not required\n" . $herecurr);
5573 } elsif ($spacing !~ /\s+/) {
5575 "space required before the open parenthesis '('\n" . $herecurr);
5579 # unnecessary return in a void function
5580 # at end-of-function, with the previous line a single leading tab, then return;
5581 # and the line before that not a goto label target like "out:"
5582 if ($sline =~ /^[ \+]}\s*$/ &&
5583 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5585 $lines[$linenr - 3] =~ /^[ +]/ &&
5586 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5588 "void function return statements are not generally useful\n" . $hereprev);
5591 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5592 if ($perl_version_ok &&
5593 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5594 my $openparens = $1;
5595 my $count = $openparens =~ tr@\(@\(@;
5597 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5598 my $comp = $4; #Not $1 because of $LvalOrFunc
5599 $msg = " - maybe == should be = ?" if ($comp eq "==");
5600 WARN("UNNECESSARY_PARENTHESES",
5601 "Unnecessary parentheses$msg\n" . $herecurr);
5605 # comparisons with a constant or upper case identifier on the left
5606 # avoid cases like "foo + BAR < baz"
5607 # only fix matches surrounded by parentheses to avoid incorrect
5608 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5609 if ($perl_version_ok &&
5610 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5615 my $newcomp = $comp;
5616 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5617 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5618 WARN("CONSTANT_COMPARISON",
5619 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5623 } elsif ($comp eq "<=") {
5625 } elsif ($comp eq ">") {
5627 } elsif ($comp eq ">=") {
5630 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5634 # Return of what appears to be an errno should normally be negative
5635 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5637 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5638 WARN("USE_NEGATIVE_ERRNO",
5639 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5643 # Need a space before open parenthesis after if, while etc
5644 if ($line =~ /\b(if|while|for|switch)\(/) {
5645 if (ERROR("SPACING",
5646 "space required before the open parenthesis '('\n" . $herecurr) &&
5648 $fixed[$fixlinenr] =~
5649 s/\b(if|while|for|switch)\(/$1 \(/;
5653 # Check for illegal assignment in if conditional -- and check for trailing
5654 # statements after the conditional.
5655 if ($line =~ /do\s*(?!{)/) {
5656 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5657 ctx_statement_block($linenr, $realcnt, 0)
5658 if (!defined $stat);
5659 my ($stat_next) = ctx_statement_block($line_nr_next,
5660 $remain_next, $off_next);
5661 $stat_next =~ s/\n./\n /g;
5662 ##print "stat<$stat> stat_next<$stat_next>\n";
5664 if ($stat_next =~ /^\s*while\b/) {
5665 # If the statement carries leading newlines,
5666 # then count those as offsets.
5668 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5670 statement_rawlines($whitespace) - 1;
5672 $suppress_whiletrailers{$line_nr_next +
5676 if (!defined $suppress_whiletrailers{$linenr} &&
5677 defined($stat) && defined($cond) &&
5678 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5679 my ($s, $c) = ($stat, $cond);
5680 my $fixed_assign_in_if = 0;
5682 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5683 if (ERROR("ASSIGN_IN_IF",
5684 "do not use assignment in if condition\n" . $herecurr) &&
5685 $fix && $perl_version_ok) {
5686 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5694 fix_delete_line($fixlinenr, $rawline);
5695 fix_insert_line($fixlinenr, "$space$statement;");
5696 my $newline = "${space}if (";
5697 $newline .= '!' if defined($not);
5698 $newline .= '(' if (defined $not && defined($test) && defined($against));
5699 $newline .= "$assigned";
5700 $newline .= " $test $against" if (defined($test) && defined($against));
5701 $newline .= ')' if (defined $not && defined($test) && defined($against));
5703 $newline .= " {" if (defined($brace));
5704 fix_insert_line($fixlinenr + 1, $newline);
5705 $fixed_assign_in_if = 1;
5710 # Find out what is on the end of the line after the
5712 substr($s, 0, length($c), '');
5714 $s =~ s/$;//g; # Remove any comments
5715 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5716 $c !~ /}\s*while\s*/)
5718 # Find out how long the conditional actually is.
5719 my @newlines = ($c =~ /\n/gs);
5720 my $cond_lines = 1 + $#newlines;
5723 $stat_real = raw_line($linenr, $cond_lines)
5724 . "\n" if ($cond_lines);
5725 if (defined($stat_real) && $cond_lines > 1) {
5726 $stat_real = "[...]\n$stat_real";
5729 if (ERROR("TRAILING_STATEMENTS",
5730 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5731 !$fixed_assign_in_if &&
5733 $fix && $perl_version_ok &&
5734 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5737 my $rest = rtrim($4);
5738 if ($rest =~ /;$/) {
5739 $fixed[$fixlinenr] = "\+$indent$test";
5740 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5746 # Check for bitwise tests written as boolean
5758 WARN("HEXADECIMAL_BOOLEAN_TEST",
5759 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5762 # if and else should not have general statements after it
5763 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5765 $s =~ s/$;//g; # Remove any comments
5766 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5767 ERROR("TRAILING_STATEMENTS",
5768 "trailing statements should be on next line\n" . $herecurr);
5771 # if should not continue a brace
5772 if ($line =~ /}\s*if\b/) {
5773 ERROR("TRAILING_STATEMENTS",
5774 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5777 # case and default should not have general statements after them
5778 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5780 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5784 ERROR("TRAILING_STATEMENTS",
5785 "trailing statements should be on next line\n" . $herecurr);
5788 # Check for }<nl>else {, these must be at the same
5789 # indent level to be relevant to each other.
5790 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5791 $previndent == $indent) {
5792 if (ERROR("ELSE_AFTER_BRACE",
5793 "else should follow close brace '}'\n" . $hereprev) &&
5794 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5795 fix_delete_line($fixlinenr - 1, $prevrawline);
5796 fix_delete_line($fixlinenr, $rawline);
5797 my $fixedline = $prevrawline;
5798 $fixedline =~ s/}\s*$//;
5799 if ($fixedline !~ /^\+\s*$/) {
5800 fix_insert_line($fixlinenr, $fixedline);
5802 $fixedline = $rawline;
5803 $fixedline =~ s/^(.\s*)else/$1} else/;
5804 fix_insert_line($fixlinenr, $fixedline);
5808 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5809 $previndent == $indent) {
5810 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5812 # Find out what is on the end of the line after the
5814 substr($s, 0, length($c), '');
5817 if ($s =~ /^\s*;/) {
5818 if (ERROR("WHILE_AFTER_BRACE",
5819 "while should follow close brace '}'\n" . $hereprev) &&
5820 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5821 fix_delete_line($fixlinenr - 1, $prevrawline);
5822 fix_delete_line($fixlinenr, $rawline);
5823 my $fixedline = $prevrawline;
5824 my $trailing = $rawline;
5825 $trailing =~ s/^\+//;
5826 $trailing = trim($trailing);
5827 $fixedline =~ s/}\s*$/} $trailing/;
5828 fix_insert_line($fixlinenr, $fixedline);
5833 #Specific variable tests
5834 while ($line =~ m{($Constant|$Lval)}g) {
5838 if ($var !~ /^$Constant$/ &&
5839 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5840 #Ignore some autogenerated defines and enum values
5841 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5842 #Ignore Page<foo> variants
5843 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5844 #Ignore ETHTOOL_LINK_MODE_<foo> variants
5845 $var !~ /^ETHTOOL_LINK_MODE_/ &&
5846 #Ignore SI style variants like nS, mV and dB
5847 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5848 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5849 #Ignore some three character SI units explicitly, like MiB and KHz
5850 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5851 while ($var =~ m{\b($Ident)}g) {
5853 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5855 seed_camelcase_includes();
5856 if (!$file && !$camelcase_file_seeded) {
5857 seed_camelcase_file($realfile);
5858 $camelcase_file_seeded = 1;
5861 if (!defined $camelcase{$word}) {
5862 $camelcase{$word} = 1;
5864 "Avoid CamelCase: <$word>\n" . $herecurr);
5870 #no spaces allowed after \ in define
5871 if ($line =~ /\#\s*define.*\\\s+$/) {
5872 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5873 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5875 $fixed[$fixlinenr] =~ s/\s+$//;
5879 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5880 # itself <asm/foo.h> (uses RAW line)
5881 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5883 my $checkfile = "include/linux/$file";
5884 if (-f "$root/$checkfile" &&
5885 $realfile ne $checkfile &&
5886 $1 !~ /$allowed_asm_includes/)
5888 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5889 if ($asminclude > 0) {
5890 if ($realfile =~ m{^arch/}) {
5891 CHK("ARCH_INCLUDE_LINUX",
5892 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5894 WARN("INCLUDE_LINUX",
5895 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5901 # multi-statement macros should be enclosed in a do while loop, grab the
5902 # first statement and ensure its the whole macro if its not enclosed
5903 # in a known good container
5904 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5905 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5908 my ($off, $dstat, $dcond, $rest);
5910 my $has_flow_statement = 0;
5911 my $has_arg_concat = 0;
5912 ($dstat, $dcond, $ln, $cnt, $off) =
5913 ctx_statement_block($linenr, $realcnt, 0);
5915 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5916 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5918 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5919 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5921 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5922 my $define_args = $1;
5923 my $define_stmt = $dstat;
5926 if (defined $define_args && $define_args ne "") {
5927 $define_args = substr($define_args, 1, length($define_args) - 2);
5928 $define_args =~ s/\s*//g;
5929 $define_args =~ s/\\\+?//g;
5930 @def_args = split(",", $define_args);
5934 $dstat =~ s/\\\n.//g;
5935 $dstat =~ s/^\s*//s;
5936 $dstat =~ s/\s*$//s;
5938 # Flatten any parentheses and braces
5939 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5940 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5941 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5945 # Flatten any obvious string concatenation.
5946 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5947 $dstat =~ s/$Ident\s*($String)/$1/)
5951 # Make asm volatile uses seem like a generic function
5952 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5954 my $exceptions = qr{
5967 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5970 my $stmt_cnt = statement_rawlines($ctx);
5971 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5974 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5975 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5976 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5977 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5978 $dstat !~ /$exceptions/ &&
5979 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5980 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5981 $dstat !~ /^case\b/ && # case ...
5982 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5983 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5984 $dstat !~ /^for\s*$Constant$/ && # for (...)
5985 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5986 $dstat !~ /^do\s*{/ && # do {...
5987 $dstat !~ /^\(\{/ && # ({...
5988 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5990 if ($dstat =~ /^\s*if\b/) {
5991 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5992 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5993 } elsif ($dstat =~ /;/) {
5994 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5995 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5997 ERROR("COMPLEX_MACRO",
5998 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
6003 # Make $define_stmt single line, comment-free, etc
6004 my @stmt_array = split('\n', $define_stmt);
6007 foreach my $l (@stmt_array) {
6012 } elsif ($l =~ /^[\+ ]/) {
6013 $define_stmt .= substr($l, 1);
6016 $define_stmt =~ s/$;//g;
6017 $define_stmt =~ s/\s+/ /g;
6018 $define_stmt = trim($define_stmt);
6020 # check if any macro arguments are reused (ignore '...' and 'type')
6021 foreach my $arg (@def_args) {
6022 next if ($arg =~ /\.\.\./);
6023 next if ($arg =~ /^type$/i);
6024 my $tmp_stmt = $define_stmt;
6025 $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;
6026 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6027 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
6028 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6030 CHK("MACRO_ARG_REUSE",
6031 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6033 # check if any macro arguments may have other precedence issues
6034 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6035 ((defined($1) && $1 ne ',') ||
6036 (defined($2) && $2 ne ','))) {
6037 CHK("MACRO_ARG_PRECEDENCE",
6038 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6042 # check for macros with flow control, but without ## concatenation
6043 # ## concatenation is commonly a macro that defines a function so ignore those
6044 if ($has_flow_statement && !$has_arg_concat) {
6045 my $cnt = statement_rawlines($ctx);
6046 my $herectx = get_stat_here($linenr, $cnt, $here);
6048 WARN("MACRO_WITH_FLOW_CONTROL",
6049 "Macros with flow control statements should be avoided\n" . "$herectx");
6052 # check for line continuations outside of #defines, preprocessor #, and asm
6055 if ($prevline !~ /^..*\\$/ &&
6056 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6057 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
6058 $line =~ /^\+.*\\$/) {
6059 WARN("LINE_CONTINUATIONS",
6060 "Avoid unnecessary line continuations\n" . $herecurr);
6064 # do {} while (0) macro tests:
6065 # single-statement macros do not need to be enclosed in do while (0) loop,
6066 # macro should not end with a semicolon
6067 if ($perl_version_ok &&
6068 $realfile !~ m@/vmlinux.lds.h$@ &&
6069 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6072 my ($off, $dstat, $dcond, $rest);
6074 ($dstat, $dcond, $ln, $cnt, $off) =
6075 ctx_statement_block($linenr, $realcnt, 0);
6078 $dstat =~ s/\\\n.//g;
6081 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6086 my $cnt = statement_rawlines($ctx);
6087 my $herectx = get_stat_here($linenr, $cnt, $here);
6089 if (($stmts =~ tr/;/;/) == 1 &&
6090 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6091 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6092 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6094 if (defined $semis && $semis ne "") {
6095 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6096 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6098 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6100 my $cnt = statement_rawlines($ctx);
6101 my $herectx = get_stat_here($linenr, $cnt, $here);
6103 WARN("TRAILING_SEMICOLON",
6104 "macros should not use a trailing semicolon\n" . "$herectx");
6108 # check for redundant bracing round if etc
6109 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6110 my ($level, $endln, @chunks) =
6111 ctx_statement_full($linenr, $realcnt, 1);
6112 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6113 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6114 if ($#chunks > 0 && $level == 0) {
6118 my $herectx = $here . "\n";
6119 my $ln = $linenr - 1;
6120 for my $chunk (@chunks) {
6121 my ($cond, $block) = @{$chunk};
6123 # If the condition carries leading newlines, then count those as offsets.
6124 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6125 my $offset = statement_rawlines($whitespace) - 1;
6127 $allowed[$allow] = 0;
6128 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6130 # We have looked at and allowed this specific line.
6131 $suppress_ifbraces{$ln + $offset} = 1;
6133 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6134 $ln += statement_rawlines($block) - 1;
6136 substr($block, 0, length($cond), '');
6138 $seen++ if ($block =~ /^\s*{/);
6140 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6141 if (statement_lines($cond) > 1) {
6142 #print "APW: ALLOWED: cond<$cond>\n";
6143 $allowed[$allow] = 1;
6145 if ($block =~/\b(?:if|for|while)\b/) {
6146 #print "APW: ALLOWED: block<$block>\n";
6147 $allowed[$allow] = 1;
6149 if (statement_block_size($block) > 1) {
6150 #print "APW: ALLOWED: lines block<$block>\n";
6151 $allowed[$allow] = 1;
6156 my $sum_allowed = 0;
6157 foreach (@allowed) {
6160 if ($sum_allowed == 0) {
6162 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6163 } elsif ($sum_allowed != $allow &&
6166 "braces {} should be used on all arms of this statement\n" . $herectx);
6171 if (!defined $suppress_ifbraces{$linenr - 1} &&
6172 $line =~ /\b(if|while|for|else)\b/) {
6175 # Check the pre-context.
6176 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6177 #print "APW: ALLOWED: pre<$1>\n";
6181 my ($level, $endln, @chunks) =
6182 ctx_statement_full($linenr, $realcnt, $-[0]);
6184 # Check the condition.
6185 my ($cond, $block) = @{$chunks[0]};
6186 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6187 if (defined $cond) {
6188 substr($block, 0, length($cond), '');
6190 if (statement_lines($cond) > 1) {
6191 #print "APW: ALLOWED: cond<$cond>\n";
6194 if ($block =~/\b(?:if|for|while)\b/) {
6195 #print "APW: ALLOWED: block<$block>\n";
6198 if (statement_block_size($block) > 1) {
6199 #print "APW: ALLOWED: lines block<$block>\n";
6202 # Check the post-context.
6203 if (defined $chunks[1]) {
6204 my ($cond, $block) = @{$chunks[1]};
6205 if (defined $cond) {
6206 substr($block, 0, length($cond), '');
6208 if ($block =~ /^\s*\{/) {
6209 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6213 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6214 my $cnt = statement_rawlines($block);
6215 my $herectx = get_stat_here($linenr, $cnt, $here);
6218 "braces {} are not necessary for single statement blocks\n" . $herectx);
6222 # check for single line unbalanced braces
6223 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6224 $sline =~ /^.\s*else\s*\{\s*$/) {
6225 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6228 # check for unnecessary blank lines around braces
6229 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6231 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6232 $fix && $prevrawline =~ /^\+/) {
6233 fix_delete_line($fixlinenr - 1, $prevrawline);
6236 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6238 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6240 fix_delete_line($fixlinenr, $rawline);
6244 # no volatiles please
6245 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6246 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6248 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6251 # Check for user-visible strings broken across lines, which breaks the ability
6252 # to grep for the string. Make exceptions when the previous string ends in a
6253 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6254 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6255 if ($line =~ /^\+\s*$String/ &&
6256 $prevline =~ /"\s*$/ &&
6257 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6258 if (WARN("SPLIT_STRING",
6259 "quoted string split across lines\n" . $hereprev) &&
6261 $prevrawline =~ /^\+.*"\s*$/ &&
6262 $last_coalesced_string_linenr != $linenr - 1) {
6263 my $extracted_string = get_quoted_string($line, $rawline);
6264 my $comma_close = "";
6265 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6269 fix_delete_line($fixlinenr - 1, $prevrawline);
6270 fix_delete_line($fixlinenr, $rawline);
6271 my $fixedline = $prevrawline;
6272 $fixedline =~ s/"\s*$//;
6273 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6274 fix_insert_line($fixlinenr - 1, $fixedline);
6275 $fixedline = $rawline;
6276 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6277 if ($fixedline !~ /\+\s*$/) {
6278 fix_insert_line($fixlinenr, $fixedline);
6280 $last_coalesced_string_linenr = $linenr;
6284 # check for missing a space in a string concatenation
6285 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6286 WARN('MISSING_SPACE',
6287 "break quoted strings at a space character\n" . $hereprev);
6290 # check for an embedded function name in a string when the function is known
6291 # This does not work very well for -f --file checking as it depends on patch
6292 # context providing the function name or a single line form for in-file
6293 # function declarations
6294 if ($line =~ /^\+.*$String/ &&
6295 defined($context_function) &&
6296 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6297 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6298 WARN("EMBEDDED_FUNCTION_NAME",
6299 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6302 # check for unnecessary function tracing like uses
6303 # This does not use $logFunctions because there are many instances like
6304 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6305 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6306 if (WARN("TRACING_LOGGING",
6307 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6309 fix_delete_line($fixlinenr, $rawline);
6313 # check for spaces before a quoted newline
6314 if ($rawline =~ /^.*\".*\s\\n/) {
6315 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6316 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6318 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6323 # concatenated string without spaces between elements
6324 if ($line =~ /$String[A-Z_]/ ||
6325 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6326 if (CHK("CONCATENATED_STRING",
6327 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6329 while ($line =~ /($String)/g) {
6330 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6331 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6332 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6337 # uncoalesced string fragments
6338 if ($line =~ /$String\s*[Lu]?"/) {
6339 if (WARN("STRING_FRAGMENTS",
6340 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6342 while ($line =~ /($String)(?=\s*")/g) {
6343 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6344 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6349 # check for non-standard and hex prefixed decimal printf formats
6350 my $show_L = 1; #don't show the same defect twice
6352 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6353 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6354 $string =~ s/%%/__/g;
6356 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6358 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6362 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6364 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6367 # check for 0x<decimal>
6368 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6369 ERROR("PRINTF_0XDECIMAL",
6370 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6374 # check for line continuations in quoted strings with odd counts of "
6375 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6376 WARN("LINE_CONTINUATIONS",
6377 "Avoid line continuations in quoted strings\n" . $herecurr);
6381 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6383 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6387 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6389 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6392 # check for needless "if (<foo>) fn(<foo>)" uses
6393 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6394 my $tested = quotemeta($1);
6395 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6396 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6398 if (WARN('NEEDLESS_IF',
6399 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6402 my $leading_tabs = "";
6403 my $new_leading_tabs = "";
6404 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6409 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6410 $new_leading_tabs = $1;
6411 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6418 fix_delete_line($fixlinenr - 1, $prevrawline);
6419 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6425 # check for soon-to-be-deprecated single-argument k[v]free_rcu() API
6426 if ($line =~ /\bk[v]?free_rcu\s*\([^(]+\)/) {
6427 if ($line =~ /\bk[v]?free_rcu\s*\([^,]+\)/) {
6428 ERROR("DEPRECATED_API",
6429 "Single-argument k[v]free_rcu() API is deprecated, please pass rcu_head object or call k[v]free_rcu_mightsleep()." . $herecurr);
6434 # check for unnecessary "Out of Memory" messages
6435 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6436 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6437 (defined $1 || defined $3) &&
6440 my $testline = $lines[$linenr - 3];
6442 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6443 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6445 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6446 $s !~ /\b__GFP_NOWARN\b/ ) {
6448 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6452 # check for logging functions with KERN_<LEVEL>
6453 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6454 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6456 if (WARN("UNNECESSARY_KERN_LEVEL",
6457 "Possible unnecessary $level\n" . $herecurr) &&
6459 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6463 # check for logging continuations
6464 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6465 WARN("LOGGING_CONTINUATION",
6466 "Avoid logging continuation uses where feasible\n" . $herecurr);
6469 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6470 if (defined $stat &&
6471 $line =~ /\b$logFunctions\s*\(/ &&
6472 index($stat, '"') >= 0) {
6473 my $lc = $stat =~ tr@\n@@;
6474 $lc = $lc + $linenr;
6475 my $stat_real = get_stat_real($linenr, $lc);
6476 pos($stat_real) = index($stat_real, '"');
6477 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6480 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6481 if (WARN("UNNECESSARY_MODIFIER",
6482 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6483 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6486 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6491 # check for mask then right shift without a parentheses
6492 if ($perl_version_ok &&
6493 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6494 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6495 WARN("MASK_THEN_SHIFT",
6496 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6499 # check for pointer comparisons to NULL
6500 if ($perl_version_ok) {
6501 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6504 $equal = "" if ($4 eq "!=");
6505 if (CHK("COMPARISON_TO_NULL",
6506 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6508 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6513 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6514 if ($line =~ /(\b$InitAttribute\b)/) {
6516 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6519 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6520 ERROR("MISPLACED_INIT",
6521 "$attr should be placed after $var\n" . $herecurr)) ||
6522 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6523 WARN("MISPLACED_INIT",
6524 "$attr should be placed after $var\n" . $herecurr))) &&
6526 $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;
6531 # check for $InitAttributeData (ie: __initdata) with const
6532 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6534 $attr =~ /($InitAttributePrefix)(.*)/;
6535 my $attr_prefix = $1;
6537 if (ERROR("INIT_ATTRIBUTE",
6538 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6540 $fixed[$fixlinenr] =~
6541 s/$InitAttributeData/${attr_prefix}initconst/;
6545 # check for $InitAttributeConst (ie: __initconst) without const
6546 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6548 if (ERROR("INIT_ATTRIBUTE",
6549 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6551 my $lead = $fixed[$fixlinenr] =~
6552 /(^\+\s*(?:static\s+))/;
6554 $lead = "$lead " if ($lead !~ /^\+$/);
6555 $lead = "${lead}const ";
6556 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6560 # check for __read_mostly with const non-pointer (should just be const)
6561 if ($line =~ /\b__read_mostly\b/ &&
6562 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6563 if (ERROR("CONST_READ_MOSTLY",
6564 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6566 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6570 # don't use __constant_<foo> functions outside of include/uapi/
6571 if ($realfile !~ m@^include/uapi/@ &&
6572 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6573 my $constant_func = $1;
6574 my $func = $constant_func;
6575 $func =~ s/^__constant_//;
6576 if (WARN("CONSTANT_CONVERSION",
6577 "$constant_func should be $func\n" . $herecurr) &&
6579 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6583 # prefer usleep_range over udelay
6584 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6586 # ignore udelay's < 10, however
6587 if (! ($delay < 10) ) {
6589 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6591 if ($delay > 2000) {
6593 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6597 # warn about unexpectedly long msleep's
6598 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6601 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6605 # check for comparisons of jiffies
6606 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6607 WARN("JIFFIES_COMPARISON",
6608 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6611 # check for comparisons of get_jiffies_64()
6612 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6613 WARN("JIFFIES_COMPARISON",
6614 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6617 # warn about #ifdefs in C files
6618 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6619 # print "#ifdef in C files should be avoided\n";
6620 # print "$herecurr";
6624 # warn about spacing in #ifdefs
6625 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6626 if (ERROR("SPACING",
6627 "exactly one space required after that #$1\n" . $herecurr) &&
6629 $fixed[$fixlinenr] =~
6630 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6635 # check for spinlock_t definitions without a comment.
6636 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6637 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6639 if (!ctx_has_comment($first_line, $linenr)) {
6640 CHK("UNCOMMENTED_DEFINITION",
6641 "$1 definition without comment\n" . $herecurr);
6644 # check for memory barriers without a comment.
6651 my $barrier_stems = qr{
6659 my $all_barriers = qr{
6661 smp_(?:$barrier_stems)|
6662 virt_(?:$barrier_stems)
6665 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6666 if (!ctx_has_comment($first_line, $linenr)) {
6667 WARN("MEMORY_BARRIER",
6668 "memory barrier without comment\n" . $herecurr);
6672 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6674 if ($realfile !~ m@^include/asm-generic/@ &&
6675 $realfile !~ m@/barrier\.h$@ &&
6676 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6677 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6678 WARN("MEMORY_BARRIER",
6679 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6682 # check for waitqueue_active without a comment.
6683 if ($line =~ /\bwaitqueue_active\s*\(/) {
6684 if (!ctx_has_comment($first_line, $linenr)) {
6685 WARN("WAITQUEUE_ACTIVE",
6686 "waitqueue_active without comment\n" . $herecurr);
6690 # check for data_race without a comment.
6691 if ($line =~ /\bdata_race\s*\(/) {
6692 if (!ctx_has_comment($first_line, $linenr)) {
6694 "data_race without comment\n" . $herecurr);
6698 # check of hardware specific defines
6699 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6701 "architecture specific defines should be avoided\n" . $herecurr);
6704 # check that the storage class is not after a type
6705 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6706 WARN("STORAGE_CLASS",
6707 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6709 # Check that the storage class is at the beginning of a declaration
6710 if ($line =~ /\b$Storage\b/ &&
6711 $line !~ /^.\s*$Storage/ &&
6712 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6713 $1 !~ /[\,\)]\s*$/) {
6714 WARN("STORAGE_CLASS",
6715 "storage class should be at the beginning of the declaration\n" . $herecurr);
6718 # check the location of the inline attribute, that it is between
6719 # storage class and type.
6720 if ($line =~ /\b$Type\s+$Inline\b/ ||
6721 $line =~ /\b$Inline\s+$Storage\b/) {
6722 ERROR("INLINE_LOCATION",
6723 "inline keyword should sit between storage class and type\n" . $herecurr);
6726 # Check for __inline__ and __inline, prefer inline
6727 if ($realfile !~ m@\binclude/uapi/@ &&
6728 $line =~ /\b(__inline__|__inline)\b/) {
6730 "plain inline is preferred over $1\n" . $herecurr) &&
6732 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6737 # Check for compiler attributes
6738 if ($realfile !~ m@\binclude/uapi/@ &&
6739 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6741 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6744 "alias" => "__alias",
6745 "aligned" => "__aligned",
6746 "always_inline" => "__always_inline",
6747 "assume_aligned" => "__assume_aligned",
6749 "const" => "__attribute_const__",
6751 "designated_init" => "__designated_init",
6752 "externally_visible" => "__visible",
6753 "format" => "printf|scanf",
6754 "gnu_inline" => "__gnu_inline",
6755 "malloc" => "__malloc",
6757 "no_caller_saved_registers" => "__no_caller_saved_registers",
6758 "noclone" => "__noclone",
6759 "noinline" => "noinline",
6760 "nonstring" => "__nonstring",
6761 "noreturn" => "__noreturn",
6762 "packed" => "__packed",
6764 "section" => "__section",
6769 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6772 $params = $2 if defined($2);
6773 my $curr_attr = $orig_attr;
6774 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6775 if (exists($attr_list{$curr_attr})) {
6776 my $new = $attr_list{$curr_attr};
6777 if ($curr_attr eq "format" && $params) {
6778 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6781 $new = "$new$params";
6783 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6784 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6786 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6787 $fixed[$fixlinenr] =~ s/$remove//;
6788 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6789 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6790 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6795 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6796 if ($attr =~ /^_*unused/) {
6797 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6798 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6802 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6803 if ($perl_version_ok &&
6804 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6805 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6806 $line =~ /\b__weak\b/)) {
6807 ERROR("WEAK_DECLARATION",
6808 "Using weak declarations can have unintended link defects\n" . $herecurr);
6811 # check for c99 types like uint8_t used outside of uapi/ and tools/
6812 if ($realfile !~ m@\binclude/uapi/@ &&
6813 $realfile !~ m@\btools/@ &&
6814 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6816 if ($type =~ /\b($typeC99Typedefs)\b/) {
6818 my $kernel_type = 'u';
6819 $kernel_type = 's' if ($type =~ /^_*[si]/);
6822 if (CHK("PREFER_KERNEL_TYPES",
6823 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6825 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6830 # check for cast of C90 native int or longer types constants
6831 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6835 my $newconst = $const;
6836 $newconst =~ s/${Int_type}$//;
6837 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6838 if ($cast =~ /\blong\s+long\b/) {
6840 } elsif ($cast =~ /\blong\b/) {
6843 if (WARN("TYPECAST_INT_CONSTANT",
6844 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6846 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6850 # check for sizeof(&)
6851 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6852 WARN("SIZEOF_ADDRESS",
6853 "sizeof(& should be avoided\n" . $herecurr);
6856 # check for sizeof without parenthesis
6857 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6858 if (WARN("SIZEOF_PARENTHESIS",
6859 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6861 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6865 # check for struct spinlock declarations
6866 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6867 WARN("USE_SPINLOCK_T",
6868 "struct spinlock should be spinlock_t\n" . $herecurr);
6871 # check for seq_printf uses that could be seq_puts
6872 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6873 my $fmt = get_quoted_string($line, $rawline);
6876 if (WARN("PREFER_SEQ_PUTS",
6877 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6879 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6884 # check for vsprintf extension %p<foo> misuses
6885 if ($perl_version_ok &&
6887 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6888 $1 !~ /^_*volatile_*$/) {
6891 my $lc = $stat =~ tr@\n@@;
6892 $lc = $lc + $linenr;
6893 for (my $count = $linenr; $count <= $lc; $count++) {
6897 my $bad_specifier = "";
6898 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6901 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6905 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6906 ($extension eq "f" &&
6907 defined $qualifier && $qualifier !~ /^w/) ||
6908 ($extension eq "4" &&
6909 defined $qualifier && $qualifier !~ /^cc/)) {
6910 $bad_specifier = $specifier;
6913 if ($extension eq "x" && !defined($stat_real)) {
6914 if (!defined($stat_real)) {
6915 $stat_real = get_stat_real($linenr, $lc);
6917 WARN("VSPRINTF_SPECIFIER_PX",
6918 "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");
6921 if ($bad_specifier ne "") {
6922 my $stat_real = get_stat_real($linenr, $lc);
6923 my $msg_level = \&WARN;
6924 my $ext_type = "Invalid";
6926 if ($bad_specifier =~ /p[Ff]/) {
6927 $use = " - use %pS instead";
6928 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6929 } elsif ($bad_specifier =~ /pA/) {
6930 $use = " - '%pA' is only intended to be used from Rust code";
6931 $msg_level = \&ERROR;
6934 &{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6935 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6940 # Check for misused memsets
6941 if ($perl_version_ok &&
6943 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6949 if ($ms_size =~ /^(0x|)0$/i) {
6951 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6952 } elsif ($ms_size =~ /^(0x|)1$/i) {
6954 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6958 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6959 # if ($perl_version_ok &&
6961 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6962 # if (WARN("PREFER_ETHER_ADDR_COPY",
6963 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6965 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6969 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6970 # if ($perl_version_ok &&
6972 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6973 # WARN("PREFER_ETHER_ADDR_EQUAL",
6974 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6977 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6978 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6979 # if ($perl_version_ok &&
6981 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6985 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6986 # if (WARN("PREFER_ETH_ZERO_ADDR",
6987 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6989 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6991 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6992 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6993 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6995 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
7000 # strcpy uses that should likely be strscpy
7001 if ($line =~ /\bstrcpy\s*\(/) {
7003 "Prefer strscpy over strcpy - see: https://github.com/KSPP/linux/issues/88\n" . $herecurr);
7006 # strlcpy uses that should likely be strscpy
7007 if ($line =~ /\bstrlcpy\s*\(/) {
7009 "Prefer strscpy over strlcpy - see: https://github.com/KSPP/linux/issues/89\n" . $herecurr);
7012 # strncpy uses that should likely be strscpy or strscpy_pad
7013 if ($line =~ /\bstrncpy\s*\(/) {
7015 "Prefer strscpy, strscpy_pad, or __nonstring over strncpy - see: https://github.com/KSPP/linux/issues/90\n" . $herecurr);
7018 # typecasts on min/max could be min_t/max_t
7019 if ($perl_version_ok &&
7021 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7022 if (defined $2 || defined $7) {
7024 my $cast1 = deparenthesize($2);
7026 my $cast2 = deparenthesize($7);
7030 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7031 $cast = "$cast1 or $cast2";
7032 } elsif ($cast1 ne "") {
7038 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7042 # check usleep_range arguments
7043 if ($perl_version_ok &&
7045 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7049 WARN("USLEEP_RANGE",
7050 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7051 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7053 WARN("USLEEP_RANGE",
7054 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7058 # check for naked sscanf
7059 if ($perl_version_ok &&
7061 $line =~ /\bsscanf\b/ &&
7062 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7063 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7064 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7065 my $lc = $stat =~ tr@\n@@;
7066 $lc = $lc + $linenr;
7067 my $stat_real = get_stat_real($linenr, $lc);
7068 WARN("NAKED_SSCANF",
7069 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7072 # check for simple sscanf that should be kstrto<foo>
7073 if ($perl_version_ok &&
7075 $line =~ /\bsscanf\b/) {
7076 my $lc = $stat =~ tr@\n@@;
7077 $lc = $lc + $linenr;
7078 my $stat_real = get_stat_real($linenr, $lc);
7079 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7081 my $count = $format =~ tr@%@%@;
7083 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7084 WARN("SSCANF_TO_KSTRTO",
7085 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7090 # check for new externs in .h files.
7091 if ($realfile =~ /\.h$/ &&
7092 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7093 if (CHK("AVOID_EXTERNS",
7094 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
7096 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7100 # check for new externs in .c files.
7101 if ($realfile =~ /\.c$/ && defined $stat &&
7102 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7104 my $function_name = $1;
7105 my $paren_space = $2;
7108 if (defined $cond) {
7109 substr($s, 0, length($cond), '');
7113 WARN("AVOID_EXTERNS",
7114 "externs should be avoided in .c files\n" . $herecurr);
7117 if ($paren_space =~ /\n/) {
7118 WARN("FUNCTION_ARGUMENTS",
7119 "arguments for function declarations should follow identifier\n" . $herecurr);
7122 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7123 $stat =~ /^.\s*extern\s+/)
7125 WARN("AVOID_EXTERNS",
7126 "externs should be avoided in .c files\n" . $herecurr);
7129 # check for function declarations that have arguments without identifier names
7130 if (defined $stat &&
7131 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7133 my $args = trim($1);
7134 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7136 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7137 WARN("FUNCTION_ARGUMENTS",
7138 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7143 # check for function definitions
7144 if ($perl_version_ok &&
7146 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7147 $context_function = $1;
7149 # check for multiline function definition with misplaced open brace
7151 my $cnt = statement_rawlines($stat);
7152 my $herectx = $here . "\n";
7153 for (my $n = 0; $n < $cnt; $n++) {
7154 my $rl = raw_line($linenr, $n);
7155 $herectx .= $rl . "\n";
7156 $ok = 1 if ($rl =~ /^[ \+]\{/);
7157 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7158 last if $rl =~ /^[ \+].*\{/;
7162 "open brace '{' following function definitions go on the next line\n" . $herectx);
7166 # checks for new __setup's
7167 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7170 if (!grep(/$name/, @setup_docs)) {
7171 CHK("UNDOCUMENTED_SETUP",
7172 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7176 # check for pointless casting of alloc functions
7177 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7178 WARN("UNNECESSARY_CASTS",
7179 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7183 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7184 if ($perl_version_ok &&
7185 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7186 CHK("ALLOC_SIZEOF_STRUCT",
7187 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7190 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7191 if ($perl_version_ok &&
7193 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7197 my $newfunc = "kmalloc_array";
7198 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7199 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7200 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7203 if ($a1 =~ /^sizeof\s*\S/) {
7207 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7208 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7209 my $cnt = statement_rawlines($stat);
7210 my $herectx = get_stat_here($linenr, $cnt, $here);
7212 if (WARN("ALLOC_WITH_MULTIPLY",
7213 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7216 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
7221 # check for krealloc arg reuse
7222 if ($perl_version_ok &&
7223 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7225 WARN("KREALLOC_ARG_REUSE",
7226 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7229 # check for alloc argument mismatch
7230 if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
7231 WARN("ALLOC_ARRAY_ARGS",
7232 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7235 # check for multiple semicolons
7236 if ($line =~ /;\s*;\s*$/) {
7237 if (WARN("ONE_SEMICOLON",
7238 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7240 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7244 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7245 if ($realfile !~ m@^include/uapi/@ &&
7246 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7248 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7249 if (CHK("BIT_MACRO",
7250 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7252 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7256 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7257 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7258 WARN("IS_ENABLED_CONFIG",
7259 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7262 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7263 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7265 if (WARN("PREFER_IS_ENABLED",
7266 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7268 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7272 # check for /* fallthrough */ like comment, prefer fallthrough;
7273 my @fallthroughs = (
7276 'lint -fallthrough[ \t]*',
7277 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7278 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7279 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7280 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7282 if ($raw_comment ne '') {
7283 foreach my $ft (@fallthroughs) {
7284 if ($raw_comment =~ /$ft/) {
7285 my $msg_level = \&WARN;
7286 $msg_level = \&CHK if ($file);
7287 &{$msg_level}("PREFER_FALLTHROUGH",
7288 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7294 # check for switch/default statements without a break;
7295 if ($perl_version_ok &&
7297 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7298 my $cnt = statement_rawlines($stat);
7299 my $herectx = get_stat_here($linenr, $cnt, $here);
7301 WARN("DEFAULT_NO_BREAK",
7302 "switch default: should use break\n" . $herectx);
7305 # check for gcc specific __FUNCTION__
7306 if ($line =~ /\b__FUNCTION__\b/) {
7307 if (WARN("USE_FUNC",
7308 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7310 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7314 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7315 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7317 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7320 # check for use of yield()
7321 if ($line =~ /\byield\s*\(\s*\)/) {
7323 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7326 # check for comparisons against true and false
7327 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7335 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7337 my $type = lc($otype);
7338 if ($type =~ /^(?:true|false)$/) {
7339 if (("$test" eq "==" && "$type" eq "true") ||
7340 ("$test" eq "!=" && "$type" eq "false")) {
7344 CHK("BOOL_COMPARISON",
7345 "Using comparison to $otype is error prone\n" . $herecurr);
7347 ## maybe suggesting a correct construct would better
7348 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7353 # check for semaphores initialized locked
7354 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7355 WARN("CONSIDER_COMPLETION",
7356 "consider using a completion\n" . $herecurr);
7359 # recommend kstrto* over simple_strto* and strict_strto*
7360 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7361 WARN("CONSIDER_KSTRTO",
7362 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7365 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7366 if ($line =~ /^.\s*__initcall\s*\(/) {
7367 WARN("USE_DEVICE_INITCALL",
7368 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7371 # check for spin_is_locked(), suggest lockdep instead
7372 if ($line =~ /\bspin_is_locked\(/) {
7374 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7377 # check for deprecated apis
7378 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7379 my $deprecated_api = $1;
7380 my $new_api = $deprecated_apis{$deprecated_api};
7381 WARN("DEPRECATED_API",
7382 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7385 # check for various structs that are normally const (ops, kgdb, device_tree)
7386 # and avoid what seem like struct definitions 'struct foo {'
7387 if (defined($const_structs) &&
7388 $line !~ /\bconst\b/ &&
7389 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7390 WARN("CONST_STRUCT",
7391 "struct $1 should normally be const\n" . $herecurr);
7394 # use of NR_CPUS is usually wrong
7395 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7396 # ignore designated initializers using NR_CPUS
7397 if ($line =~ /\bNR_CPUS\b/ &&
7398 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7399 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7400 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7401 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7402 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7403 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7406 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7409 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7410 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7411 ERROR("DEFINE_ARCH_HAS",
7412 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7415 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7416 if ($perl_version_ok &&
7417 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7418 WARN("LIKELY_MISUSE",
7419 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7422 # return sysfs_emit(foo, fmt, ...) fmt without newline
7423 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7424 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7425 my $offset = $+[6] - 1;
7426 if (WARN("SYSFS_EMIT",
7427 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7429 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7433 # check for array definition/declarations that should use flexible arrays instead
7434 if ($sline =~ /^[\+ ]\s*\}(?:\s*__packed)?\s*;\s*$/ &&
7435 $prevline =~ /^\+\s*(?:\}(?:\s*__packed\s*)?|$Type)\s*$Ident\s*\[\s*(0|1)\s*\]\s*;\s*$/) {
7436 if (ERROR("FLEXIBLE_ARRAY",
7437 "Use C99 flexible arrays - see https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays\n" . $hereprev) &&
7438 $1 == '0' && $fix) {
7439 $fixed[$fixlinenr - 1] =~ s/\[\s*0\s*\]/[]/;
7443 # nested likely/unlikely calls
7444 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7445 WARN("LIKELY_MISUSE",
7446 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7449 # whine mightly about in_atomic
7450 if ($line =~ /\bin_atomic\s*\(/) {
7451 if ($realfile =~ m@^drivers/@) {
7453 "do not use in_atomic in drivers\n" . $herecurr);
7454 } elsif ($realfile !~ m@^kernel/@) {
7456 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7460 # Complain about RCU Tasks Trace used outside of BPF (and of course, RCU).
7461 our $rcu_trace_funcs = qr{(?x:
7462 rcu_read_lock_trace |
7463 rcu_read_lock_trace_held |
7464 rcu_read_unlock_trace |
7465 call_rcu_tasks_trace |
7466 synchronize_rcu_tasks_trace |
7467 rcu_barrier_tasks_trace |
7468 rcu_request_urgent_qs_task
7470 our $rcu_trace_paths = qr{(?x:
7477 if ($line =~ /\b($rcu_trace_funcs)\s*\(/) {
7478 if ($realfile !~ m{^$rcu_trace_paths}) {
7479 WARN("RCU_TASKS_TRACE",
7480 "use of RCU tasks trace is incorrect outside BPF or core RCU code\n" . $herecurr);
7484 # check for lockdep_set_novalidate_class
7485 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7486 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7487 if ($realfile !~ m@^kernel/lockdep@ &&
7488 $realfile !~ m@^include/linux/lockdep@ &&
7489 $realfile !~ m@^drivers/base/core@) {
7491 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7495 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7496 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7497 WARN("EXPORTED_WORLD_WRITABLE",
7498 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7501 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7502 # and whether or not function naming is typical and if
7503 # DEVICE_ATTR permissions uses are unusual too
7504 if ($perl_version_ok &&
7506 $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*\)/) {
7511 my $octal_perms = perms_to_octal($perms);
7512 if ($show =~ /^${var}_show$/ &&
7513 $store =~ /^${var}_store$/ &&
7514 $octal_perms eq "0644") {
7515 if (WARN("DEVICE_ATTR_RW",
7516 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7518 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7520 } elsif ($show =~ /^${var}_show$/ &&
7521 $store =~ /^NULL$/ &&
7522 $octal_perms eq "0444") {
7523 if (WARN("DEVICE_ATTR_RO",
7524 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7526 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7528 } elsif ($show =~ /^NULL$/ &&
7529 $store =~ /^${var}_store$/ &&
7530 $octal_perms eq "0200") {
7531 if (WARN("DEVICE_ATTR_WO",
7532 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7534 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7536 } elsif ($octal_perms eq "0644" ||
7537 $octal_perms eq "0444" ||
7538 $octal_perms eq "0200") {
7539 my $newshow = "$show";
7540 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7541 my $newstore = $store;
7542 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7544 if ($show ne $newshow) {
7545 $rename .= " '$show' to '$newshow'";
7547 if ($store ne $newstore) {
7548 $rename .= " '$store' to '$newstore'";
7550 WARN("DEVICE_ATTR_FUNCTIONS",
7551 "Consider renaming function(s)$rename\n" . $herecurr);
7553 WARN("DEVICE_ATTR_PERMS",
7554 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7558 # Mode permission misuses where it seems decimal should be octal
7559 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7560 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7561 # specific definition of not visible in sysfs.
7562 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7563 # use the default permissions
7564 if ($perl_version_ok &&
7566 $line =~ /$mode_perms_search/) {
7567 foreach my $entry (@mode_permission_funcs) {
7568 my $func = $entry->[0];
7569 my $arg_pos = $entry->[1];
7571 my $lc = $stat =~ tr@\n@@;
7572 $lc = $lc + $linenr;
7573 my $stat_real = get_stat_real($linenr, $lc);
7578 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7580 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7581 if ($stat =~ /$test/) {
7583 $val = $6 if ($skip_args ne "");
7584 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7585 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7586 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7587 ERROR("NON_OCTAL_PERMISSIONS",
7588 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7590 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7591 ERROR("EXPORTED_WORLD_WRITABLE",
7592 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7598 # check for uses of S_<PERMS> that could be octal for readability
7599 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7601 my $octal = perms_to_octal($oval);
7602 if (WARN("SYMBOLIC_PERMS",
7603 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7605 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7609 # validate content of MODULE_LICENSE against list from include/linux/module.h
7610 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7611 my $extracted_string = get_quoted_string($line, $rawline);
7612 my $valid_licenses = qr{
7615 GPL\ and\ additional\ rights|
7621 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7622 WARN("MODULE_LICENSE",
7623 "unknown module license " . $extracted_string . "\n" . $herecurr);
7625 if (!$file && $extracted_string eq '"GPL v2"') {
7626 if (WARN("MODULE_LICENSE",
7627 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7629 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7634 # check for sysctl duplicate constants
7635 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7636 WARN("DUPLICATED_SYSCTL_CONST",
7637 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7641 # If we have no input at all, then there is nothing to report on
7642 # so just keep quiet.
7643 if ($#rawlines == -1) {
7647 # In mailback mode only produce a report in the negative, for
7648 # things that appear to be patches.
7649 if ($mailback && ($clean == 1 || !$is_patch)) {
7653 # This is not a patch, and we are in 'no-patch' mode so
7655 if (!$chk_patch && !$is_patch) {
7659 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7660 ERROR("NOT_UNIFIED_DIFF",
7661 "Does not appear to be a unified-diff format patch\n");
7663 if ($is_patch && $has_commit_log && $chk_signoff) {
7664 if ($signoff == 0) {
7665 ERROR("MISSING_SIGN_OFF",
7666 "Missing Signed-off-by: line(s)\n");
7667 } elsif ($authorsignoff != 1) {
7668 # authorsignoff values:
7669 # 0 -> missing sign off
7670 # 1 -> sign off identical
7671 # 2 -> names and addresses match, comments mismatch
7672 # 3 -> addresses match, names different
7673 # 4 -> names match, addresses different
7674 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7676 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7678 if ($authorsignoff == 0) {
7679 ERROR("NO_AUTHOR_SIGN_OFF",
7680 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7681 } elsif ($authorsignoff == 2) {
7682 CHK("FROM_SIGN_OFF_MISMATCH",
7683 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7684 } elsif ($authorsignoff == 3) {
7685 WARN("FROM_SIGN_OFF_MISMATCH",
7686 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7687 } elsif ($authorsignoff == 4) {
7688 WARN("FROM_SIGN_OFF_MISMATCH",
7689 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7690 } elsif ($authorsignoff == 5) {
7691 WARN("FROM_SIGN_OFF_MISMATCH",
7692 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7697 print report_dump();
7698 if ($summary && !($clean == 1 && $quiet == 1)) {
7699 print "$filename " if ($summary_file);
7700 print "total: $cnt_error errors, $cnt_warn warnings, " .
7701 (($check)? "$cnt_chk checks, " : "") .
7702 "$cnt_lines lines checked\n";
7706 # If there were any defects found and not already fixing them
7707 if (!$clean and !$fix) {
7710 NOTE: For some of the reported defects, checkpatch may be able to
7711 mechanically convert to the typical style using --fix or --fix-inplace.
7714 # If there were whitespace errors which cleanpatch can fix
7715 # then suggest that.
7716 if ($rpt_cleaners) {
7720 NOTE: Whitespace errors detected.
7721 You may wish to use scripts/cleanpatch or scripts/cleanfile
7726 if ($clean == 0 && $fix &&
7727 ("@rawlines" ne "@fixed" ||
7728 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7729 my $newfile = $filename;
7730 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7734 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7736 open($f, '>', $newfile)
7737 or die "$P: Can't open $newfile for write\n";
7738 foreach my $fixed_line (@fixed) {
7741 if ($linecount > 3) {
7742 $fixed_line =~ s/^\+//;
7743 print $f $fixed_line . "\n";
7746 print $f $fixed_line . "\n";
7754 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7756 Do _NOT_ trust the results written to this file.
7757 Do _NOT_ submit these changes without inspecting them for correctness.
7759 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7760 No warranties, expressed or implied...
7768 print "$vname has no obvious style problems and is ready for submission.\n";
7770 print "$vname has style problems, please review.\n";