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);
25 # ATTENTION: easily track modification to this script for OpenOCD.
26 # When possible, don't modify the existing code, don't change its indentation,
27 # but remove it enclosing it within:
33 # Mark every addition within comments
34 # # OpenOCD specific: Begin[: additional comment]
35 # # OpenOCD specific: End
40 my %verbose_messages = ();
41 my %verbose_emitted = ();
62 my $gitroot = $ENV{'GIT_DIR'};
63 $gitroot = ".git" if !defined($gitroot);
71 my $configuration_file = ".checkpatch.conf";
72 my $max_line_length = 100;
73 my $ignore_perl_version = 0;
74 my $minimum_perl_version = 5.10.0;
75 my $min_conf_desc_length = 4;
76 my $spelling_file = "$D/spelling.txt";
78 my $codespellfile = "/usr/share/codespell/dictionary.txt";
79 my $user_codespellfile = "";
80 my $conststructsfile = "$D/const_structs.checkpatch";
81 my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
84 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
85 # git output parsing needs US English output, so first set backtick child process LANGUAGE
86 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
88 my ${CONFIG_} = "CONFIG_";
94 Usage: $P [OPTION]... [FILE]...
99 -v, --verbose verbose mode
100 --no-tree run without a kernel tree
101 --no-signoff do not check for 'Signed-off-by' line
102 --patch treat FILE as patchfile (default)
103 --emacs emacs compile window format
104 --terse one line per report
105 --showfile emit diffed file position, not input file position
106 -g, --git treat FILE as a single commit or git revision range
107 single git commit with:
111 multiple git commits with:
115 git merges are ignored
116 -f, --file treat FILE as regular source file
117 --subjective, --strict enable more subjective tests
118 --list-types list the possible message types
119 --types TYPE(,TYPE2...) show only these comma separated message types
120 --ignore TYPE(,TYPE2...) ignore various comma separated message types
121 --show-types show the specific message type in the output
122 --max-line-length=n set the maximum line length, (default $max_line_length)
123 if exceeded, warn on patches
124 requires --strict for use with --file
125 --min-conf-desc-length=n set the min description length, if shorter, warn
126 --tab-size=n set the number of spaces for tab (default $tabsize)
127 --root=PATH PATH to the kernel tree root
128 --no-summary suppress the per-file summary
129 --mailback only produce a report in case of warnings/errors
130 --summary-file include the filename in summary
131 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
132 'values', 'possible', 'type', and 'attr' (default
134 --test-only=WORD report only warnings/errors containing WORD
136 --fix EXPERIMENTAL - may create horrible results
137 If correctable single-line errors exist, create
138 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
139 with potential errors corrected to the preferred
141 --fix-inplace EXPERIMENTAL - may create horrible results
142 Is the same as --fix, but overwrites the input
143 file. It's your fault if there's no backup or git
144 --ignore-perl-version override checking of perl version. expect
146 --codespell Use the codespell dictionary for spelling/typos
147 (default:$codespellfile)
148 --codespellfile Use this codespell dictionary
149 --typedefsfile Read additional types from this file
150 --color[=WHEN] Use colors 'always', 'never', or only when output
151 is a terminal ('auto'). Default is 'auto'.
152 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
154 -h, --help, --version display this help and exit
156 When FILE is - read standard input.
164 return grep { !$seen{$_}++ } @_;
174 open(my $script, '<', abs_path($P)) or
175 die "$P: Can't read '$P' $!\n";
177 my $text = <$script>;
181 # Also catch when type or level is passed through a variable
182 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
184 if (exists($types{$2})) {
185 $types{$2} .= ",$1" if ($types{$2} ne $1);
190 $types{$2} = "UNDETERMINED";
194 print("#\tMessage type\n\n");
196 print(" ( Color coding: ");
197 print(RED . "ERROR" . RESET);
199 print(YELLOW . "WARNING" . RESET);
201 print(GREEN . "CHECK" . RESET);
203 print("Multiple levels / Undetermined");
207 foreach my $type (sort keys %types) {
208 my $orig_type = $type;
210 my $level = $types{$type};
211 if ($level eq "ERROR") {
212 $type = RED . $type . RESET;
213 } elsif ($level eq "WARN") {
214 $type = YELLOW . $type . RESET;
215 } elsif ($level eq "CHK") {
216 $type = GREEN . $type . RESET;
219 print(++$count . "\t" . $type . "\n");
220 if ($verbose && exists($verbose_messages{$orig_type})) {
221 my $message = $verbose_messages{$orig_type};
222 $message =~ s/\n/\n\t/g;
223 print("\t" . $message . "\n\n");
230 my $conf = which_conf($configuration_file);
233 open(my $conffile, '<', "$conf")
234 or warn "$P: Can't find a readable $configuration_file file $!\n";
236 while (<$conffile>) {
239 $line =~ s/\s*\n?$//g;
243 next if ($line =~ m/^\s*#/);
244 next if ($line =~ m/^\s*$/);
246 my @words = split(" ", $line);
247 foreach my $word (@words) {
248 last if ($word =~ m/^#/);
249 push (@conf_args, $word);
253 unshift(@ARGV, @conf_args) if @conf_args;
257 open(my $docs, '<', "$docsfile")
258 or warn "$P: Can't read the documentation file $docsfile $!\n";
269 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
271 $verbose_messages{$type} = trim($desc);
277 if ($line =~ /^(?:\s{4,}|$)/) {
282 $verbose_messages{$type} = trim($desc);
291 $verbose_messages{$type} = trim($desc);
296 # Perl's Getopt::Long allows options to take optional arguments after a space.
297 # Prevent --color by itself from consuming other arguments
299 if ($_ eq "--color" || $_ eq "-color") {
300 $_ = "--color=$color";
305 'q|quiet+' => \$quiet,
306 'v|verbose!' => \$verbose,
308 'signoff!' => \$chk_signoff,
309 'patch!' => \$chk_patch,
312 'showfile!' => \$showfile,
315 'subjective!' => \$check,
316 'strict!' => \$check,
317 'ignore=s' => \@ignore,
319 'show-types!' => \$show_types,
320 'list-types!' => \$list_types,
321 'max-line-length=i' => \$max_line_length,
322 'min-conf-desc-length=i' => \$min_conf_desc_length,
323 'tab-size=i' => \$tabsize,
325 'summary!' => \$summary,
326 'mailback!' => \$mailback,
327 'summary-file!' => \$summary_file,
329 'fix-inplace!' => \$fix_inplace,
330 'ignore-perl-version!' => \$ignore_perl_version,
331 'debug=s' => \%debug,
332 'test-only=s' => \$tst_only,
333 'codespell!' => \$codespell,
334 'codespellfile=s' => \$user_codespellfile,
335 'typedefsfile=s' => \$typedefsfile,
336 'color=s' => \$color,
337 'no-color' => \$color, #keep old behaviors of -nocolor
338 'nocolor' => \$color, #keep old behaviors of -nocolor
339 'kconfig-prefix=s' => \${CONFIG_},
344 if ($user_codespellfile) {
345 # Use the user provided codespell file unconditionally
346 $codespellfile = $user_codespellfile;
347 } elsif (!(-f $codespellfile)) {
348 # If /usr/share/codespell/dictionary.txt is not present, try to find it
349 # under codespell's install directory: <codespell_root>/data/dictionary.txt
350 if (($codespell || $help) && which("python3") ne "") {
351 my $python_codespell_dict = << "EOF";
355 codespell_dir = op.dirname(codespell_lib.__file__)
356 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
357 print(codespell_file, end='')
360 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
361 $codespellfile = $codespell_dict if (-f $codespell_dict);
365 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
366 # $help is 2 if invalid option is passed - exitcode: 1
367 help($help - 1) if ($help);
369 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
370 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
372 if ($color =~ /^[01]$/) {
374 } elsif ($color =~ /^always$/i) {
376 } elsif ($color =~ /^never$/i) {
378 } elsif ($color =~ /^auto$/i) {
379 $color = (-t STDOUT);
381 die "$P: Invalid color mode: $color\n";
384 load_docs() if ($verbose);
385 list_types(0) if ($list_types);
387 $fix = 1 if ($fix_inplace);
388 $check_orig = $check;
392 my $perl_version_ok = 1;
393 if ($^V && $^V lt $minimum_perl_version) {
394 $perl_version_ok = 0;
395 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
396 exit(1) if (!$ignore_perl_version);
399 #if no filenames are given, push '-' to read patch from stdin
404 # skip TAB size 1 to avoid additional checks on $tabsize - 1
405 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
407 sub hash_save_array_words {
408 my ($hashRef, $arrayRef) = @_;
410 my @array = split(/,/, join(',', @$arrayRef));
411 foreach my $word (@array) {
412 $word =~ s/\s*\n?$//g;
415 $word =~ tr/[a-z]/[A-Z]/;
417 next if ($word =~ m/^\s*#/);
418 next if ($word =~ m/^\s*$/);
424 sub hash_show_words {
425 my ($hashRef, $prefix) = @_;
427 if (keys %$hashRef) {
428 print "\nNOTE: $prefix message types:";
429 foreach my $word (sort keys %$hashRef) {
436 hash_save_array_words(\%ignore_type, \@ignore);
437 hash_save_array_words(\%use_type, \@use);
440 my $dbg_possible = 0;
443 for my $key (keys %debug) {
445 eval "\${dbg_$key} = '$debug{$key}';";
449 my $rpt_cleaners = 0;
458 if (!top_of_kernel_tree($root)) {
459 die "$P: $root: --root does not point at a valid tree\n";
462 if (top_of_kernel_tree('.')) {
464 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
465 top_of_kernel_tree($1)) {
470 if (!defined $root) {
471 print "Must be run from the top-level dir. of a kernel tree\n";
476 my $emitted_corrupt = 0;
479 [A-Za-z_][A-Za-z\d_]*
480 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
482 our $Storage = qr{extern|static|asmlinkage};
496 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
497 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
498 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
499 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
500 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
502 # Notes to $Attribute:
503 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
526 ____cacheline_aligned|
527 ____cacheline_aligned_in_smp|
528 ____cacheline_internodealigned_in_smp|
530 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
533 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
534 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
535 our $Lval = qr{$Ident(?:$Member)*};
537 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
538 our $Binary = qr{(?i)0b[01]+$Int_type?};
539 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
540 our $Int = qr{[0-9]+$Int_type?};
541 our $Octal = qr{0[0-7]+$Int_type?};
542 our $String = qr{(?:\b[Lu])?"[X\t]*"};
543 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
544 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
545 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
546 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
547 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
548 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
549 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
550 our $Arithmetic = qr{\+|-|\*|\/|%};
554 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
557 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
561 our $NonptrTypeMisordered;
562 our $NonptrTypeWithAttr;
566 our $DeclareMisordered;
568 our $NON_ASCII_UTF8 = qr{
569 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
570 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
571 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
572 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
573 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
574 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
575 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
579 [\x09\x0A\x0D\x20-\x7E] # ASCII
583 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
584 our $typeOtherOSTypedefs = qr{(?x:
585 u_(?:char|short|int|long) | # bsd
586 u(?:nchar|short|int|long) # sysv
588 our $typeKernelTypedefs = qr{(?x:
589 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
592 our $typeTypedefs = qr{(?x:
594 $typeOtherOSTypedefs\b|
595 $typeKernelTypedefs\b
598 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
600 our $logFunctions = qr{(?x:
601 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
602 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
604 WARN(?:_RATELIMIT|_ONCE|)|
607 seq_vprintf|seq_printf|seq_puts
610 our $allocFunctions = qr{(?x:
612 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
615 (?:\w+)?alloc_skb(?:_ip_align)? |
616 # dev_alloc_skb/netdev_alloc_skb, et al
620 our $signature_tags = qr{(?xi:
632 our $tracing_logging_tags = qr{(?xi:
656 sub edit_distance_min {
658 my $len = scalar @arr;
659 if ((scalar @arr) < 1) {
660 # if underflow, return
664 for my $i (0 .. ($len-1)) {
665 if ($arr[$i] < $min) {
672 sub get_edit_distance {
673 my ($str1, $str2) = @_;
678 my $len1 = length($str1);
679 my $len2 = length($str2);
680 # two dimensional array storing minimum edit distance
682 for my $i (0 .. $len1) {
683 for my $j (0 .. $len2) {
685 $distance[$i][$j] = $j;
687 $distance[$i][$j] = $i;
688 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
689 $distance[$i][$j] = $distance[$i - 1][$j - 1];
691 my $dist1 = $distance[$i][$j - 1]; #insert distance
692 my $dist2 = $distance[$i - 1][$j]; # remove
693 my $dist3 = $distance[$i - 1][$j - 1]; #replace
694 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
698 return $distance[$len1][$len2];
701 sub find_standard_signature {
703 my @standard_signature_tags = (
704 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
705 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
707 foreach my $signature (@standard_signature_tags) {
708 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
714 our @typeListMisordered = (
715 qr{char\s+(?:un)?signed},
716 qr{int\s+(?:(?:un)?signed\s+)?short\s},
717 qr{int\s+short(?:\s+(?:un)?signed)},
718 qr{short\s+int(?:\s+(?:un)?signed)},
719 qr{(?:un)?signed\s+int\s+short},
720 qr{short\s+(?:un)?signed},
721 qr{long\s+int\s+(?:un)?signed},
722 qr{int\s+long\s+(?:un)?signed},
723 qr{long\s+(?:un)?signed\s+int},
724 qr{int\s+(?:un)?signed\s+long},
725 qr{int\s+(?:un)?signed},
726 qr{int\s+long\s+long\s+(?:un)?signed},
727 qr{long\s+long\s+int\s+(?:un)?signed},
728 qr{long\s+long\s+(?:un)?signed\s+int},
729 qr{long\s+long\s+(?:un)?signed},
730 qr{long\s+(?:un)?signed},
735 qr{(?:(?:un)?signed\s+)?char},
736 qr{(?:(?:un)?signed\s+)?short\s+int},
737 qr{(?:(?:un)?signed\s+)?short},
738 qr{(?:(?:un)?signed\s+)?int},
739 qr{(?:(?:un)?signed\s+)?long\s+int},
740 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
741 qr{(?:(?:un)?signed\s+)?long\s+long},
742 qr{(?:(?:un)?signed\s+)?long},
751 qr{${Ident}_handler},
752 qr{${Ident}_handler_fn},
756 our $C90_int_types = qr{(?x:
757 long\s+long\s+int\s+(?:un)?signed|
758 long\s+long\s+(?:un)?signed\s+int|
759 long\s+long\s+(?:un)?signed|
760 (?:(?:un)?signed\s+)?long\s+long\s+int|
761 (?:(?:un)?signed\s+)?long\s+long|
762 int\s+long\s+long\s+(?:un)?signed|
763 int\s+(?:(?:un)?signed\s+)?long\s+long|
765 long\s+int\s+(?:un)?signed|
766 long\s+(?:un)?signed\s+int|
767 long\s+(?:un)?signed|
768 (?:(?:un)?signed\s+)?long\s+int|
769 (?:(?:un)?signed\s+)?long|
770 int\s+long\s+(?:un)?signed|
771 int\s+(?:(?:un)?signed\s+)?long|
774 (?:(?:un)?signed\s+)?int
777 our @typeListFile = ();
778 our @typeListWithAttr = (
780 qr{struct\s+$InitAttribute\s+$Ident},
781 qr{union\s+$InitAttribute\s+$Ident},
784 our @modifierList = (
787 our @modifierListFile = ();
789 our @mode_permission_funcs = (
791 ["module_param_(?:array|named|string)", 4],
792 ["module_param_array_named", 5],
793 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
794 ["proc_create(?:_data|)", 2],
795 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
796 ["IIO_DEV_ATTR_[A-Z_]+", 1],
797 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
798 ["SENSOR_TEMPLATE(?:_2|)", 3],
802 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
804 #Create a search pattern for all these functions to speed up a loop below
805 our $mode_perms_search = "";
806 foreach my $entry (@mode_permission_funcs) {
807 $mode_perms_search .= '|' if ($mode_perms_search ne "");
808 $mode_perms_search .= $entry->[0];
810 $mode_perms_search = "(?:${mode_perms_search})";
812 our %deprecated_apis = (
813 "synchronize_rcu_bh" => "synchronize_rcu",
814 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
815 "call_rcu_bh" => "call_rcu",
816 "rcu_barrier_bh" => "rcu_barrier",
817 "synchronize_sched" => "synchronize_rcu",
818 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
819 "call_rcu_sched" => "call_rcu",
820 "rcu_barrier_sched" => "rcu_barrier",
821 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
822 "cond_synchronize_sched" => "cond_synchronize_rcu",
825 #Create a search pattern for all these strings to speed up a loop below
826 our $deprecated_apis_search = "";
827 foreach my $entry (keys %deprecated_apis) {
828 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
829 $deprecated_apis_search .= $entry;
831 $deprecated_apis_search = "(?:${deprecated_apis_search})";
833 our $mode_perms_world_writable = qr{
841 our %mode_permission_string_types = (
860 #Create a search pattern for all these strings to speed up a loop below
861 our $mode_perms_string_search = "";
862 foreach my $entry (keys %mode_permission_string_types) {
863 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
864 $mode_perms_string_search .= $entry;
866 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
867 our $multi_mode_perms_string_search = qr{
868 ${single_mode_perms_string_search}
869 (?:\s*\|\s*${single_mode_perms_string_search})*
875 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
882 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
883 $curpos = pos($string);
886 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
888 $to |= $mode_permission_string_types{$match};
889 $val .= '\s*\|\s*' if ($val ne "");
893 $oval =~ s/^\s*\|\s*//;
894 $oval =~ s/\s*\|\s*$//;
895 return sprintf("%04o", $to);
898 our $allowed_asm_includes = qr{(?x:
904 # memory.h: ARM has a custom one
906 # Load common spelling mistakes and build regular expression list.
910 if (open(my $spelling, '<', $spelling_file)) {
911 while (<$spelling>) {
914 $line =~ s/\s*\n?$//g;
917 next if ($line =~ m/^\s*#/);
918 next if ($line =~ m/^\s*$/);
920 my ($suspect, $fix) = split(/\|\|/, $line);
922 $spelling_fix{$suspect} = $fix;
926 warn "No typos will be found - file '$spelling_file': $!\n";
930 if (open(my $spelling, '<', $codespellfile)) {
931 while (<$spelling>) {
934 $line =~ s/\s*\n?$//g;
937 next if ($line =~ m/^\s*#/);
938 next if ($line =~ m/^\s*$/);
939 next if ($line =~ m/, disabled/i);
943 my ($suspect, $fix) = split(/->/, $line);
945 $spelling_fix{$suspect} = $fix;
949 warn "No codespell typos will be found - file '$codespellfile': $!\n";
953 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
956 my ($wordsRef, $file) = @_;
958 if (open(my $words, '<', $file)) {
962 $line =~ s/\s*\n?$//g;
965 next if ($line =~ m/^\s*#/);
966 next if ($line =~ m/^\s*$/);
968 print("$file: '$line' invalid - ignored\n");
972 $$wordsRef .= '|' if (defined $$wordsRef);
983 if (show_type("CONST_STRUCT")) {
984 read_words(\$const_structs, $conststructsfile)
985 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
988 if (defined($typedefsfile)) {
989 my $typeOtherTypedefs;
990 read_words(\$typeOtherTypedefs, $typedefsfile)
991 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
992 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
996 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
997 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
998 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
999 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1000 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1002 (?:$typeTypedefs\b)|
1006 (?:$Modifier\s+|const\s+)*
1008 (?:typeof|__typeof__)\s*\([^\)]*\)|
1009 (?:$typeTypedefs\b)|
1012 (?:\s+$Modifier|\s+const)*
1014 $NonptrTypeMisordered = qr{
1015 (?:$Modifier\s+|const\s+)*
1019 (?:\s+$Modifier|\s+const)*
1021 $NonptrTypeWithAttr = qr{
1022 (?:$Modifier\s+|const\s+)*
1024 (?:typeof|__typeof__)\s*\([^\)]*\)|
1025 (?:$typeTypedefs\b)|
1026 (?:${allWithAttr}\b)
1028 (?:\s+$Modifier|\s+const)*
1032 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1033 (?:\s+$Inline|\s+$Modifier)*
1035 $TypeMisordered = qr{
1036 $NonptrTypeMisordered
1037 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1038 (?:\s+$Inline|\s+$Modifier)*
1040 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1041 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1045 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1047 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1048 # requires at least perl version v5.10.0
1049 # Any use must be runtime checked with $^V
1051 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1052 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1053 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1055 our $declaration_macros = qr{(?x:
1056 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1057 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1058 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1059 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1062 our %allow_repeated_words = (
1069 sub deparenthesize {
1071 return "" if (!defined($string));
1073 while ($string =~ /^\s*\(.*\)\s*$/) {
1074 $string =~ s@^\s*\(\s*@@;
1075 $string =~ s@\s*\)\s*$@@;
1078 $string =~ s@\s+@ @g;
1083 sub seed_camelcase_file {
1086 return if (!(-f $file));
1090 open(my $include_file, '<', "$file")
1091 or warn "$P: Can't read '$file' $!\n";
1092 my $text = <$include_file>;
1093 close($include_file);
1095 my @lines = split('\n', $text);
1097 foreach my $line (@lines) {
1098 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1099 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1101 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1103 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1109 our %maintained_status = ();
1111 sub is_maintained_obsolete {
1112 my ($filename) = @_;
1114 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1116 if (!exists($maintained_status{$filename})) {
1117 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1120 return $maintained_status{$filename} =~ /obsolete/i;
1123 sub is_SPDX_License_valid {
1126 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1128 my $root_path = abs_path($root);
1129 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1130 return 0 if ($status ne "");
1134 my $camelcase_seeded = 0;
1135 sub seed_camelcase_includes {
1136 return if ($camelcase_seeded);
1139 my $camelcase_cache = "";
1140 my @include_files = ();
1142 $camelcase_seeded = 1;
1144 if (-e "$gitroot") {
1145 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1146 chomp $git_last_include_commit;
1147 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1149 my $last_mod_date = 0;
1150 $files = `find $root/include -name "*.h"`;
1151 @include_files = split('\n', $files);
1152 foreach my $file (@include_files) {
1153 my $date = POSIX::strftime("%Y%m%d%H%M",
1154 localtime((stat $file)[9]));
1155 $last_mod_date = $date if ($last_mod_date < $date);
1157 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1160 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1161 open(my $camelcase_file, '<', "$camelcase_cache")
1162 or warn "$P: Can't read '$camelcase_cache' $!\n";
1163 while (<$camelcase_file>) {
1167 close($camelcase_file);
1172 if (-e "$gitroot") {
1173 $files = `${git_command} ls-files "include/*.h"`;
1174 @include_files = split('\n', $files);
1177 foreach my $file (@include_files) {
1178 seed_camelcase_file($file);
1181 if ($camelcase_cache ne "") {
1182 unlink glob ".checkpatch-camelcase.*";
1183 open(my $camelcase_file, '>', "$camelcase_cache")
1184 or warn "$P: Can't write '$camelcase_cache' $!\n";
1185 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1186 print $camelcase_file ("$_\n");
1188 close($camelcase_file);
1192 sub git_is_single_file {
1193 my ($filename) = @_;
1195 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1197 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1198 my $count = $output =~ tr/\n//;
1199 return $count eq 1 && $output =~ m{^${filename}$};
1202 sub git_commit_info {
1203 my ($commit, $id, $desc) = @_;
1205 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1207 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1208 $output =~ s/^\s*//gm;
1209 my @lines = split("\n", $output);
1211 return ($id, $desc) if ($#lines < 0);
1213 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1214 # Maybe one day convert this block of bash into something that returns
1215 # all matching commit ids, but it's very slow...
1217 # echo "checking commits $1..."
1218 # git rev-list --remotes | grep -i "^$1" |
1219 # while read line ; do
1220 # git log --format='%H %s' -1 $line |
1221 # echo "commit $(cut -c 1-12,41-)"
1223 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1224 $lines[0] =~ /^fatal: bad object $commit/) {
1227 $id = substr($lines[0], 0, 12);
1228 $desc = substr($lines[0], 41);
1231 return ($id, $desc);
1234 $chk_signoff = 0 if ($file);
1239 my @fixed_inserted = ();
1240 my @fixed_deleted = ();
1243 # If input is git commits, extract all commits from the commit expressions.
1244 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1245 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1249 foreach my $commit_expr (@ARGV) {
1251 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1252 $git_range = "-$2 $1";
1253 } elsif ($commit_expr =~ m/\.\./) {
1254 $git_range = "$commit_expr";
1256 $git_range = "-1 $commit_expr";
1258 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1259 foreach my $line (split(/\n/, $lines)) {
1260 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1261 next if (!defined($1) || !defined($2));
1264 unshift(@commits, $sha1);
1265 $git_commits{$sha1} = $subject;
1268 die "$P: no git commits after extraction!\n" if (@commits == 0);
1273 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1274 for my $filename (@ARGV) {
1276 my $is_git_file = git_is_single_file($filename);
1277 my $oldfile = $file;
1278 $file = 1 if ($is_git_file);
1280 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1281 die "$P: $filename: git format-patch failed - $!\n";
1283 open($FILE, '-|', "diff -u /dev/null $filename") ||
1284 die "$P: $filename: diff failed - $!\n";
1285 } elsif ($filename eq '-') {
1286 open($FILE, '<&STDIN');
1288 open($FILE, '<', "$filename") ||
1289 die "$P: $filename: open failed - $!\n";
1291 if ($filename eq '-') {
1292 $vname = 'Your patch';
1294 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1300 push(@rawlines, $_);
1301 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1305 if ($#ARGV > 0 && $quiet == 0) {
1306 print '-' x length($vname) . "\n";
1308 print '-' x length($vname) . "\n";
1311 if (!process($filename)) {
1317 @fixed_inserted = ();
1318 @fixed_deleted = ();
1320 @modifierListFile = ();
1323 $file = $oldfile if ($is_git_file);
1327 hash_show_words(\%use_type, "Used");
1328 hash_show_words(\%ignore_type, "Ignored");
1330 if (!$perl_version_ok) {
1333 NOTE: perl $^V is not modern enough to detect all possible issues.
1334 An upgrade to at least perl $minimum_perl_version is suggested.
1340 NOTE: If any of the errors are false positives, please report
1341 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1348 sub top_of_kernel_tree {
1352 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1353 "README", "Documentation", "arch", "include", "drivers",
1354 "fs", "init", "ipc", "kernel", "lib", "scripts",
1357 foreach my $check (@tree_check) {
1358 if (! -e $root . '/' . $check) {
1366 my ($formatted_email) = @_;
1370 my $name_comment = "";
1374 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1377 $comment = $3 if defined $3;
1378 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1380 $comment = $2 if defined $2;
1381 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1383 $comment = $2 if defined $2;
1384 $formatted_email =~ s/\Q$address\E.*$//;
1385 $name = $formatted_email;
1386 $name = trim($name);
1387 $name =~ s/^\"|\"$//g;
1388 # If there's a name left after stripping spaces and
1389 # leading quotes, and the address doesn't have both
1390 # leading and trailing angle brackets, the address
1392 # "joe smith joe@smith.com" bad
1393 # "joe smith <joe@smith.com" bad
1394 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1401 # Extract comments from names excluding quoted parts
1402 # "John D. (Doe)" - Do not extract
1403 if ($name =~ s/\"(.+)\"//) {
1406 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1407 $name_comment .= trim($1);
1409 $name =~ s/^[ \"]+|[ \"]+$//g;
1410 $name = trim("$quoted $name");
1412 $address = trim($address);
1413 $address =~ s/^\<|\>$//g;
1414 $comment = trim($comment);
1416 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1417 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1418 $name = "\"$name\"";
1421 return ($name, $name_comment, $address, $comment);
1425 my ($name, $name_comment, $address, $comment) = @_;
1427 my $formatted_email;
1429 $name =~ s/^[ \"]+|[ \"]+$//g;
1430 $address = trim($address);
1431 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1433 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1434 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1435 $name = "\"$name\"";
1438 $name_comment = trim($name_comment);
1439 $name_comment = " $name_comment" if ($name_comment ne "");
1440 $comment = trim($comment);
1441 $comment = " $comment" if ($comment ne "");
1443 if ("$name" eq "") {
1444 $formatted_email = "$address";
1446 $formatted_email = "$name$name_comment <$address>";
1448 $formatted_email .= "$comment";
1449 return $formatted_email;
1452 sub reformat_email {
1455 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1456 return format_email($email_name, $name_comment, $email_address, $comment);
1459 sub same_email_addresses {
1460 my ($email1, $email2) = @_;
1462 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1463 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1465 return $email1_name eq $email2_name &&
1466 $email1_address eq $email2_address &&
1467 $name1_comment eq $name2_comment &&
1468 $comment1 eq $comment2;
1474 foreach my $path (split(/:/, $ENV{PATH})) {
1475 if (-e "$path/$bin") {
1476 return "$path/$bin";
1486 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1487 if (-e "$path/$conf") {
1488 return "$path/$conf";
1500 for my $c (split(//, $str)) {
1504 for (; ($n % $tabsize) != 0; $n++) {
1516 (my $res = shift) =~ tr/\t/ /c;
1523 # Drop the diff line leader and expand tabs
1525 $line = expand_tabs($line);
1527 # Pick the indent from the front of the line.
1528 my ($white) = ($line =~ /^(\s*)/);
1530 return (length($line), length($white));
1533 my $sanitise_quote = '';
1535 sub sanitise_line_reset {
1536 my ($in_comment) = @_;
1539 $sanitise_quote = '*/';
1541 $sanitise_quote = '';
1554 # Always copy over the diff marker.
1555 $res = substr($line, 0, 1);
1557 for ($off = 1; $off < length($line); $off++) {
1558 $c = substr($line, $off, 1);
1560 # Comments we are whacking completely including the begin
1561 # and end, all to $;.
1562 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1563 $sanitise_quote = '*/';
1565 substr($res, $off, 2, "$;$;");
1569 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1570 $sanitise_quote = '';
1571 substr($res, $off, 2, "$;$;");
1575 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1576 $sanitise_quote = '//';
1578 substr($res, $off, 2, $sanitise_quote);
1583 # A \ in a string means ignore the next character.
1584 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1586 substr($res, $off, 2, 'XX');
1591 if ($c eq "'" || $c eq '"') {
1592 if ($sanitise_quote eq '') {
1593 $sanitise_quote = $c;
1595 substr($res, $off, 1, $c);
1597 } elsif ($sanitise_quote eq $c) {
1598 $sanitise_quote = '';
1602 #print "c<$c> SQ<$sanitise_quote>\n";
1603 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1604 substr($res, $off, 1, $;);
1605 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1606 substr($res, $off, 1, $;);
1607 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1608 substr($res, $off, 1, 'X');
1610 substr($res, $off, 1, $c);
1614 if ($sanitise_quote eq '//') {
1615 $sanitise_quote = '';
1618 # The pathname on a #include may be surrounded by '<' and '>'.
1619 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1620 my $clean = 'X' x length($1);
1621 $res =~ s@\<.*\>@<$clean>@;
1623 # The whole of a #error is a string.
1624 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1625 my $clean = 'X' x length($1);
1626 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1629 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1631 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1637 sub get_quoted_string {
1638 my ($line, $rawline) = @_;
1640 return "" if (!defined($line) || !defined($rawline));
1641 return "" if ($line !~ m/($String)/g);
1642 return substr($rawline, $-[0], $+[0] - $-[0]);
1645 sub ctx_statement_block {
1646 my ($linenr, $remain, $off) = @_;
1647 my $line = $linenr - 1;
1650 my $coff = $off - 1;
1664 @stack = (['', 0]) if ($#stack == -1);
1666 #warn "CSB: blk<$blk> remain<$remain>\n";
1667 # If we are about to drop off the end, pull in more
1670 for (; $remain > 0; $line++) {
1671 last if (!defined $lines[$line]);
1672 next if ($lines[$line] =~ /^-/);
1675 $blk .= $lines[$line] . "\n";
1676 $len = length($blk);
1680 # Bail if there is no further context.
1681 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1685 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1691 $c = substr($blk, $off, 1);
1692 $remainder = substr($blk, $off);
1694 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1696 # Handle nested #if/#else.
1697 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1698 push(@stack, [ $type, $level ]);
1699 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1700 ($type, $level) = @{$stack[$#stack - 1]};
1701 } elsif ($remainder =~ /^#\s*endif\b/) {
1702 ($type, $level) = @{pop(@stack)};
1705 # Statement ends at the ';' or a close '}' at the
1707 if ($level == 0 && $c eq ';') {
1711 # An else is really a conditional as long as its not else if
1712 if ($level == 0 && $coff_set == 0 &&
1713 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1714 $remainder =~ /^(else)(?:\s|{)/ &&
1715 $remainder !~ /^else\s+if\b/) {
1716 $coff = $off + length($1) - 1;
1718 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1719 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1722 if (($type eq '' || $type eq '(') && $c eq '(') {
1726 if ($type eq '(' && $c eq ')') {
1728 $type = ($level != 0)? '(' : '';
1730 if ($level == 0 && $coff < $soff) {
1733 #warn "CSB: mark coff<$coff>\n";
1736 if (($type eq '' || $type eq '{') && $c eq '{') {
1740 if ($type eq '{' && $c eq '}') {
1742 $type = ($level != 0)? '{' : '';
1745 if (substr($blk, $off + 1, 1) eq ';') {
1751 # Preprocessor commands end at the newline unless escaped.
1752 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1760 # We are truly at the end, so shuffle to the next line.
1767 my $statement = substr($blk, $soff, $off - $soff + 1);
1768 my $condition = substr($blk, $soff, $coff - $soff + 1);
1770 #warn "STATEMENT<$statement>\n";
1771 #warn "CONDITION<$condition>\n";
1773 #print "coff<$coff> soff<$off> loff<$loff>\n";
1775 return ($statement, $condition,
1776 $line, $remain + 1, $off - $loff + 1, $level);
1779 sub statement_lines {
1782 # Strip the diff line prefixes and rip blank lines at start and end.
1783 $stmt =~ s/(^|\n)./$1/g;
1787 my @stmt_lines = ($stmt =~ /\n/g);
1789 return $#stmt_lines + 2;
1792 sub statement_rawlines {
1795 my @stmt_lines = ($stmt =~ /\n/g);
1797 return $#stmt_lines + 2;
1800 sub statement_block_size {
1803 $stmt =~ s/(^|\n)./$1/g;
1809 my @stmt_lines = ($stmt =~ /\n/g);
1810 my @stmt_statements = ($stmt =~ /;/g);
1812 my $stmt_lines = $#stmt_lines + 2;
1813 my $stmt_statements = $#stmt_statements + 1;
1815 if ($stmt_lines > $stmt_statements) {
1818 return $stmt_statements;
1822 sub ctx_statement_full {
1823 my ($linenr, $remain, $off) = @_;
1824 my ($statement, $condition, $level);
1828 # Grab the first conditional/block pair.
1829 ($statement, $condition, $linenr, $remain, $off, $level) =
1830 ctx_statement_block($linenr, $remain, $off);
1831 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1832 push(@chunks, [ $condition, $statement ]);
1833 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1834 return ($level, $linenr, @chunks);
1837 # Pull in the following conditional/block pairs and see if they
1838 # could continue the statement.
1840 ($statement, $condition, $linenr, $remain, $off, $level) =
1841 ctx_statement_block($linenr, $remain, $off);
1842 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1843 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1845 push(@chunks, [ $condition, $statement ]);
1848 return ($level, $linenr, @chunks);
1852 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1854 my $start = $linenr - 1;
1861 my @stack = ($level);
1862 for ($line = $start; $remain > 0; $line++) {
1863 next if ($rawlines[$line] =~ /^-/);
1866 $blk .= $rawlines[$line];
1868 # Handle nested #if/#else.
1869 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1870 push(@stack, $level);
1871 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1872 $level = $stack[$#stack - 1];
1873 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1874 $level = pop(@stack);
1877 foreach my $c (split(//, $lines[$line])) {
1878 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1884 if ($c eq $close && $level > 0) {
1886 last if ($level == 0);
1887 } elsif ($c eq $open) {
1892 if (!$outer || $level <= 1) {
1893 push(@res, $rawlines[$line]);
1896 last if ($level == 0);
1899 return ($level, @res);
1901 sub ctx_block_outer {
1902 my ($linenr, $remain) = @_;
1904 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1908 my ($linenr, $remain) = @_;
1910 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1914 my ($linenr, $remain, $off) = @_;
1916 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1919 sub ctx_block_level {
1920 my ($linenr, $remain) = @_;
1922 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1924 sub ctx_statement_level {
1925 my ($linenr, $remain, $off) = @_;
1927 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1930 sub ctx_locate_comment {
1931 my ($first_line, $end_line) = @_;
1933 # If c99 comment on the current line, or the line before or after
1934 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1935 return $current_comment if (defined $current_comment);
1936 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1937 return $current_comment if (defined $current_comment);
1938 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1939 return $current_comment if (defined $current_comment);
1941 # Catch a comment on the end of the line itself.
1942 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1943 return $current_comment if (defined $current_comment);
1945 # Look through the context and try and figure out if there is a
1948 $current_comment = '';
1949 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1950 my $line = $rawlines[$linenr - 1];
1952 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1955 if ($line =~ m@/\*@) {
1958 if (!$in_comment && $current_comment ne '') {
1959 $current_comment = '';
1961 $current_comment .= $line . "\n" if ($in_comment);
1962 if ($line =~ m@\*/@) {
1967 chomp($current_comment);
1968 return($current_comment);
1970 sub ctx_has_comment {
1971 my ($first_line, $end_line) = @_;
1972 my $cmt = ctx_locate_comment($first_line, $end_line);
1974 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1975 ##print "CMMT: $cmt\n";
1977 return ($cmt ne '');
1981 my ($linenr, $cnt) = @_;
1983 my $offset = $linenr - 1;
1988 $line = $rawlines[$offset++];
1989 next if (defined($line) && $line =~ /^-/);
1997 my ($linenr, $lc) = @_;
1999 my $stat_real = raw_line($linenr, 0);
2000 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2001 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2008 my ($linenr, $cnt, $here) = @_;
2010 my $herectx = $here . "\n";
2011 for (my $n = 0; $n < $cnt; $n++) {
2012 $herectx .= raw_line($linenr, $n) . "\n";
2023 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2026 $coded = sprintf("^%c", unpack('C', $2) + 64);
2035 my $av_preprocessor = 0;
2040 sub annotate_reset {
2041 $av_preprocessor = 0;
2043 @av_paren_type = ('E');
2044 $av_pend_colon = 'O';
2047 sub annotate_values {
2048 my ($stream, $type) = @_;
2051 my $var = '_' x length($stream);
2054 print "$stream\n" if ($dbg_values > 1);
2056 while (length($cur)) {
2057 @av_paren_type = ('E') if ($#av_paren_type < 0);
2058 print " <" . join('', @av_paren_type) .
2059 "> <$type> <$av_pending>" if ($dbg_values > 1);
2060 if ($cur =~ /^(\s+)/o) {
2061 print "WS($1)\n" if ($dbg_values > 1);
2062 if ($1 =~ /\n/ && $av_preprocessor) {
2063 $type = pop(@av_paren_type);
2064 $av_preprocessor = 0;
2067 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2068 print "CAST($1)\n" if ($dbg_values > 1);
2069 push(@av_paren_type, $type);
2072 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2073 print "DECLARE($1)\n" if ($dbg_values > 1);
2076 } elsif ($cur =~ /^($Modifier)\s*/) {
2077 print "MODIFIER($1)\n" if ($dbg_values > 1);
2080 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2081 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2082 $av_preprocessor = 1;
2083 push(@av_paren_type, $type);
2089 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2090 print "UNDEF($1)\n" if ($dbg_values > 1);
2091 $av_preprocessor = 1;
2092 push(@av_paren_type, $type);
2094 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2095 print "PRE_START($1)\n" if ($dbg_values > 1);
2096 $av_preprocessor = 1;
2098 push(@av_paren_type, $type);
2099 push(@av_paren_type, $type);
2102 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2103 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2104 $av_preprocessor = 1;
2106 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2110 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2111 print "PRE_END($1)\n" if ($dbg_values > 1);
2113 $av_preprocessor = 1;
2115 # Assume all arms of the conditional end as this
2116 # one does, and continue as if the #endif was not here.
2117 pop(@av_paren_type);
2118 push(@av_paren_type, $type);
2121 } elsif ($cur =~ /^(\\\n)/o) {
2122 print "PRECONT($1)\n" if ($dbg_values > 1);
2124 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2125 print "ATTR($1)\n" if ($dbg_values > 1);
2126 $av_pending = $type;
2129 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2130 print "SIZEOF($1)\n" if ($dbg_values > 1);
2136 } elsif ($cur =~ /^(if|while|for)\b/o) {
2137 print "COND($1)\n" if ($dbg_values > 1);
2141 } elsif ($cur =~/^(case)/o) {
2142 print "CASE($1)\n" if ($dbg_values > 1);
2143 $av_pend_colon = 'C';
2146 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2147 print "KEYWORD($1)\n" if ($dbg_values > 1);
2150 } elsif ($cur =~ /^(\()/o) {
2151 print "PAREN('$1')\n" if ($dbg_values > 1);
2152 push(@av_paren_type, $av_pending);
2156 } elsif ($cur =~ /^(\))/o) {
2157 my $new_type = pop(@av_paren_type);
2158 if ($new_type ne '_') {
2160 print "PAREN('$1') -> $type\n"
2161 if ($dbg_values > 1);
2163 print "PAREN('$1')\n" if ($dbg_values > 1);
2166 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2167 print "FUNC($1)\n" if ($dbg_values > 1);
2171 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2172 if (defined $2 && $type eq 'C' || $type eq 'T') {
2173 $av_pend_colon = 'B';
2174 } elsif ($type eq 'E') {
2175 $av_pend_colon = 'L';
2177 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2180 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2181 print "IDENT($1)\n" if ($dbg_values > 1);
2184 } elsif ($cur =~ /^($Assignment)/o) {
2185 print "ASSIGN($1)\n" if ($dbg_values > 1);
2188 } elsif ($cur =~/^(;|{|})/) {
2189 print "END($1)\n" if ($dbg_values > 1);
2191 $av_pend_colon = 'O';
2193 } elsif ($cur =~/^(,)/) {
2194 print "COMMA($1)\n" if ($dbg_values > 1);
2197 } elsif ($cur =~ /^(\?)/o) {
2198 print "QUESTION($1)\n" if ($dbg_values > 1);
2201 } elsif ($cur =~ /^(:)/o) {
2202 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2204 substr($var, length($res), 1, $av_pend_colon);
2205 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2210 $av_pend_colon = 'O';
2212 } elsif ($cur =~ /^(\[)/o) {
2213 print "CLOSE($1)\n" if ($dbg_values > 1);
2216 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2219 print "OPV($1)\n" if ($dbg_values > 1);
2226 substr($var, length($res), 1, $variant);
2229 } elsif ($cur =~ /^($Operators)/o) {
2230 print "OP($1)\n" if ($dbg_values > 1);
2231 if ($1 ne '++' && $1 ne '--') {
2235 } elsif ($cur =~ /(^.)/o) {
2236 print "C($1)\n" if ($dbg_values > 1);
2239 $cur = substr($cur, length($1));
2240 $res .= $type x length($1);
2244 return ($res, $var);
2248 my ($possible, $line) = @_;
2249 my $notPermitted = qr{(?:
2266 ^(?:typedef|struct|enum)\b
2268 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2269 if ($possible !~ $notPermitted) {
2270 # Check for modifiers.
2271 $possible =~ s/\s*$Storage\s*//g;
2272 $possible =~ s/\s*$Sparse\s*//g;
2273 if ($possible =~ /^\s*$/) {
2275 } elsif ($possible =~ /\s/) {
2276 $possible =~ s/\s*$Type\s*//g;
2277 for my $modifier (split(' ', $possible)) {
2278 if ($modifier !~ $notPermitted) {
2279 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2280 push(@modifierListFile, $modifier);
2285 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2286 push(@typeListFile, $possible);
2290 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2299 $type =~ tr/[a-z]/[A-Z]/;
2301 return defined $use_type{$type} if (scalar keys %use_type > 0);
2303 return !defined $ignore_type{$type};
2307 my ($level, $type, $msg) = @_;
2309 if (!show_type($type) ||
2310 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2315 if ($level eq 'ERROR') {
2317 } elsif ($level eq 'WARNING') {
2323 $output .= $prefix . $level . ':';
2325 $output .= BLUE if ($color);
2326 $output .= "$type:";
2328 $output .= RESET if ($color);
2329 $output .= ' ' . $msg . "\n";
2332 my @lines = split("\n", $output, -1);
2333 splice(@lines, 1, 1);
2334 $output = join("\n", @lines);
2338 $output = (split('\n', $output))[0] . "\n";
2341 if ($verbose && exists($verbose_messages{$type}) &&
2342 !exists($verbose_emitted{$type})) {
2343 $output .= $verbose_messages{$type} . "\n\n";
2344 $verbose_emitted{$type} = 1;
2347 push(our @report, $output);
2356 sub fixup_current_range {
2357 my ($lineRef, $offset, $length) = @_;
2359 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2362 my $no = $o + $offset;
2363 my $nl = $l + $length;
2364 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2368 sub fix_inserted_deleted_lines {
2369 my ($linesRef, $insertedRef, $deletedRef) = @_;
2371 my $range_last_linenr = 0;
2372 my $delta_offset = 0;
2377 my $next_insert = 0;
2378 my $next_delete = 0;
2382 my $inserted = @{$insertedRef}[$next_insert++];
2383 my $deleted = @{$deletedRef}[$next_delete++];
2385 foreach my $old_line (@{$linesRef}) {
2387 my $line = $old_line; #don't modify the array
2388 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2390 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2391 $range_last_linenr = $new_linenr;
2392 fixup_current_range(\$line, $delta_offset, 0);
2395 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2396 $deleted = @{$deletedRef}[$next_delete++];
2398 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2401 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2402 push(@lines, ${$inserted}{'LINE'});
2403 $inserted = @{$insertedRef}[$next_insert++];
2405 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2409 push(@lines, $line);
2419 sub fix_insert_line {
2420 my ($linenr, $line) = @_;
2426 push(@fixed_inserted, $inserted);
2429 sub fix_delete_line {
2430 my ($linenr, $line) = @_;
2437 push(@fixed_deleted, $deleted);
2441 my ($type, $msg) = @_;
2443 if (report("ERROR", $type, $msg)) {
2451 my ($type, $msg) = @_;
2453 if (report("WARNING", $type, $msg)) {
2461 my ($type, $msg) = @_;
2463 if ($check && report("CHECK", $type, $msg)) {
2471 sub check_absolute_file {
2472 my ($absolute, $herecurr) = @_;
2473 my $file = $absolute;
2475 ##print "absolute<$absolute>\n";
2477 # See if any suffix of this path is a path within the tree.
2478 while ($file =~ s@^[^/]*/@@) {
2479 if (-f "$root/$file") {
2480 ##print "file<$file>\n";
2488 # It is, so see if the prefix is acceptable.
2489 my $prefix = $absolute;
2490 substr($prefix, -length($file)) = '';
2492 ##print "prefix<$prefix>\n";
2493 if ($prefix ne ".../") {
2494 WARN("USE_RELATIVE_PATH",
2495 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2502 $string =~ s/^\s+|\s+$//g;
2510 $string =~ s/^\s+//;
2518 $string =~ s/\s+$//;
2523 sub string_find_replace {
2524 my ($string, $find, $replace) = @_;
2526 $string =~ s/$find/$replace/g;
2534 my $source_indent = $tabsize;
2535 my $max_spaces_before_tab = $source_indent - 1;
2536 my $spaces_to_tab = " " x $source_indent;
2538 #convert leading spaces to tabs
2539 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2540 #Remove spaces before a tab
2541 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2546 sub pos_last_openparen {
2551 my $opens = $line =~ tr/\(/\(/;
2552 my $closes = $line =~ tr/\)/\)/;
2554 my $last_openparen = 0;
2556 if (($opens == 0) || ($closes >= $opens)) {
2560 my $len = length($line);
2562 for ($pos = 0; $pos < $len; $pos++) {
2563 my $string = substr($line, $pos);
2564 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2565 $pos += length($1) - 1;
2566 } elsif (substr($line, $pos, 1) eq '(') {
2567 $last_openparen = $pos;
2568 } elsif (index($string, '(') == -1) {
2573 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2576 sub get_raw_comment {
2577 my ($line, $rawline) = @_;
2580 for my $i (0 .. (length($line) - 1)) {
2581 if (substr($line, $i, 1) eq "$;") {
2582 $comment .= substr($rawline, $i, 1);
2589 sub exclude_global_initialisers {
2590 my ($realfile) = @_;
2592 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2593 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2594 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2595 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2599 my $filename = shift;
2605 my $stashrawline="";
2615 my $authorsignoff = 0;
2616 my $author_sob = '';
2618 my $is_binding_patch = -1;
2619 my $in_header_lines = $file ? 0 : 1;
2620 my $in_commit_log = 0; #Scanning lines before patch
2621 my $has_patch_separator = 0; #Found a --- line
2622 my $has_commit_log = 0; #Encountered lines before patch
2623 my $commit_log_lines = 0; #Number of commit log lines
2624 my $commit_log_possible_stack_dump = 0;
2625 my $commit_log_long_line = 0;
2626 my $commit_log_has_diff = 0;
2627 my $reported_maintainer_file = 0;
2628 my $non_utf8_charset = 0;
2630 my $last_git_commit_id_linenr = -1;
2632 my $last_blank_line = 0;
2633 my $last_coalesced_string_linenr = -1;
2641 # Trace the real file/line as we go.
2646 my $context_function; #undef'd unless there's a known function
2648 my $comment_edge = 0;
2652 my $prev_values = 'E';
2655 my %suppress_ifbraces;
2656 my %suppress_whiletrailers;
2657 my %suppress_export;
2658 my $suppress_statement = 0;
2660 my %signatures = ();
2662 # Pre-scan the patch sanitizing the lines.
2663 # Pre-scan the patch looking for any __setup documentation.
2665 my @setup_docs = ();
2668 my $camelcase_file_seeded = 0;
2670 my $checklicenseline = 1;
2672 sanitise_line_reset();
2674 foreach my $rawline (@rawlines) {
2678 push(@fixed, $rawline) if ($fix);
2680 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2682 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2687 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2696 # Guestimate if this is a continuing comment. Run
2697 # the context looking for a comment "edge". If this
2698 # edge is a close comment then we must be in a comment
2702 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2703 next if (defined $rawlines[$ln - 1] &&
2704 $rawlines[$ln - 1] =~ /^-/);
2706 #print "RAW<$rawlines[$ln - 1]>\n";
2707 last if (!defined $rawlines[$ln - 1]);
2708 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2709 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2714 if (defined $edge && $edge eq '*/') {
2718 # Guestimate if this is a continuing comment. If this
2719 # is the start of a diff block and this line starts
2720 # ' *' then it is very likely a comment.
2721 if (!defined $edge &&
2722 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2727 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2728 sanitise_line_reset($in_comment);
2730 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2731 # Standardise the strings and chars within the input to
2732 # simplify matching -- only bother with positive lines.
2733 $line = sanitise_line($rawline);
2735 push(@lines, $line);
2738 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2743 #print "==>$rawline\n";
2744 #print "-->$line\n";
2746 if ($setup_docs && $line =~ /^\+/) {
2747 push(@setup_docs, $line);
2756 foreach my $line (@lines) {
2759 my $sline = $line; #copy of $line
2760 $sline =~ s/$;/ /g; #with comments as spaces
2762 my $rawline = $rawlines[$linenr - 1];
2763 my $raw_comment = get_raw_comment($line, $rawline);
2765 # check if it's a mode change, rename or start of a patch
2766 if (!$in_commit_log &&
2767 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2768 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2769 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2773 #extract the line range in the file after the patch is applied
2774 if (!$in_commit_log &&
2775 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2778 $first_line = $linenr + 1;
2788 %suppress_ifbraces = ();
2789 %suppress_whiletrailers = ();
2790 %suppress_export = ();
2791 $suppress_statement = 0;
2792 if ($context =~ /\b(\w+)\s*\(/) {
2793 $context_function = $1;
2795 undef $context_function;
2799 # track the line number as we move through the hunk, note that
2800 # new versions of GNU diff omit the leading space on completely
2801 # blank context lines so we need to count that too.
2802 } elsif ($line =~ /^( |\+|$)/) {
2804 $realcnt-- if ($realcnt != 0);
2806 # Measure the line length and indent.
2807 ($length, $indent) = line_stats($rawline);
2809 # Track the previous line.
2810 ($prevline, $stashline) = ($stashline, $line);
2811 ($previndent, $stashindent) = ($stashindent, $indent);
2812 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2814 #warn "line<$line>\n";
2816 } elsif ($realcnt == 1) {
2820 my $hunk_line = ($realcnt != 0);
2822 $here = "#$linenr: " if (!$file);
2823 $here = "#$realline: " if ($file);
2826 # extract the filename as it passes
2827 if ($line =~ /^diff --git.*?(\S+)$/) {
2829 $realfile =~ s@^([^/]*)/@@ if (!$file);
2832 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2834 $realfile =~ s@^([^/]*)/@@ if (!$file);
2838 if (!$file && $tree && $p1_prefix ne '' &&
2839 -e "$root/$p1_prefix") {
2840 WARN("PATCH_PREFIX",
2841 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2844 if ($realfile =~ m@^include/asm/@) {
2845 ERROR("MODIFIED_INCLUDE_ASM",
2846 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2851 #make up the handle for any error we report on this line
2853 $prefix = "$realfile:$realline: "
2856 $prefix = "$filename:$realline: ";
2858 $prefix = "$filename:$linenr: ";
2863 if (is_maintained_obsolete($realfile)) {
2865 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2867 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2870 $check = $check_orig;
2872 $checklicenseline = 1;
2874 if ($realfile !~ /^MAINTAINERS/) {
2875 my $last_binding_patch = $is_binding_patch;
2877 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2879 if (($last_binding_patch != -1) &&
2880 ($last_binding_patch ^ $is_binding_patch)) {
2881 WARN("DT_SPLIT_BINDING_PATCH",
2882 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2889 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2891 my $hereline = "$here\n$rawline\n";
2892 my $herecurr = "$here\n$rawline\n";
2893 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2895 $cnt_lines++ if ($realcnt != 0);
2897 # Verify the existence of a commit log if appropriate
2898 # 2 is used because a $signature is counted in $commit_log_lines
2899 if ($in_commit_log) {
2900 if ($line !~ /^\s*$/) {
2901 $commit_log_lines++; #could be a $signature
2903 } elsif ($has_commit_log && $commit_log_lines < 2) {
2904 WARN("COMMIT_MESSAGE",
2905 "Missing commit description - Add an appropriate one\n");
2906 $commit_log_lines = 2; #warn only once
2909 # Check if the commit log has what seems like a diff which can confuse patch
2910 if ($in_commit_log && !$commit_log_has_diff &&
2911 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2912 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2913 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2914 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2915 ERROR("DIFF_IN_COMMIT_MSG",
2916 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2917 $commit_log_has_diff = 1;
2920 # Check for incorrect file permissions
2921 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2922 my $permhere = $here . "FILE: $realfile\n";
2923 if ($realfile !~ m@scripts/@ &&
2924 $realfile !~ /\.(py|pl|awk|sh)$/) {
2925 ERROR("EXECUTE_PERMISSIONS",
2926 "do not set execute permissions for source files\n" . $permhere);
2930 # Check the patch for a From:
2931 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2933 my $curline = $linenr;
2934 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2937 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2939 $author = reformat_email($author);
2942 # Check the patch for a signoff:
2943 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2946 if ($author ne '' && $authorsignoff != 1) {
2947 if (same_email_addresses($1, $author)) {
2951 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2952 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2954 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2957 } elsif (lc $email_address eq lc $author_address) {
2960 } elsif ($email_name eq $author_name) {
2964 my $address1 = $email_address;
2965 my $address2 = $author_address;
2967 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2970 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2973 if ($address1 eq $address2) {
2981 # Check for patch separator
2982 if ($line =~ /^---$/) {
2983 $has_patch_separator = 1;
2987 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2988 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2989 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2990 $reported_maintainer_file = 1;
2993 # Check signature styles
2994 if (!$in_header_lines &&
2995 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2996 my $space_before = $1;
2998 my $space_after = $3;
3000 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3002 if ($sign_off !~ /$signature_tags/) {
3003 my $suggested_signature = find_standard_signature($sign_off);
3004 if ($suggested_signature eq "") {
3005 WARN("BAD_SIGN_OFF",
3006 "Non-standard signature: $sign_off\n" . $herecurr);
3008 if (WARN("BAD_SIGN_OFF",
3009 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3011 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3015 if (defined $space_before && $space_before ne "") {
3016 if (WARN("BAD_SIGN_OFF",
3017 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3019 $fixed[$fixlinenr] =
3020 "$ucfirst_sign_off $email";
3023 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3024 if (WARN("BAD_SIGN_OFF",
3025 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3027 $fixed[$fixlinenr] =
3028 "$ucfirst_sign_off $email";
3032 if (!defined $space_after || $space_after ne " ") {
3033 if (WARN("BAD_SIGN_OFF",
3034 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3036 $fixed[$fixlinenr] =
3037 "$ucfirst_sign_off $email";
3041 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3042 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3043 if ($suggested_email eq "") {
3044 ERROR("BAD_SIGN_OFF",
3045 "Unrecognized email address: '$email'\n" . $herecurr);
3047 my $dequoted = $suggested_email;
3048 $dequoted =~ s/^"//;
3049 $dequoted =~ s/" </ </;
3050 # Don't force email to have quotes
3051 # Allow just an angle bracketed address
3052 if (!same_email_addresses($email, $suggested_email)) {
3053 if (WARN("BAD_SIGN_OFF",
3054 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3056 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3060 # Address part shouldn't have comments
3061 my $stripped_address = $email_address;
3062 $stripped_address =~ s/\([^\(\)]*\)//g;
3063 if ($email_address ne $stripped_address) {
3064 if (WARN("BAD_SIGN_OFF",
3065 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3067 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3071 # Only one name comment should be allowed
3072 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3073 if ($comment_count > 1) {
3074 WARN("BAD_SIGN_OFF",
3075 "Use a single name comment in email: '$email'\n" . $herecurr);
3079 # stable@vger.kernel.org or stable@kernel.org shouldn't
3080 # have an email name. In addition comments should strictly
3082 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3083 if (($comment ne "" && $comment !~ /^#.+/) ||
3084 ($email_name ne "")) {
3085 my $cur_name = $email_name;
3086 my $new_comment = $comment;
3087 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3089 # Remove brackets enclosing comment text
3090 # and # from start of comments to get comment text
3091 $new_comment =~ s/^\((.*)\)$/$1/;
3092 $new_comment =~ s/^\[(.*)\]$/$1/;
3093 $new_comment =~ s/^[\s\#]+|\s+$//g;
3095 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3096 $new_comment = " # $new_comment" if ($new_comment ne "");
3097 my $new_email = "$email_address$new_comment";
3099 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3100 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3102 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3105 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3106 my $new_comment = $comment;
3108 # Extract comment text from within brackets or
3109 # c89 style /*...*/ comments
3110 $new_comment =~ s/^\[(.*)\]$/$1/;
3111 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3113 $new_comment = trim($new_comment);
3114 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3115 $new_comment = "($new_comment)" if ($new_comment ne "");
3116 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3118 if (WARN("BAD_SIGN_OFF",
3119 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3121 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3126 # Check for duplicate signatures
3127 my $sig_nospace = $line;
3128 $sig_nospace =~ s/\s//g;
3129 $sig_nospace = lc($sig_nospace);
3130 if (defined $signatures{$sig_nospace}) {
3131 WARN("BAD_SIGN_OFF",
3132 "Duplicate signature\n" . $herecurr);
3134 $signatures{$sig_nospace} = 1;
3137 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3138 if ($sign_off =~ /^co-developed-by:$/i) {
3139 if ($email eq $author) {
3140 WARN("BAD_SIGN_OFF",
3141 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3143 if (!defined $lines[$linenr]) {
3144 WARN("BAD_SIGN_OFF",
3145 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3146 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3147 WARN("BAD_SIGN_OFF",
3148 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3149 } elsif ($1 ne $email) {
3150 WARN("BAD_SIGN_OFF",
3151 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3156 # Check email subject for common tools that don't need to be mentioned
3157 if ($in_header_lines &&
3158 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3159 WARN("EMAIL_SUBJECT",
3160 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3163 # Check for Gerrit Change-Ids not in any patch context
3164 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3165 if (ERROR("GERRIT_CHANGE_ID",
3166 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3168 fix_delete_line($fixlinenr, $rawline);
3172 # Check if the commit log is in a possible stack dump
3173 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3174 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3175 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3177 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3178 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3179 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3180 # stack dump address styles
3181 $commit_log_possible_stack_dump = 1;
3184 # Check for line lengths > 75 in commit log, warn once
3185 if ($in_commit_log && !$commit_log_long_line &&
3186 length($line) > 75 &&
3187 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3188 # file delta changes
3189 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3191 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3192 # A Fixes: or Link: line or signature tag line
3193 $commit_log_possible_stack_dump)) {
3194 WARN("COMMIT_LOG_LONG_LINE",
3195 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3196 $commit_log_long_line = 1;
3199 # Reset possible stack dump if a blank line is found
3200 if ($in_commit_log && $commit_log_possible_stack_dump &&
3202 $commit_log_possible_stack_dump = 0;
3205 # Check for lines starting with a #
3206 if ($in_commit_log && $line =~ /^#/) {
3207 if (WARN("COMMIT_COMMENT_SYMBOL",
3208 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3210 $fixed[$fixlinenr] =~ s/^/ /;
3214 # Check for git id commit length and improperly formed commit descriptions
3215 # A correctly formed commit description is:
3216 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3217 # with the commit subject '("' prefix and '")' suffix
3218 # This is a fairly compilicated block as it tests for what appears to be
3219 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3220 # possible SHA-1 matches.
3221 # A commit match can span multiple lines so this block attempts to find a
3222 # complete typical commit on a maximum of 3 lines
3223 if ($perl_version_ok &&
3224 $in_commit_log && !$commit_log_possible_stack_dump &&
3225 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3226 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3227 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3228 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3229 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3230 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3231 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3232 my $init_char = "c";
3233 my $orig_commit = "";
3238 my $id = '0123456789ab';
3239 my $orig_desc = "commit description";
3240 my $description = "";
3241 my $herectx = $herecurr;
3246 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3247 for (my $n = 0; $n < 2; $n++) {
3248 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3251 # Always strip leading/trailing parens then double quotes if existing
3252 $orig_desc = substr($orig_desc, 1, -1);
3253 if ($orig_desc =~ /^".*"$/) {
3254 $orig_desc = substr($orig_desc, 1, -1);
3259 last if ($#lines < $linenr + $n);
3260 $input .= " " . trim($rawlines[$linenr + $n]);
3261 $herectx .= "$rawlines[$linenr + $n]\n";
3263 $herectx = $herecurr if (!$has_parens);
3266 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3268 $orig_commit = lc($2);
3269 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3270 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3271 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3272 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3273 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3274 $orig_commit = lc($1);
3277 ($id, $description) = git_commit_info($orig_commit,
3281 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3282 $last_git_commit_id_linenr != $linenr - 1) {
3283 ERROR("GIT_COMMIT_ID",
3284 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3286 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3287 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3290 # Check for added, moved or deleted files
3291 if (!$reported_maintainer_file && !$in_commit_log &&
3292 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3293 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3294 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3295 (defined($1) || defined($2))))) {
3297 $reported_maintainer_file = 1;
3298 WARN("FILE_PATH_CHANGES",
3299 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3302 # Check for adding new DT bindings not in schema format
3303 if (!$in_commit_log &&
3304 ($line =~ /^new file mode\s*\d+\s*$/) &&
3305 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3306 WARN("DT_SCHEMA_BINDING_PATCH",
3307 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3310 # Check for wrappage within a valid hunk of the file
3311 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3312 ERROR("CORRUPTED_PATCH",
3313 "patch seems to be corrupt (line wrapped?)\n" .
3314 $herecurr) if (!$emitted_corrupt++);
3317 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3318 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3319 $rawline !~ m/^$UTF8*$/) {
3320 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3322 my $blank = copy_spacing($rawline);
3323 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3324 my $hereptr = "$hereline$ptr\n";
3327 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3330 # Check if it's the start of a commit log
3331 # (not a header line and we haven't seen the patch filename)
3332 if ($in_header_lines && $realfile =~ /^$/ &&
3333 !($rawline =~ /^\s+(?:\S|$)/ ||
3334 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3335 $in_header_lines = 0;
3337 $has_commit_log = 1;
3340 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3341 # declined it, i.e defined some charset where it is missing.
3342 if ($in_header_lines &&
3343 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3345 $non_utf8_charset = 1;
3348 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3349 $rawline =~ /$NON_ASCII_UTF8/) {
3350 WARN("UTF8_BEFORE_PATCH",
3351 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3354 # Check for absolute kernel paths in commit message
3355 if ($tree && $in_commit_log) {
3356 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3359 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3360 check_absolute_file($1, $herecurr)) {
3363 check_absolute_file($file, $herecurr);
3368 # Check for various typo / spelling mistakes
3369 if (defined($misspellings) &&
3370 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3371 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3373 my $blank = copy_spacing($rawline);
3374 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3375 my $hereptr = "$hereline$ptr\n";
3376 my $typo_fix = $spelling_fix{lc($typo)};
3377 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3378 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3379 my $msg_level = \&WARN;
3380 $msg_level = \&CHK if ($file);
3381 if (&{$msg_level}("TYPO_SPELLING",
3382 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3384 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3389 # check for invalid commit id
3390 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3393 ($id, $description) = git_commit_info($2, undef, undef);
3394 if (!defined($id)) {
3395 WARN("UNKNOWN_COMMIT_ID",
3396 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3400 # check for repeated words separated by a single space
3401 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3402 if (($rawline =~ /^\+/ || $in_commit_log) &&
3403 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3404 pos($rawline) = 1 if (!$in_commit_log);
3405 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3409 my $start_pos = $-[1];
3410 my $end_pos = $+[2];
3411 if ($first =~ /(?:struct|union|enum)/) {
3412 pos($rawline) += length($first) + length($second) + 1;
3416 next if (lc($first) ne lc($second));
3417 next if ($first eq 'long');
3419 # check for character before and after the word matches
3420 my $start_char = '';
3422 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3423 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3425 next if ($start_char =~ /^\S$/);
3426 next if (index(" \t.,;?!", $end_char) == -1);
3428 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3429 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3430 next if (!exists($allow_repeated_words{lc($first)}));
3433 if (WARN("REPEATED_WORD",
3434 "Possible repeated word: '$first'\n" . $herecurr) &&
3436 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3440 # if it's a repeated word on consecutive lines in a comment block
3441 if ($prevline =~ /$;+\s*$/ &&
3442 $prevrawline =~ /($word_pattern)\s*$/) {
3444 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3445 if (WARN("REPEATED_WORD",
3446 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3448 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3454 # ignore non-hunk lines and lines being removed
3455 next if (!$hunk_line || $line =~ /^-/);
3457 #trailing whitespace
3458 if ($line =~ /^\+.*\015/) {
3459 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3460 if (ERROR("DOS_LINE_ENDINGS",
3461 "DOS line endings\n" . $herevet) &&
3463 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3465 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3466 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3467 if (ERROR("TRAILING_WHITESPACE",
3468 "trailing whitespace\n" . $herevet) &&
3470 $fixed[$fixlinenr] =~ s/\s+$//;
3476 # Check for FSF mailing addresses.
3477 if ($rawline =~ /\bwrite to the Free/i ||
3478 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3479 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3480 $rawline =~ /\b51\s+Franklin\s+St/i) {
3481 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3482 my $msg_level = \&ERROR;
3483 $msg_level = \&CHK if ($file);
3484 &{$msg_level}("FSF_MAILING_ADDRESS",
3485 "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)
3488 # check for Kconfig help text having a real description
3489 # Only applies when adding the entry originally, after that we do not have
3490 # sufficient context to determine whether it is indeed long enough.
3491 if ($realfile =~ /Kconfig/ &&
3492 # 'choice' is usually the last thing on the line (though
3493 # Kconfig supports named choices), so use a word boundary
3494 # (\b) rather than a whitespace character (\s)
3495 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3499 my $help_length = 0;
3500 while (defined $lines[$ln]) {
3501 my $f = $lines[$ln++];
3503 next if ($f =~ /^-/);
3504 last if ($f !~ /^[\+ ]/); # !patch context
3506 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3510 if ($f =~ /^\+\s*help\s*$/) {
3515 $f =~ s/^.//; # strip patch context [+ ]
3516 $f =~ s/#.*//; # strip # directives
3517 $f =~ s/^\s+//; # strip leading blanks
3518 next if ($f =~ /^$/); # skip blank lines
3520 # At the end of this Kconfig block:
3521 # This only checks context lines in the patch
3522 # and so hopefully shouldn't trigger false
3523 # positives, even though some of these are
3524 # common words in help texts
3525 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3526 if|endif|menu|endmenu|source)\b/x) {
3529 $help_length++ if ($has_help);
3532 $help_length < $min_conf_desc_length) {
3533 my $stat_real = get_stat_real($linenr, $ln - 1);
3534 WARN("CONFIG_DESCRIPTION",
3535 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3539 # check MAINTAINERS entries
3540 if ($realfile =~ /^MAINTAINERS$/) {
3541 # check MAINTAINERS entries for the right form
3542 if ($rawline =~ /^\+[A-Z]:/ &&
3543 $rawline !~ /^\+[A-Z]:\t\S/) {
3544 if (WARN("MAINTAINERS_STYLE",
3545 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3547 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3550 # check MAINTAINERS entries for the right ordering too
3551 my $preferred_order = 'MRLSWQBCPTFXNK';
3552 if ($rawline =~ /^\+[A-Z]:/ &&
3553 $prevrawline =~ /^[\+ ][A-Z]:/) {
3554 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3557 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3560 my $curindex = index($preferred_order, $cur);
3561 my $previndex = index($preferred_order, $prev);
3562 if ($curindex < 0) {
3563 WARN("MAINTAINERS_STYLE",
3564 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3566 if ($previndex >= 0 && $curindex < $previndex) {
3567 WARN("MAINTAINERS_STYLE",
3568 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3569 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3570 ($prev eq 'X' && $cur eq 'X')) &&
3571 ($prevval cmp $curval) > 0) {
3572 WARN("MAINTAINERS_STYLE",
3573 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3579 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3580 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3583 'EXTRA_AFLAGS' => 'asflags-y',
3584 'EXTRA_CFLAGS' => 'ccflags-y',
3585 'EXTRA_CPPFLAGS' => 'cppflags-y',
3586 'EXTRA_LDFLAGS' => 'ldflags-y',
3589 WARN("DEPRECATED_VARIABLE",
3590 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3593 # check for DT compatible documentation
3594 if (defined $root &&
3595 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3596 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3598 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3600 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3601 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3603 foreach my $compat (@compats) {
3604 my $compat2 = $compat;
3605 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3606 my $compat3 = $compat;
3607 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3608 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3610 WARN("UNDOCUMENTED_DT_STRING",
3611 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3614 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3616 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3618 WARN("UNDOCUMENTED_DT_STRING",
3619 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3624 # check for using SPDX license tag at beginning of files
3625 if ($realline == $checklicenseline) {
3626 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3627 $checklicenseline = 2;
3628 } elsif ($rawline =~ /^\+/) {
3630 if ($realfile =~ /\.(h|s|S)$/) {
3632 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3634 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3636 } elsif ($realfile =~ /\.rst$/) {
3640 # check SPDX comment style for .[chsS] files
3641 if ($realfile =~ /\.[chsS]$/ &&
3642 $rawline =~ /SPDX-License-Identifier:/ &&
3643 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3644 WARN("SPDX_LICENSE_TAG",
3645 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3648 if ($comment !~ /^$/ &&
3649 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3650 WARN("SPDX_LICENSE_TAG",
3651 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3652 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3653 my $spdx_license = $1;
3654 if (!is_SPDX_License_valid($spdx_license)) {
3655 WARN("SPDX_LICENSE_TAG",
3656 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3658 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3659 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3660 my $msg_level = \&WARN;
3661 $msg_level = \&CHK if ($file);
3662 if (&{$msg_level}("SPDX_LICENSE_TAG",
3664 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3666 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3673 # check for embedded filenames
3674 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3675 WARN("EMBEDDED_FILENAME",
3676 "It's generally not useful to have the filename in the file\n" . $herecurr);
3679 # check we are in a valid source file if not then ignore this hunk
3680 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3682 # check for using SPDX-License-Identifier on the wrong line number
3683 if ($realline != $checklicenseline &&
3684 $rawline =~ /\bSPDX-License-Identifier:/ &&
3685 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3686 WARN("SPDX_LICENSE_TAG",
3687 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3690 # line length limit (with some exclusions)
3692 # There are a few types of lines that may extend beyond $max_line_length:
3693 # logging functions like pr_info that end in a string
3694 # lines with a single string
3695 # #defines that are a single string
3696 # lines with an RFC3986 like URL
3698 # There are 3 different line length message types:
3699 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3700 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3701 # LONG_LINE all other lines longer than $max_line_length
3703 # if LONG_LINE is ignored, the other 2 types are also ignored
3706 if ($line =~ /^\+/ && $length > $max_line_length) {
3707 my $msg_type = "LONG_LINE";
3709 # Check the allowed long line types first
3711 # logging functions that end in a string that starts
3712 # before $max_line_length
3713 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3714 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3717 # lines with only strings (w/ possible termination)
3718 # #defines with only strings
3719 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3720 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3723 # More special cases
3724 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3725 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3728 # URL ($rawline is used in case the URL is in a comment)
3729 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3732 # Otherwise set the alternate message types
3734 # a comment starts before $max_line_length
3735 } elsif ($line =~ /($;[\s$;]*)$/ &&
3736 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3737 $msg_type = "LONG_LINE_COMMENT"
3739 # a quoted string starts before $max_line_length
3740 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3741 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3742 $msg_type = "LONG_LINE_STRING"
3745 if ($msg_type ne "" &&
3746 (show_type("LONG_LINE") || show_type($msg_type))) {
3747 my $msg_level = \&WARN;
3748 $msg_level = \&CHK if ($file);
3749 &{$msg_level}($msg_type,
3750 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3754 # check for adding lines without a newline.
3755 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3756 if (WARN("MISSING_EOF_NEWLINE",
3757 "adding a line without newline at end of file\n" . $herecurr) &&
3759 fix_delete_line($fixlinenr+1, "No newline at end of file");
3763 # check for .L prefix local symbols in .S files
3764 if ($realfile =~ /\.S$/ &&
3765 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3766 WARN("AVOID_L_PREFIX",
3767 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/asm-annotations.rst\n" . $herecurr);
3770 # check we are in a valid source file C or perl if not then ignore this hunk
3771 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3773 # at the beginning of a line any tabs must come first and anything
3774 # more than $tabsize must use tabs.
3775 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3776 $rawline =~ /^\+\s* \s*/) {
3777 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3779 if (ERROR("CODE_INDENT",
3780 "code indent should use tabs where possible\n" . $herevet) &&
3782 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3786 # check for space before tabs.
3787 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3788 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3789 if (WARN("SPACE_BEFORE_TAB",
3790 "please, no space before tabs\n" . $herevet) &&
3792 while ($fixed[$fixlinenr] =~
3793 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3794 while ($fixed[$fixlinenr] =~
3795 s/(^\+.*) +\t/$1\t/) {}
3799 # check for assignments on the start of a line
3800 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3802 if (CHK("ASSIGNMENT_CONTINUATIONS",
3803 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3804 $fix && $prevrawline =~ /^\+/) {
3805 # add assignment operator to the previous line, remove from current line
3806 $fixed[$fixlinenr - 1] .= " $operator";
3807 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3811 # check for && or || at the start of a line
3812 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3814 if (CHK("LOGICAL_CONTINUATIONS",
3815 "Logical continuations should be on the previous line\n" . $hereprev) &&
3816 $fix && $prevrawline =~ /^\+/) {
3817 # insert logical operator at last non-comment, non-whitepsace char on previous line
3818 $prevline =~ /[\s$;]*$/;
3819 my $line_end = substr($prevrawline, $-[0]);
3820 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3821 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3825 # check indentation starts on a tab stop
3826 if ($perl_version_ok &&
3827 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3828 my $indent = length($1);
3829 if ($indent % $tabsize) {
3831 "Statements should start on a tabstop\n" . $herecurr) &&
3833 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3838 # check multi-line statement indentation matches previous line
3839 if ($perl_version_ok &&
3840 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3841 $prevline =~ /^\+(\t*)(.*)$/;
3845 my $pos = pos_last_openparen($rest);
3847 $line =~ /^(\+| )([ \t]*)/;
3850 my $goodtabindent = $oldindent .
3851 "\t" x ($pos / $tabsize) .
3852 " " x ($pos % $tabsize);
3853 my $goodspaceindent = $oldindent . " " x $pos;
3855 if ($newindent ne $goodtabindent &&
3856 $newindent ne $goodspaceindent) {
3858 if (CHK("PARENTHESIS_ALIGNMENT",
3859 "Alignment should match open parenthesis\n" . $hereprev) &&
3860 $fix && $line =~ /^\+/) {
3861 $fixed[$fixlinenr] =~
3862 s/^\+[ \t]*/\+$goodtabindent/;
3868 # check for space after cast like "(int) foo" or "(struct foo) bar"
3869 # avoid checking a few false positives:
3870 # "sizeof(<type>)" or "__alignof__(<type>)"
3871 # function pointer declarations like "(*foo)(int) = bar;"
3872 # structure definitions like "(struct foo) { 0 };"
3873 # multiline macros that define functions
3874 # known attributes or the __attribute__ keyword
3875 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3876 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3878 "No space is necessary after a cast\n" . $herecurr) &&
3880 $fixed[$fixlinenr] =~
3881 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3885 # Block comment styles
3886 # Networking with an initial /*
3887 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3888 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3889 $rawline =~ /^\+[ \t]*\*/ &&
3890 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3891 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3892 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3895 # Block comments use * on subsequent lines
3896 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3897 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3898 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3899 $rawline =~ /^\+/ && #line is new
3900 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3901 WARN("BLOCK_COMMENT_STYLE",
3902 "Block comments use * on subsequent lines\n" . $hereprev);
3905 # Block comments use */ on trailing lines
3906 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3907 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3908 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3909 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3910 WARN("BLOCK_COMMENT_STYLE",
3911 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3914 # Block comment * alignment
3915 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3916 $line =~ /^\+[ \t]*$;/ && #leading comment
3917 $rawline =~ /^\+[ \t]*\*/ && #leading *
3918 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3919 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3920 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3922 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3924 $oldindent = expand_tabs($1);
3926 $prevrawline =~ m@^\+(.*/?)\*@;
3927 $oldindent = expand_tabs($1);
3929 $rawline =~ m@^\+([ \t]*)\*@;
3931 $newindent = expand_tabs($newindent);
3932 if (length($oldindent) ne length($newindent)) {
3933 WARN("BLOCK_COMMENT_STYLE",
3934 "Block comments should align the * on each line\n" . $hereprev);
3938 # check for missing blank lines after struct/union declarations
3939 # with exceptions for various attributes and macros
3940 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3942 !($line =~ /^\+\s*$/ ||
3943 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
3944 $line =~ /^\+\s*MODULE_/i ||
3945 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3946 $line =~ /^\+[a-z_]*init/ ||
3947 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3948 $line =~ /^\+\s*DECLARE/ ||
3949 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3950 $line =~ /^\+\s*__setup/)) {
3951 if (CHK("LINE_SPACING",
3952 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3954 fix_insert_line($fixlinenr, "\+");
3958 # check for multiple consecutive blank lines
3959 if ($prevline =~ /^[\+ ]\s*$/ &&
3960 $line =~ /^\+\s*$/ &&
3961 $last_blank_line != ($linenr - 1)) {
3962 if (CHK("LINE_SPACING",
3963 "Please don't use multiple blank lines\n" . $hereprev) &&
3965 fix_delete_line($fixlinenr, $rawline);
3968 $last_blank_line = $linenr;
3971 # check for missing blank lines after declarations
3972 # (declarations must have the same indentation and not be at the start of line)
3973 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3977 # remove $Attribute/$Sparse uses to simplify comparisons
3978 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3979 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3980 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3981 # function pointer declarations
3982 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3983 # foo bar; where foo is some local typedef or #define
3984 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3985 # known declaration macros
3986 $pl =~ /^\+\s+$declaration_macros/) &&
3987 # for "else if" which can look like "$Ident $Ident"
3988 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3989 # other possible extensions of declaration lines
3990 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3991 # not starting a section or a macro "\" extended line
3992 $pl =~ /(?:\{\s*|\\)$/) &&
3993 # looks like a declaration
3994 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3995 # function pointer declarations
3996 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3997 # foo bar; where foo is some local typedef or #define
3998 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3999 # known declaration macros
4000 $sl =~ /^\+\s+$declaration_macros/ ||
4001 # start of struct or union or enum
4002 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4003 # start or end of block or continuation of declaration
4004 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4005 # bitfield continuation
4006 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4007 # other possible extensions of declaration lines
4008 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4009 if (WARN("LINE_SPACING",
4010 "Missing a blank line after declarations\n" . $hereprev) &&
4012 fix_insert_line($fixlinenr, "\+");
4017 # check for spaces at the beginning of a line.
4019 # 1) within comments
4020 # 2) indented preprocessor commands
4022 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4023 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4024 if (WARN("LEADING_SPACE",
4025 "please, no spaces at the start of a line\n" . $herevet) &&
4027 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4031 # check we are in a valid C source file if not then ignore this hunk
4032 next if ($realfile !~ /\.(h|c)$/);
4034 # check for unusual line ending [ or (
4035 if ($line =~ /^\+.*([\[\(])\s*$/) {
4036 CHK("OPEN_ENDED_LINE",
4037 "Lines should not end with a '$1'\n" . $herecurr);
4040 # check if this appears to be the start function declaration, save the name
4041 if ($sline =~ /^\+\{\s*$/ &&
4042 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4043 $context_function = $1;
4046 # check if this appears to be the end of function declaration
4047 if ($sline =~ /^\+\}\s*$/) {
4048 undef $context_function;
4051 # check indentation of any line with a bare else
4052 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4053 # if the previous line is a break or return and is indented 1 tab more...
4054 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4055 my $tabs = length($1) + 1;
4056 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4057 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4058 defined $lines[$linenr] &&
4059 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4060 WARN("UNNECESSARY_ELSE",
4061 "else is not generally useful after a break or return\n" . $hereprev);
4065 # check indentation of a line with a break;
4066 # if the previous line is a goto, return or break
4067 # and is indented the same # of tabs
4068 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4070 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4071 if (WARN("UNNECESSARY_BREAK",
4072 "break is not useful after a $1\n" . $hereprev) &&
4074 fix_delete_line($fixlinenr, $rawline);
4079 # check for RCS/CVS revision markers
4080 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4082 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4085 # check for old HOTPLUG __dev<foo> section markings
4086 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4087 WARN("HOTPLUG_SECTION",
4088 "Using $1 is unnecessary\n" . $herecurr);
4091 # Check for potential 'bare' types
4092 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4094 #print "LINE<$line>\n";
4095 if ($linenr > $suppress_statement &&
4096 $realcnt && $sline =~ /.\s*\S/) {
4097 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4098 ctx_statement_block($linenr, $realcnt, 0);
4099 $stat =~ s/\n./\n /g;
4100 $cond =~ s/\n./\n /g;
4102 #print "linenr<$linenr> <$stat>\n";
4103 # If this statement has no statement boundaries within
4104 # it there is no point in retrying a statement scan
4105 # until we hit end of it.
4106 my $frag = $stat; $frag =~ s/;+\s*$//;
4107 if ($frag !~ /(?:{|;)/) {
4108 #print "skip<$line_nr_next>\n";
4109 $suppress_statement = $line_nr_next;
4112 # Find the real next line.
4113 $realline_next = $line_nr_next;
4114 if (defined $realline_next &&
4115 (!defined $lines[$realline_next - 1] ||
4116 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4123 # Ignore goto labels.
4124 if ($s =~ /$Ident:\*$/s) {
4126 # Ignore functions being called
4127 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4129 } elsif ($s =~ /^.\s*else\b/s) {
4131 # declarations always start with types
4132 } 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) {
4135 possible($type, "A:" . $s);
4137 # definitions in global scope can only start with types
4138 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4139 possible($1, "B:" . $s);
4142 # any (foo ... *) is a pointer cast, and foo is a type
4143 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4144 possible($1, "C:" . $s);
4147 # Check for any sort of function declaration.
4148 # int foo(something bar, other baz);
4149 # void (*store_gdt)(x86_descr_ptr *);
4150 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4151 my ($name_len) = length($1);
4154 substr($ctx, 0, $name_len + 1, '');
4155 $ctx =~ s/\)[^\)]*$//;
4157 for my $arg (split(/\s*,\s*/, $ctx)) {
4158 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4160 possible($1, "D:" . $s);
4168 # Checks which may be anchored in the context.
4171 # Check for switch () and associated case and default
4172 # statements should be at the same indent.
4173 if ($line=~/\bswitch\s*\(.*\)/) {
4176 my @ctx = ctx_block_outer($linenr, $realcnt);
4178 for my $ctx (@ctx) {
4179 my ($clen, $cindent) = line_stats($ctx);
4180 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4181 $indent != $cindent) {
4182 $err .= "$sep$ctx\n";
4189 ERROR("SWITCH_CASE_INDENT_LEVEL",
4190 "switch and case should be at the same indent\n$hereline$err");
4194 # if/while/etc brace do not go on next line, unless defining a do while loop,
4195 # or if that brace on the next line is for something else
4196 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4197 my $pre_ctx = "$1$2";
4199 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4201 if ($line =~ /^\+\t{6,}/) {
4202 WARN("DEEP_INDENTATION",
4203 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4206 my $ctx_cnt = $realcnt - $#ctx - 1;
4207 my $ctx = join("\n", @ctx);
4209 my $ctx_ln = $linenr;
4210 my $ctx_skip = $realcnt;
4212 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4213 defined $lines[$ctx_ln - 1] &&
4214 $lines[$ctx_ln - 1] =~ /^-/)) {
4215 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4216 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4220 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4221 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4223 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4225 "that open brace { should be on the previous line\n" .
4226 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4228 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4229 $ctx =~ /\)\s*\;\s*$/ &&
4230 defined $lines[$ctx_ln - 1])
4232 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4233 if ($nindent > $indent) {
4234 WARN("TRAILING_SEMICOLON",
4235 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4236 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4241 # Check relative indent for conditionals and blocks.
4242 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4243 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4244 ctx_statement_block($linenr, $realcnt, 0)
4245 if (!defined $stat);
4246 my ($s, $c) = ($stat, $cond);
4248 substr($s, 0, length($c), '');
4250 # remove inline comments
4254 # Find out how long the conditional actually is.
4255 my @newlines = ($c =~ /\n/gs);
4256 my $cond_lines = 1 + $#newlines;
4258 # Make sure we remove the line prefixes as we have
4259 # none on the first line, and are going to readd them
4262 while ($s =~ /\n\s+\\\n/) {
4263 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4266 # We want to check the first line inside the block
4267 # starting at the end of the conditional, so remove:
4268 # 1) any blank line termination
4269 # 2) any opening brace { on end of the line
4271 my $continuation = 0;
4273 $s =~ s/^.*\bdo\b//;
4275 if ($s =~ s/^\s*\\//) {
4278 if ($s =~ s/^\s*?\n//) {
4283 # Also ignore a loop construct at the end of a
4284 # preprocessor statement.
4285 if (($prevline =~ /^.\s*#\s*define\s/ ||
4286 $prevline =~ /\\\s*$/) && $continuation == 0) {
4292 while ($cond_ptr != $cond_lines) {
4293 $cond_ptr = $cond_lines;
4295 # If we see an #else/#elif then the code
4297 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4302 # 1) blank lines, they should be at 0,
4303 # 2) preprocessor lines, and
4305 if ($continuation ||
4307 $s =~ /^\s*#\s*?/ ||
4308 $s =~ /^\s*$Ident\s*:/) {
4309 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4310 if ($s =~ s/^.*?\n//) {
4316 my (undef, $sindent) = line_stats("+" . $s);
4317 my $stat_real = raw_line($linenr, $cond_lines);
4319 # Check if either of these lines are modified, else
4320 # this is not this patch's fault.
4321 if (!defined($stat_real) ||
4322 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4325 if (defined($stat_real) && $cond_lines > 1) {
4326 $stat_real = "[...]\n$stat_real";
4329 #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";
4331 if ($check && $s ne '' &&
4332 (($sindent % $tabsize) != 0 ||
4333 ($sindent < $indent) ||
4334 ($sindent == $indent &&
4335 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4336 ($sindent > $indent + $tabsize))) {
4337 WARN("SUSPECT_CODE_INDENT",
4338 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4342 # Track the 'values' across context and added lines.
4343 my $opline = $line; $opline =~ s/^./ /;
4344 my ($curr_values, $curr_vars) =
4345 annotate_values($opline . "\n", $prev_values);
4346 $curr_values = $prev_values . $curr_values;
4348 my $outline = $opline; $outline =~ s/\t/ /g;
4349 print "$linenr > .$outline\n";
4350 print "$linenr > $curr_values\n";
4351 print "$linenr > $curr_vars\n";
4353 $prev_values = substr($curr_values, -1);
4355 #ignore lines not being added
4356 next if ($line =~ /^[^\+]/);
4358 # check for self assignments used to avoid compiler warnings
4359 # e.g.: int foo = foo, *bar = NULL;
4360 # struct foo bar = *(&(bar));
4361 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4363 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4364 WARN("SELF_ASSIGNMENT",
4365 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4369 # check for dereferences that span multiple lines
4370 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4371 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4372 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4374 $line =~ /^.\s*($Lval)/;
4377 WARN("MULTILINE_DEREFERENCE",
4378 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4381 # check for declarations of signed or unsigned without int
4382 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4385 $var = "" if (!defined $var);
4386 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4390 $pointer = "" if (!defined $pointer);
4392 if (WARN("UNSPECIFIED_INT",
4393 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4395 my $decl = trim($sign) . " int ";
4396 my $comp_pointer = $pointer;
4397 $comp_pointer =~ s/\s//g;
4398 $decl .= $comp_pointer;
4399 $decl = rtrim($decl) if ($var eq "");
4400 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4405 # TEST: allow direct testing of the type matcher.
4407 if ($line =~ /^.\s*$Declare\s*$/) {
4409 "TEST: is type\n" . $herecurr);
4410 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4411 ERROR("TEST_NOT_TYPE",
4412 "TEST: is not type ($1 is)\n". $herecurr);
4416 # TEST: allow direct testing of the attribute matcher.
4418 if ($line =~ /^.\s*$Modifier\s*$/) {
4420 "TEST: is attr\n" . $herecurr);
4421 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4422 ERROR("TEST_NOT_ATTR",
4423 "TEST: is not attr ($1 is)\n". $herecurr);
4428 # check for initialisation to aggregates open brace on the next line
4429 if ($line =~ /^.\s*{/ &&
4430 $prevline =~ /(?:^|[^=])=\s*$/) {
4431 if (ERROR("OPEN_BRACE",
4432 "that open brace { should be on the previous line\n" . $hereprev) &&
4433 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4434 fix_delete_line($fixlinenr - 1, $prevrawline);
4435 fix_delete_line($fixlinenr, $rawline);
4436 my $fixedline = $prevrawline;
4437 $fixedline =~ s/\s*=\s*$/ = {/;
4438 fix_insert_line($fixlinenr, $fixedline);
4440 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4441 fix_insert_line($fixlinenr, $fixedline);
4446 # Checks which are anchored on the added line.
4449 # check for malformed paths in #include statements (uses RAW line)
4450 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4452 if ($path =~ m{//}) {
4453 ERROR("MALFORMED_INCLUDE",
4454 "malformed #include filename\n" . $herecurr);
4456 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4457 ERROR("UAPI_INCLUDE",
4458 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4462 # no C99 // comments
4463 if ($line =~ m{//}) {
4464 if (ERROR("C99_COMMENTS",
4465 "do not use C99 // comments\n" . $herecurr) &&
4467 my $line = $fixed[$fixlinenr];
4468 if ($line =~ /\/\/(.*)$/) {
4469 my $comment = trim($1);
4470 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4474 # Remove C99 comments.
4476 $opline =~ s@//.*@@;
4478 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4479 # the whole statement.
4480 #print "APW <$lines[$realline_next - 1]>\n";
4481 if (defined $realline_next &&
4482 exists $lines[$realline_next - 1] &&
4483 !defined $suppress_export{$realline_next} &&
4484 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4485 # Handle definitions which produce identifiers with
4488 # EXPORT_SYMBOL(something_foo);
4490 $name =~ s/^\s*($Ident).*/$1/;
4491 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4492 $name =~ /^${Ident}_$2/) {
4493 #print "FOO C name<$name>\n";
4494 $suppress_export{$realline_next} = 1;
4496 } elsif ($stat !~ /(?:
4498 ^.DEFINE_$Ident\(\Q$name\E\)|
4499 ^.DECLARE_$Ident\(\Q$name\E\)|
4500 ^.LIST_HEAD\(\Q$name\E\)|
4501 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4502 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4504 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4505 $suppress_export{$realline_next} = 2;
4507 $suppress_export{$realline_next} = 1;
4510 if (!defined $suppress_export{$linenr} &&
4511 $prevline =~ /^.\s*$/ &&
4512 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4513 #print "FOO B <$lines[$linenr - 1]>\n";
4514 $suppress_export{$linenr} = 2;
4516 if (defined $suppress_export{$linenr} &&
4517 $suppress_export{$linenr} == 2) {
4518 WARN("EXPORT_SYMBOL",
4519 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4522 # check for global initialisers.
4523 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4524 !exclude_global_initialisers($realfile)) {
4525 if (ERROR("GLOBAL_INITIALISERS",
4526 "do not initialise globals to $1\n" . $herecurr) &&
4528 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4531 # check for static initialisers.
4532 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4533 if (ERROR("INITIALISED_STATIC",
4534 "do not initialise statics to $1\n" .
4537 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4541 # check for misordered declarations of char/short/int/long with signed/unsigned
4542 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4544 WARN("MISORDERED_TYPE",
4545 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4548 # check for unnecessary <signed> int declarations of short/long/long long
4549 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4550 my $type = trim($1);
4551 next if ($type !~ /\bint\b/);
4552 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4553 my $new_type = $type;
4554 $new_type =~ s/\b\s*int\s*\b/ /;
4555 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4556 $new_type =~ s/^const\s+//;
4557 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4558 $new_type = "const $new_type" if ($type =~ /^const\b/);
4559 $new_type =~ s/\s+/ /g;
4560 $new_type = trim($new_type);
4561 if (WARN("UNNECESSARY_INT",
4562 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4564 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4568 # check for static const char * arrays.
4569 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4570 WARN("STATIC_CONST_CHAR_ARRAY",
4571 "static const char * array should probably be static const char * const\n" .
4575 # check for initialized const char arrays that should be static const
4576 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4577 if (WARN("STATIC_CONST_CHAR_ARRAY",
4578 "const array should probably be static const\n" . $herecurr) &&
4580 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4584 # check for static char foo[] = "bar" declarations.
4585 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4586 WARN("STATIC_CONST_CHAR_ARRAY",
4587 "static char array declaration should probably be static const char\n" .
4591 # check for const <foo> const where <foo> is not a pointer or array type
4592 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4594 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4596 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4597 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4599 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4603 # check for const static or static <non ptr type> const declarations
4604 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4605 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4606 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4607 if (WARN("STATIC_CONST",
4608 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4610 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4611 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4615 # check for non-global char *foo[] = {"bar", ...} declarations.
4616 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4617 WARN("STATIC_CONST_CHAR_ARRAY",
4618 "char * array declaration might be better as static const\n" .
4622 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4623 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4625 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4627 if (WARN("ARRAY_SIZE",
4628 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4630 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4635 # check for function declarations without arguments like "int foo()"
4636 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4637 if (ERROR("FUNCTION_WITHOUT_ARGS",
4638 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4640 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4644 # check for new typedefs, only function parameters and sparse annotations
4646 if ($line =~ /\btypedef\s/ &&
4647 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4648 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4649 $line !~ /\b$typeTypedefs\b/ &&
4650 $line !~ /\b__bitwise\b/) {
4651 WARN("NEW_TYPEDEFS",
4652 "do not add new typedefs\n" . $herecurr);
4655 # * goes on variable not on type
4657 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4659 my ($ident, $from, $to) = ($1, $2, $2);
4661 # Should start with a space.
4662 $to =~ s/^(\S)/ $1/;
4663 # Should not end with a space.
4665 # '*'s should not have spaces between.
4666 while ($to =~ s/\*\s+\*/\*\*/) {
4669 ## print "1: from<$from> to<$to> ident<$ident>\n";
4671 if (ERROR("POINTER_LOCATION",
4672 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4674 my $sub_from = $ident;
4675 my $sub_to = $ident;
4676 $sub_to =~ s/\Q$from\E/$to/;
4677 $fixed[$fixlinenr] =~
4678 s@\Q$sub_from\E@$sub_to@;
4682 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4684 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4686 # Should start with a space.
4687 $to =~ s/^(\S)/ $1/;
4688 # Should not end with a space.
4690 # '*'s should not have spaces between.
4691 while ($to =~ s/\*\s+\*/\*\*/) {
4693 # Modifiers should have spaces.
4694 $to =~ s/(\b$Modifier$)/$1 /;
4696 ## print "2: from<$from> to<$to> ident<$ident>\n";
4697 if ($from ne $to && $ident !~ /^$Modifier$/) {
4698 if (ERROR("POINTER_LOCATION",
4699 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4702 my $sub_from = $match;
4703 my $sub_to = $match;
4704 $sub_to =~ s/\Q$from\E/$to/;
4705 $fixed[$fixlinenr] =~
4706 s@\Q$sub_from\E@$sub_to@;
4711 # avoid BUG() or BUG_ON()
4712 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4713 my $msg_level = \&WARN;
4714 $msg_level = \&CHK if ($file);
4715 &{$msg_level}("AVOID_BUG",
4716 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4719 # avoid LINUX_VERSION_CODE
4720 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4721 WARN("LINUX_VERSION_CODE",
4722 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4725 # check for uses of printk_ratelimit
4726 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4727 WARN("PRINTK_RATELIMITED",
4728 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4731 # printk should use KERN_* levels
4732 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4733 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4734 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4737 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4738 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4742 $modifier = "" if (!defined($modifier));
4743 my $level = lc($orig);
4744 $level = "warn" if ($level eq "warning");
4745 my $level2 = $level;
4746 $level2 = "dbg" if ($level eq "debug");
4747 $level .= $modifier;
4748 $level2 .= $modifier;
4749 WARN("PREFER_PR_LEVEL",
4750 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4753 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4754 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4756 my $level = lc($orig);
4757 $level = "warn" if ($level eq "warning");
4758 $level = "dbg" if ($level eq "debug");
4759 WARN("PREFER_DEV_LEVEL",
4760 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4763 # trace_printk should not be used in production code.
4764 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4765 WARN("TRACE_PRINTK",
4766 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4769 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4770 # number of false positives, but assembly files are not checked, so at
4771 # least the arch entry code will not trigger this warning.
4772 if ($line =~ /\bENOSYS\b/) {
4774 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4777 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4778 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4779 # Similarly to ENOSYS warning a small number of false positives is expected.
4780 if (!$file && $line =~ /\bENOTSUPP\b/) {
4781 if (WARN("ENOTSUPP",
4782 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4784 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4788 # function brace can't be on same line, except for #defines of do while,
4789 # or if closed on same line
4790 if ($perl_version_ok &&
4791 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4792 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4794 if (ERROR("OPEN_BRACE",
4795 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4797 fix_delete_line($fixlinenr, $rawline);
4798 my $fixed_line = $rawline;
4799 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4802 fix_insert_line($fixlinenr, ltrim($line1));
4803 fix_insert_line($fixlinenr, "\+{");
4804 if ($line2 !~ /^\s*$/) {
4805 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4810 # open braces for enum, union and struct go on the same line.
4811 if ($line =~ /^.\s*{/ &&
4812 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4813 if (ERROR("OPEN_BRACE",
4814 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4815 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4816 fix_delete_line($fixlinenr - 1, $prevrawline);
4817 fix_delete_line($fixlinenr, $rawline);
4818 my $fixedline = rtrim($prevrawline) . " {";
4819 fix_insert_line($fixlinenr, $fixedline);
4820 $fixedline = $rawline;
4821 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4822 if ($fixedline !~ /^\+\s*$/) {
4823 fix_insert_line($fixlinenr, $fixedline);
4828 # missing space after union, struct or enum definition
4829 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4831 "missing space after $1 definition\n" . $herecurr) &&
4833 $fixed[$fixlinenr] =~
4834 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4838 # Function pointer declarations
4839 # check spacing between type, funcptr, and args
4840 # canonical declaration is "type (*funcptr)(args...)"
4841 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4843 my $pre_pointer_space = $2;
4844 my $post_pointer_space = $3;
4846 my $post_funcname_space = $5;
4847 my $pre_args_space = $6;
4849 # the $Declare variable will capture all spaces after the type
4850 # so check it for a missing trailing missing space but pointer return types
4851 # don't need a space so don't warn for those.
4852 my $post_declare_space = "";
4853 if ($declare =~ /(\s+)$/) {
4854 $post_declare_space = $1;
4855 $declare = rtrim($declare);
4857 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4859 "missing space after return type\n" . $herecurr);
4860 $post_declare_space = " ";
4863 # unnecessary space "type (*funcptr)(args...)"
4864 # This test is not currently implemented because these declarations are
4866 # int foo(int bar, ...)
4867 # and this is form shouldn't/doesn't generate a checkpatch warning.
4869 # elsif ($declare =~ /\s{2,}$/) {
4871 # "Multiple spaces after return type\n" . $herecurr);
4874 # unnecessary space "type ( *funcptr)(args...)"
4875 if (defined $pre_pointer_space &&
4876 $pre_pointer_space =~ /^\s/) {
4878 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4881 # unnecessary space "type (* funcptr)(args...)"
4882 if (defined $post_pointer_space &&
4883 $post_pointer_space =~ /^\s/) {
4885 "Unnecessary space before function pointer name\n" . $herecurr);
4888 # unnecessary space "type (*funcptr )(args...)"
4889 if (defined $post_funcname_space &&
4890 $post_funcname_space =~ /^\s/) {
4892 "Unnecessary space after function pointer name\n" . $herecurr);
4895 # unnecessary space "type (*funcptr) (args...)"
4896 if (defined $pre_args_space &&
4897 $pre_args_space =~ /^\s/) {
4899 "Unnecessary space before function pointer arguments\n" . $herecurr);
4902 if (show_type("SPACING") && $fix) {
4903 $fixed[$fixlinenr] =~
4904 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4908 # check for spacing round square brackets; allowed:
4909 # 1. with a type on the left -- int [] a;
4910 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4911 # 3. inside a curly brace -- = { [0...10] = 5 }
4912 while ($line =~ /(.*?\s)\[/g) {
4913 my ($where, $prefix) = ($-[1], $1);
4914 if ($prefix !~ /$Type\s+$/ &&
4915 ($where != 0 || $prefix !~ /^.\s+$/) &&
4916 $prefix !~ /[{,:]\s+$/) {
4917 if (ERROR("BRACKET_SPACE",
4918 "space prohibited before open square bracket '['\n" . $herecurr) &&
4920 $fixed[$fixlinenr] =~
4921 s/^(\+.*?)\s+\[/$1\[/;
4926 # check for spaces between functions and their parentheses.
4927 while ($line =~ /($Ident)\s+\(/g) {
4929 my $ctx_before = substr($line, 0, $-[1]);
4930 my $ctx = "$ctx_before$name";
4932 # Ignore those directives where spaces _are_ permitted.
4934 if|for|while|switch|return|case|
4935 volatile|__volatile__|
4936 __attribute__|format|__extension__|
4939 # cpp #define statements have non-optional spaces, ie
4940 # if there is a space between the name and the open
4941 # parenthesis it is simply not a parameter group.
4942 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4944 # cpp #elif statement condition may start with a (
4945 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4947 # If this whole things ends with a type its most
4948 # likely a typedef for a function.
4949 } elsif ($ctx =~ /$Type$/) {
4953 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4955 $fixed[$fixlinenr] =~
4956 s/\b$name\s+\(/$name\(/;
4961 # Check operator spacing.
4962 if (!($line=~/\#\s*include/)) {
4963 my $fixed_line = "";
4967 <<=|>>=|<=|>=|==|!=|
4968 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4969 =>|->|<<|>>|<|>|=|!|~|
4970 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4973 my @elements = split(/($ops|;)/, $opline);
4975 ## print("element count: <" . $#elements . ">\n");
4976 ## foreach my $el (@elements) {
4977 ## print("el: <$el>\n");
4980 my @fix_elements = ();
4983 foreach my $el (@elements) {
4984 push(@fix_elements, substr($rawline, $off, length($el)));
4985 $off += length($el);
4990 my $blank = copy_spacing($opline);
4991 my $last_after = -1;
4993 for (my $n = 0; $n < $#elements; $n += 2) {
4995 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4997 ## print("n: <$n> good: <$good>\n");
4999 $off += length($elements[$n]);
5001 # Pick up the preceding and succeeding characters.
5002 my $ca = substr($opline, 0, $off);
5004 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5005 $cc = substr($opline, $off + length($elements[$n + 1]));
5007 my $cb = "$ca$;$cc";
5010 $a = 'V' if ($elements[$n] ne '');
5011 $a = 'W' if ($elements[$n] =~ /\s$/);
5012 $a = 'C' if ($elements[$n] =~ /$;$/);
5013 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5014 $a = 'O' if ($elements[$n] eq '');
5015 $a = 'E' if ($ca =~ /^\s*$/);
5017 my $op = $elements[$n + 1];
5020 if (defined $elements[$n + 2]) {
5021 $c = 'V' if ($elements[$n + 2] ne '');
5022 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5023 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5024 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5025 $c = 'O' if ($elements[$n + 2] eq '');
5026 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5031 my $ctx = "${a}x${c}";
5033 my $at = "(ctx:$ctx)";
5035 my $ptr = substr($blank, 0, $off) . "^";
5036 my $hereptr = "$hereline$ptr\n";
5038 # Pull out the value of this operator.
5039 my $op_type = substr($curr_values, $off + 1, 1);
5041 # Get the full operator variant.
5042 my $opv = $op . substr($curr_vars, $off, 1);
5044 # Ignore operators passed as parameters.
5045 if ($op_type ne 'V' &&
5046 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5049 # } elsif ($op =~ /^$;+$/) {
5051 # ; should have either the end of line or a space or \ after it
5052 } elsif ($op eq ';') {
5053 if ($ctx !~ /.x[WEBC]/ &&
5054 $cc !~ /^\\/ && $cc !~ /^;/) {
5055 if (ERROR("SPACING",
5056 "space required after that '$op' $at\n" . $hereptr)) {
5057 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5063 } elsif ($op eq '//') {
5065 # : when part of a bitfield
5066 } elsif ($opv eq ':B') {
5067 # skip the bitfield test for now
5071 } elsif ($op eq '->') {
5072 if ($ctx =~ /Wx.|.xW/) {
5073 if (ERROR("SPACING",
5074 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5075 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5076 if (defined $fix_elements[$n + 2]) {
5077 $fix_elements[$n + 2] =~ s/^\s+//;
5083 # , must not have a space before and must have a space on the right.
5084 } elsif ($op eq ',') {
5085 my $rtrim_before = 0;
5086 my $space_after = 0;
5087 if ($ctx =~ /Wx./) {
5088 if (ERROR("SPACING",
5089 "space prohibited before that '$op' $at\n" . $hereptr)) {
5094 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5095 if (ERROR("SPACING",
5096 "space required after that '$op' $at\n" . $hereptr)) {
5102 if ($rtrim_before || $space_after) {
5103 if ($rtrim_before) {
5104 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5106 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5113 # '*' as part of a type definition -- reported already.
5114 } elsif ($opv eq '*_') {
5115 #warn "'*' is part of type\n";
5117 # unary operators should have a space before and
5118 # none after. May be left adjacent to another
5119 # unary operator, or a cast
5120 } elsif ($op eq '!' || $op eq '~' ||
5121 $opv eq '*U' || $opv eq '-U' ||
5122 $opv eq '&U' || $opv eq '&&U') {
5123 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5124 if (ERROR("SPACING",
5125 "space required before that '$op' $at\n" . $hereptr)) {
5126 if ($n != $last_after + 2) {
5127 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5132 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5133 # A unary '*' may be const
5135 } elsif ($ctx =~ /.xW/) {
5136 if (ERROR("SPACING",
5137 "space prohibited after that '$op' $at\n" . $hereptr)) {
5138 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5139 if (defined $fix_elements[$n + 2]) {
5140 $fix_elements[$n + 2] =~ s/^\s+//;
5146 # unary ++ and unary -- are allowed no space on one side.
5147 } elsif ($op eq '++' or $op eq '--') {
5148 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5149 if (ERROR("SPACING",
5150 "space required one side of that '$op' $at\n" . $hereptr)) {
5151 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5155 if ($ctx =~ /Wx[BE]/ ||
5156 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5157 if (ERROR("SPACING",
5158 "space prohibited before that '$op' $at\n" . $hereptr)) {
5159 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5163 if ($ctx =~ /ExW/) {
5164 if (ERROR("SPACING",
5165 "space prohibited after that '$op' $at\n" . $hereptr)) {
5166 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5167 if (defined $fix_elements[$n + 2]) {
5168 $fix_elements[$n + 2] =~ s/^\s+//;
5174 # << and >> may either have or not have spaces both sides
5175 } elsif ($op eq '<<' or $op eq '>>' or
5176 $op eq '&' or $op eq '^' or $op eq '|' or
5177 $op eq '+' or $op eq '-' or
5178 $op eq '*' or $op eq '/' or
5182 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5184 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5185 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5186 $fix_elements[$n + 2] =~ s/^\s+//;
5189 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5191 "space preferred before that '$op' $at\n" . $hereptr)) {
5192 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5196 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5197 if (ERROR("SPACING",
5198 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5199 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5200 if (defined $fix_elements[$n + 2]) {
5201 $fix_elements[$n + 2] =~ s/^\s+//;
5207 # A colon needs no spaces before when it is
5208 # terminating a case value or a label.
5209 } elsif ($opv eq ':C' || $opv eq ':L') {
5210 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5211 if (ERROR("SPACING",
5212 "space prohibited before that '$op' $at\n" . $hereptr)) {
5213 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5218 # All the others need spaces both sides.
5219 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5222 # Ignore email addresses <foo@bar>
5224 $cc =~ /^\S+\@\S+>/) ||
5226 $ca =~ /<\S+\@\S+$/))
5231 # for asm volatile statements
5232 # ignore a colon with another
5233 # colon immediately before or after
5235 ($ca =~ /:$/ || $cc =~ /^:/)) {
5239 # messages are ERROR, but ?: are CHK
5241 my $msg_level = \&ERROR;
5242 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5244 if (&{$msg_level}("SPACING",
5245 "spaces required around that '$op' $at\n" . $hereptr)) {
5246 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5247 if (defined $fix_elements[$n + 2]) {
5248 $fix_elements[$n + 2] =~ s/^\s+//;
5254 $off += length($elements[$n + 1]);
5256 ## print("n: <$n> GOOD: <$good>\n");
5258 $fixed_line = $fixed_line . $good;
5261 if (($#elements % 2) == 0) {
5262 $fixed_line = $fixed_line . $fix_elements[$#elements];
5265 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5266 $fixed[$fixlinenr] = $fixed_line;
5272 # check for whitespace before a non-naked semicolon
5273 if ($line =~ /^\+.*\S\s+;\s*$/) {
5275 "space prohibited before semicolon\n" . $herecurr) &&
5277 1 while $fixed[$fixlinenr] =~
5278 s/^(\+.*\S)\s+;/$1;/;
5282 # check for multiple assignments
5283 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5284 CHK("MULTIPLE_ASSIGNMENTS",
5285 "multiple assignments should be avoided\n" . $herecurr);
5288 ## # check for multiple declarations, allowing for a function declaration
5290 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5291 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5293 ## # Remove any bracketed sections to ensure we do not
5294 ## # falsely report the parameters of functions.
5296 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5298 ## if ($ln =~ /,/) {
5299 ## WARN("MULTIPLE_DECLARATION",
5300 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5304 #need space before brace following if, while, etc
5305 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5306 $line =~ /\b(?:else|do)\{/) {
5307 if (ERROR("SPACING",
5308 "space required before the open brace '{'\n" . $herecurr) &&
5310 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5314 ## # check for blank lines before declarations
5315 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5316 ## $prevrawline =~ /^.\s*$/) {
5318 ## "No blank lines before declarations\n" . $hereprev);
5322 # closing brace should have a space following it when it has anything
5324 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5325 if (ERROR("SPACING",
5326 "space required after that close brace '}'\n" . $herecurr) &&
5328 $fixed[$fixlinenr] =~
5329 s/}((?!(?:,|;|\)))\S)/} $1/;
5333 # check spacing on square brackets
5334 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5335 if (ERROR("SPACING",
5336 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5338 $fixed[$fixlinenr] =~
5342 if ($line =~ /\s\]/) {
5343 if (ERROR("SPACING",
5344 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5346 $fixed[$fixlinenr] =~
5351 # check spacing on parentheses
5352 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5353 $line !~ /for\s*\(\s+;/) {
5354 if (ERROR("SPACING",
5355 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5357 $fixed[$fixlinenr] =~
5361 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5362 $line !~ /for\s*\(.*;\s+\)/ &&
5363 $line !~ /:\s+\)/) {
5364 if (ERROR("SPACING",
5365 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5367 $fixed[$fixlinenr] =~
5372 # check unnecessary parentheses around addressof/dereference single $Lvals
5373 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5375 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5377 if (CHK("UNNECESSARY_PARENTHESES",
5378 "Unnecessary parentheses around $var\n" . $herecurr) &&
5380 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5384 # check for unnecessary parentheses around function pointer uses
5385 # ie: (foo->bar)(); should be foo->bar();
5386 # but not "if (foo->bar) (" to avoid some false positives
5387 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5389 if (CHK("UNNECESSARY_PARENTHESES",
5390 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5392 my $var2 = deparenthesize($var);
5394 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5398 # check for unnecessary parentheses around comparisons in if uses
5399 # when !drivers/staging or command-line uses --strict
5400 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5401 $perl_version_ok && defined($stat) &&
5402 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5404 my $test = substr($2, 1, -1);
5406 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5408 # avoid parentheses around potential macro args
5409 next if ($match =~ /^\s*\w+\s*$/);
5410 if (!defined($herectx)) {
5411 $herectx = $here . "\n";
5412 my $cnt = statement_rawlines($if_stat);
5413 for (my $n = 0; $n < $cnt; $n++) {
5414 my $rl = raw_line($linenr, $n);
5415 $herectx .= $rl . "\n";
5416 last if $rl =~ /^[ \+].*\{/;
5419 CHK("UNNECESSARY_PARENTHESES",
5420 "Unnecessary parentheses around '$match'\n" . $herectx);
5424 # check that goto labels aren't indented (allow a single space indentation)
5425 # and ignore bitfield definitions like foo:1
5426 # Strictly, labels can have whitespace after the identifier and before the :
5427 # but this is not allowed here as many ?: uses would appear to be labels
5428 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5429 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5430 $sline !~ /^.\s+default:/) {
5431 if (WARN("INDENTED_LABEL",
5432 "labels should not be indented\n" . $herecurr) &&
5434 $fixed[$fixlinenr] =~
5439 # check if a statement with a comma should be two statements like:
5440 # foo = bar(), /* comma should be semicolon */
5442 if (defined($stat) &&
5443 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5444 my $cnt = statement_rawlines($stat);
5445 my $herectx = get_stat_here($linenr, $cnt, $here);
5446 WARN("SUSPECT_COMMA_SEMICOLON",
5447 "Possible comma where semicolon could be used\n" . $herectx);
5450 # return is not a function
5451 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5453 if ($perl_version_ok &&
5454 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5456 $value = deparenthesize($value);
5457 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5458 ERROR("RETURN_PARENTHESES",
5459 "return is not a function, parentheses are not required\n" . $herecurr);
5461 } elsif ($spacing !~ /\s+/) {
5463 "space required before the open parenthesis '('\n" . $herecurr);
5467 # unnecessary return in a void function
5468 # at end-of-function, with the previous line a single leading tab, then return;
5469 # and the line before that not a goto label target like "out:"
5470 if ($sline =~ /^[ \+]}\s*$/ &&
5471 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5473 $lines[$linenr - 3] =~ /^[ +]/ &&
5474 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5476 "void function return statements are not generally useful\n" . $hereprev);
5479 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5480 if ($perl_version_ok &&
5481 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5482 my $openparens = $1;
5483 my $count = $openparens =~ tr@\(@\(@;
5485 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5486 my $comp = $4; #Not $1 because of $LvalOrFunc
5487 $msg = " - maybe == should be = ?" if ($comp eq "==");
5488 WARN("UNNECESSARY_PARENTHESES",
5489 "Unnecessary parentheses$msg\n" . $herecurr);
5493 # comparisons with a constant or upper case identifier on the left
5494 # avoid cases like "foo + BAR < baz"
5495 # only fix matches surrounded by parentheses to avoid incorrect
5496 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5497 if ($perl_version_ok &&
5498 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5503 my $newcomp = $comp;
5504 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5505 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5506 WARN("CONSTANT_COMPARISON",
5507 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5511 } elsif ($comp eq "<=") {
5513 } elsif ($comp eq ">") {
5515 } elsif ($comp eq ">=") {
5518 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5522 # Return of what appears to be an errno should normally be negative
5523 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5525 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5526 WARN("USE_NEGATIVE_ERRNO",
5527 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5531 # Need a space before open parenthesis after if, while etc
5532 if ($line =~ /\b(if|while|for|switch)\(/) {
5533 if (ERROR("SPACING",
5534 "space required before the open parenthesis '('\n" . $herecurr) &&
5536 $fixed[$fixlinenr] =~
5537 s/\b(if|while|for|switch)\(/$1 \(/;
5541 # Check for illegal assignment in if conditional -- and check for trailing
5542 # statements after the conditional.
5543 if ($line =~ /do\s*(?!{)/) {
5544 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5545 ctx_statement_block($linenr, $realcnt, 0)
5546 if (!defined $stat);
5547 my ($stat_next) = ctx_statement_block($line_nr_next,
5548 $remain_next, $off_next);
5549 $stat_next =~ s/\n./\n /g;
5550 ##print "stat<$stat> stat_next<$stat_next>\n";
5552 if ($stat_next =~ /^\s*while\b/) {
5553 # If the statement carries leading newlines,
5554 # then count those as offsets.
5556 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5558 statement_rawlines($whitespace) - 1;
5560 $suppress_whiletrailers{$line_nr_next +
5564 if (!defined $suppress_whiletrailers{$linenr} &&
5565 defined($stat) && defined($cond) &&
5566 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5567 my ($s, $c) = ($stat, $cond);
5568 my $fixed_assign_in_if = 0;
5570 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5571 if (ERROR("ASSIGN_IN_IF",
5572 "do not use assignment in if condition\n" . $herecurr) &&
5573 $fix && $perl_version_ok) {
5574 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5582 fix_delete_line($fixlinenr, $rawline);
5583 fix_insert_line($fixlinenr, "$space$statement;");
5584 my $newline = "${space}if (";
5585 $newline .= '!' if defined($not);
5586 $newline .= '(' if (defined $not && defined($test) && defined($against));
5587 $newline .= "$assigned";
5588 $newline .= " $test $against" if (defined($test) && defined($against));
5589 $newline .= ')' if (defined $not && defined($test) && defined($against));
5591 $newline .= " {" if (defined($brace));
5592 fix_insert_line($fixlinenr + 1, $newline);
5593 $fixed_assign_in_if = 1;
5598 # Find out what is on the end of the line after the
5600 substr($s, 0, length($c), '');
5602 $s =~ s/$;//g; # Remove any comments
5603 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5604 $c !~ /}\s*while\s*/)
5606 # Find out how long the conditional actually is.
5607 my @newlines = ($c =~ /\n/gs);
5608 my $cond_lines = 1 + $#newlines;
5611 $stat_real = raw_line($linenr, $cond_lines)
5612 . "\n" if ($cond_lines);
5613 if (defined($stat_real) && $cond_lines > 1) {
5614 $stat_real = "[...]\n$stat_real";
5617 if (ERROR("TRAILING_STATEMENTS",
5618 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5619 !$fixed_assign_in_if &&
5621 $fix && $perl_version_ok &&
5622 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5625 my $rest = rtrim($4);
5626 if ($rest =~ /;$/) {
5627 $fixed[$fixlinenr] = "\+$indent$test";
5628 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5634 # Check for bitwise tests written as boolean
5646 WARN("HEXADECIMAL_BOOLEAN_TEST",
5647 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5650 # if and else should not have general statements after it
5651 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5653 $s =~ s/$;//g; # Remove any comments
5654 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5655 ERROR("TRAILING_STATEMENTS",
5656 "trailing statements should be on next line\n" . $herecurr);
5659 # if should not continue a brace
5660 if ($line =~ /}\s*if\b/) {
5661 ERROR("TRAILING_STATEMENTS",
5662 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5665 # case and default should not have general statements after them
5666 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5668 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5672 ERROR("TRAILING_STATEMENTS",
5673 "trailing statements should be on next line\n" . $herecurr);
5676 # Check for }<nl>else {, these must be at the same
5677 # indent level to be relevant to each other.
5678 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5679 $previndent == $indent) {
5680 if (ERROR("ELSE_AFTER_BRACE",
5681 "else should follow close brace '}'\n" . $hereprev) &&
5682 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5683 fix_delete_line($fixlinenr - 1, $prevrawline);
5684 fix_delete_line($fixlinenr, $rawline);
5685 my $fixedline = $prevrawline;
5686 $fixedline =~ s/}\s*$//;
5687 if ($fixedline !~ /^\+\s*$/) {
5688 fix_insert_line($fixlinenr, $fixedline);
5690 $fixedline = $rawline;
5691 $fixedline =~ s/^(.\s*)else/$1} else/;
5692 fix_insert_line($fixlinenr, $fixedline);
5696 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5697 $previndent == $indent) {
5698 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5700 # Find out what is on the end of the line after the
5702 substr($s, 0, length($c), '');
5705 if ($s =~ /^\s*;/) {
5706 if (ERROR("WHILE_AFTER_BRACE",
5707 "while should follow close brace '}'\n" . $hereprev) &&
5708 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5709 fix_delete_line($fixlinenr - 1, $prevrawline);
5710 fix_delete_line($fixlinenr, $rawline);
5711 my $fixedline = $prevrawline;
5712 my $trailing = $rawline;
5713 $trailing =~ s/^\+//;
5714 $trailing = trim($trailing);
5715 $fixedline =~ s/}\s*$/} $trailing/;
5716 fix_insert_line($fixlinenr, $fixedline);
5721 #Specific variable tests
5722 while ($line =~ m{($Constant|$Lval)}g) {
5726 if ($var !~ /^$Constant$/ &&
5727 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5728 #Ignore some autogenerated defines and enum values
5729 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5730 #Ignore Page<foo> variants
5731 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5732 #Ignore SI style variants like nS, mV and dB
5733 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5734 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5735 #Ignore some three character SI units explicitly, like MiB and KHz
5736 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5737 while ($var =~ m{\b($Ident)}g) {
5739 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5741 seed_camelcase_includes();
5742 if (!$file && !$camelcase_file_seeded) {
5743 seed_camelcase_file($realfile);
5744 $camelcase_file_seeded = 1;
5747 if (!defined $camelcase{$word}) {
5748 $camelcase{$word} = 1;
5750 "Avoid CamelCase: <$word>\n" . $herecurr);
5756 #no spaces allowed after \ in define
5757 if ($line =~ /\#\s*define.*\\\s+$/) {
5758 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5759 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5761 $fixed[$fixlinenr] =~ s/\s+$//;
5765 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5766 # itself <asm/foo.h> (uses RAW line)
5767 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5769 my $checkfile = "include/linux/$file";
5770 if (-f "$root/$checkfile" &&
5771 $realfile ne $checkfile &&
5772 $1 !~ /$allowed_asm_includes/)
5774 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5775 if ($asminclude > 0) {
5776 if ($realfile =~ m{^arch/}) {
5777 CHK("ARCH_INCLUDE_LINUX",
5778 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5780 WARN("INCLUDE_LINUX",
5781 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5787 # multi-statement macros should be enclosed in a do while loop, grab the
5788 # first statement and ensure its the whole macro if its not enclosed
5789 # in a known good container
5790 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5791 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5794 my ($off, $dstat, $dcond, $rest);
5796 my $has_flow_statement = 0;
5797 my $has_arg_concat = 0;
5798 ($dstat, $dcond, $ln, $cnt, $off) =
5799 ctx_statement_block($linenr, $realcnt, 0);
5801 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5802 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5804 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5805 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5807 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5808 my $define_args = $1;
5809 my $define_stmt = $dstat;
5812 if (defined $define_args && $define_args ne "") {
5813 $define_args = substr($define_args, 1, length($define_args) - 2);
5814 $define_args =~ s/\s*//g;
5815 $define_args =~ s/\\\+?//g;
5816 @def_args = split(",", $define_args);
5820 $dstat =~ s/\\\n.//g;
5821 $dstat =~ s/^\s*//s;
5822 $dstat =~ s/\s*$//s;
5824 # Flatten any parentheses and braces
5825 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5826 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5827 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5831 # Flatten any obvious string concatenation.
5832 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5833 $dstat =~ s/$Ident\s*($String)/$1/)
5837 # Make asm volatile uses seem like a generic function
5838 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5840 my $exceptions = qr{
5853 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5856 my $stmt_cnt = statement_rawlines($ctx);
5857 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5860 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5861 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5862 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5863 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5864 $dstat !~ /$exceptions/ &&
5865 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5866 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5867 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5868 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5869 $dstat !~ /^for\s*$Constant$/ && # for (...)
5870 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5871 $dstat !~ /^do\s*{/ && # do {...
5872 $dstat !~ /^\(\{/ && # ({...
5873 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5875 if ($dstat =~ /^\s*if\b/) {
5876 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5877 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5878 } elsif ($dstat =~ /;/) {
5879 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5880 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5882 ERROR("COMPLEX_MACRO",
5883 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5888 # Make $define_stmt single line, comment-free, etc
5889 my @stmt_array = split('\n', $define_stmt);
5892 foreach my $l (@stmt_array) {
5897 } elsif ($l =~ /^[\+ ]/) {
5898 $define_stmt .= substr($l, 1);
5901 $define_stmt =~ s/$;//g;
5902 $define_stmt =~ s/\s+/ /g;
5903 $define_stmt = trim($define_stmt);
5905 # check if any macro arguments are reused (ignore '...' and 'type')
5906 foreach my $arg (@def_args) {
5907 next if ($arg =~ /\.\.\./);
5908 next if ($arg =~ /^type$/i);
5909 my $tmp_stmt = $define_stmt;
5910 $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;
5911 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5912 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5913 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5915 CHK("MACRO_ARG_REUSE",
5916 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5918 # check if any macro arguments may have other precedence issues
5919 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5920 ((defined($1) && $1 ne ',') ||
5921 (defined($2) && $2 ne ','))) {
5922 CHK("MACRO_ARG_PRECEDENCE",
5923 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5927 # check for macros with flow control, but without ## concatenation
5928 # ## concatenation is commonly a macro that defines a function so ignore those
5929 if ($has_flow_statement && !$has_arg_concat) {
5930 my $cnt = statement_rawlines($ctx);
5931 my $herectx = get_stat_here($linenr, $cnt, $here);
5933 WARN("MACRO_WITH_FLOW_CONTROL",
5934 "Macros with flow control statements should be avoided\n" . "$herectx");
5937 # check for line continuations outside of #defines, preprocessor #, and asm
5940 if ($prevline !~ /^..*\\$/ &&
5941 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5942 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5943 $line =~ /^\+.*\\$/) {
5944 WARN("LINE_CONTINUATIONS",
5945 "Avoid unnecessary line continuations\n" . $herecurr);
5949 # do {} while (0) macro tests:
5950 # single-statement macros do not need to be enclosed in do while (0) loop,
5951 # macro should not end with a semicolon
5952 if ($perl_version_ok &&
5953 $realfile !~ m@/vmlinux.lds.h$@ &&
5954 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5957 my ($off, $dstat, $dcond, $rest);
5959 ($dstat, $dcond, $ln, $cnt, $off) =
5960 ctx_statement_block($linenr, $realcnt, 0);
5963 $dstat =~ s/\\\n.//g;
5966 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5971 my $cnt = statement_rawlines($ctx);
5972 my $herectx = get_stat_here($linenr, $cnt, $here);
5974 if (($stmts =~ tr/;/;/) == 1 &&
5975 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5976 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5977 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5979 if (defined $semis && $semis ne "") {
5980 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5981 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5983 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5985 my $cnt = statement_rawlines($ctx);
5986 my $herectx = get_stat_here($linenr, $cnt, $here);
5988 WARN("TRAILING_SEMICOLON",
5989 "macros should not use a trailing semicolon\n" . "$herectx");
5993 # check for redundant bracing round if etc
5994 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5995 my ($level, $endln, @chunks) =
5996 ctx_statement_full($linenr, $realcnt, 1);
5997 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5998 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5999 if ($#chunks > 0 && $level == 0) {
6003 my $herectx = $here . "\n";
6004 my $ln = $linenr - 1;
6005 for my $chunk (@chunks) {
6006 my ($cond, $block) = @{$chunk};
6008 # If the condition carries leading newlines, then count those as offsets.
6009 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6010 my $offset = statement_rawlines($whitespace) - 1;
6012 $allowed[$allow] = 0;
6013 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6015 # We have looked at and allowed this specific line.
6016 $suppress_ifbraces{$ln + $offset} = 1;
6018 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6019 $ln += statement_rawlines($block) - 1;
6021 substr($block, 0, length($cond), '');
6023 $seen++ if ($block =~ /^\s*{/);
6025 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6026 if (statement_lines($cond) > 1) {
6027 #print "APW: ALLOWED: cond<$cond>\n";
6028 $allowed[$allow] = 1;
6030 if ($block =~/\b(?:if|for|while)\b/) {
6031 #print "APW: ALLOWED: block<$block>\n";
6032 $allowed[$allow] = 1;
6034 if (statement_block_size($block) > 1) {
6035 #print "APW: ALLOWED: lines block<$block>\n";
6036 $allowed[$allow] = 1;
6041 my $sum_allowed = 0;
6042 foreach (@allowed) {
6045 if ($sum_allowed == 0) {
6047 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6048 } elsif ($sum_allowed != $allow &&
6051 "braces {} should be used on all arms of this statement\n" . $herectx);
6056 if (!defined $suppress_ifbraces{$linenr - 1} &&
6057 $line =~ /\b(if|while|for|else)\b/) {
6060 # Check the pre-context.
6061 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6062 #print "APW: ALLOWED: pre<$1>\n";
6066 my ($level, $endln, @chunks) =
6067 ctx_statement_full($linenr, $realcnt, $-[0]);
6069 # Check the condition.
6070 my ($cond, $block) = @{$chunks[0]};
6071 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6072 if (defined $cond) {
6073 substr($block, 0, length($cond), '');
6075 if (statement_lines($cond) > 1) {
6076 #print "APW: ALLOWED: cond<$cond>\n";
6079 if ($block =~/\b(?:if|for|while)\b/) {
6080 #print "APW: ALLOWED: block<$block>\n";
6083 if (statement_block_size($block) > 1) {
6084 #print "APW: ALLOWED: lines block<$block>\n";
6087 # Check the post-context.
6088 if (defined $chunks[1]) {
6089 my ($cond, $block) = @{$chunks[1]};
6090 if (defined $cond) {
6091 substr($block, 0, length($cond), '');
6093 if ($block =~ /^\s*\{/) {
6094 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6098 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6099 my $cnt = statement_rawlines($block);
6100 my $herectx = get_stat_here($linenr, $cnt, $here);
6103 "braces {} are not necessary for single statement blocks\n" . $herectx);
6107 # check for single line unbalanced braces
6108 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6109 $sline =~ /^.\s*else\s*\{\s*$/) {
6110 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6113 # check for unnecessary blank lines around braces
6114 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6116 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6117 $fix && $prevrawline =~ /^\+/) {
6118 fix_delete_line($fixlinenr - 1, $prevrawline);
6121 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6123 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6125 fix_delete_line($fixlinenr, $rawline);
6129 # no volatiles please
6130 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6131 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6133 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6136 # Check for user-visible strings broken across lines, which breaks the ability
6137 # to grep for the string. Make exceptions when the previous string ends in a
6138 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6139 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6140 if ($line =~ /^\+\s*$String/ &&
6141 $prevline =~ /"\s*$/ &&
6142 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6143 if (WARN("SPLIT_STRING",
6144 "quoted string split across lines\n" . $hereprev) &&
6146 $prevrawline =~ /^\+.*"\s*$/ &&
6147 $last_coalesced_string_linenr != $linenr - 1) {
6148 my $extracted_string = get_quoted_string($line, $rawline);
6149 my $comma_close = "";
6150 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6154 fix_delete_line($fixlinenr - 1, $prevrawline);
6155 fix_delete_line($fixlinenr, $rawline);
6156 my $fixedline = $prevrawline;
6157 $fixedline =~ s/"\s*$//;
6158 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6159 fix_insert_line($fixlinenr - 1, $fixedline);
6160 $fixedline = $rawline;
6161 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6162 if ($fixedline !~ /\+\s*$/) {
6163 fix_insert_line($fixlinenr, $fixedline);
6165 $last_coalesced_string_linenr = $linenr;
6169 # check for missing a space in a string concatenation
6170 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6171 WARN('MISSING_SPACE',
6172 "break quoted strings at a space character\n" . $hereprev);
6175 # check for an embedded function name in a string when the function is known
6176 # This does not work very well for -f --file checking as it depends on patch
6177 # context providing the function name or a single line form for in-file
6178 # function declarations
6179 if ($line =~ /^\+.*$String/ &&
6180 defined($context_function) &&
6181 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6182 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6183 WARN("EMBEDDED_FUNCTION_NAME",
6184 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6187 # check for unnecessary function tracing like uses
6188 # This does not use $logFunctions because there are many instances like
6189 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6190 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6191 if (WARN("TRACING_LOGGING",
6192 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6194 fix_delete_line($fixlinenr, $rawline);
6198 # check for spaces before a quoted newline
6199 if ($rawline =~ /^.*\".*\s\\n/) {
6200 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6201 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6203 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6208 # concatenated string without spaces between elements
6209 if ($line =~ /$String[A-Z_]/ ||
6210 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6211 if (CHK("CONCATENATED_STRING",
6212 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6214 while ($line =~ /($String)/g) {
6215 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6216 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6217 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6222 # uncoalesced string fragments
6223 if ($line =~ /$String\s*[Lu]?"/) {
6224 if (WARN("STRING_FRAGMENTS",
6225 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6227 while ($line =~ /($String)(?=\s*")/g) {
6228 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6229 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6234 # check for non-standard and hex prefixed decimal printf formats
6235 my $show_L = 1; #don't show the same defect twice
6237 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6238 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6239 $string =~ s/%%/__/g;
6241 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6243 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6247 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6249 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6252 # check for 0x<decimal>
6253 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6254 ERROR("PRINTF_0XDECIMAL",
6255 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6259 # check for line continuations in quoted strings with odd counts of "
6260 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6261 WARN("LINE_CONTINUATIONS",
6262 "Avoid line continuations in quoted strings\n" . $herecurr);
6266 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6268 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6272 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6274 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6277 # check for needless "if (<foo>) fn(<foo>)" uses
6278 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6279 my $tested = quotemeta($1);
6280 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6281 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6283 if (WARN('NEEDLESS_IF',
6284 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6287 my $leading_tabs = "";
6288 my $new_leading_tabs = "";
6289 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6294 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6295 $new_leading_tabs = $1;
6296 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6303 fix_delete_line($fixlinenr - 1, $prevrawline);
6304 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6310 # check for unnecessary "Out of Memory" messages
6311 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6312 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6313 (defined $1 || defined $3) &&
6316 my $testline = $lines[$linenr - 3];
6318 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6319 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6321 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6322 $s !~ /\b__GFP_NOWARN\b/ ) {
6324 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6328 # check for logging functions with KERN_<LEVEL>
6329 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6330 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6332 if (WARN("UNNECESSARY_KERN_LEVEL",
6333 "Possible unnecessary $level\n" . $herecurr) &&
6335 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6339 # check for logging continuations
6340 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6341 WARN("LOGGING_CONTINUATION",
6342 "Avoid logging continuation uses where feasible\n" . $herecurr);
6345 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6346 if (defined $stat &&
6347 $line =~ /\b$logFunctions\s*\(/ &&
6348 index($stat, '"') >= 0) {
6349 my $lc = $stat =~ tr@\n@@;
6350 $lc = $lc + $linenr;
6351 my $stat_real = get_stat_real($linenr, $lc);
6352 pos($stat_real) = index($stat_real, '"');
6353 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6356 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6357 if (WARN("UNNECESSARY_MODIFIER",
6358 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6359 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6362 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6367 # check for mask then right shift without a parentheses
6368 if ($perl_version_ok &&
6369 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6370 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6371 WARN("MASK_THEN_SHIFT",
6372 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6375 # check for pointer comparisons to NULL
6376 if ($perl_version_ok) {
6377 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6380 $equal = "" if ($4 eq "!=");
6381 if (CHK("COMPARISON_TO_NULL",
6382 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6384 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6389 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6390 if ($line =~ /(\b$InitAttribute\b)/) {
6392 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6395 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6396 ERROR("MISPLACED_INIT",
6397 "$attr should be placed after $var\n" . $herecurr)) ||
6398 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6399 WARN("MISPLACED_INIT",
6400 "$attr should be placed after $var\n" . $herecurr))) &&
6402 $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;
6407 # check for $InitAttributeData (ie: __initdata) with const
6408 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6410 $attr =~ /($InitAttributePrefix)(.*)/;
6411 my $attr_prefix = $1;
6413 if (ERROR("INIT_ATTRIBUTE",
6414 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6416 $fixed[$fixlinenr] =~
6417 s/$InitAttributeData/${attr_prefix}initconst/;
6421 # check for $InitAttributeConst (ie: __initconst) without const
6422 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6424 if (ERROR("INIT_ATTRIBUTE",
6425 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6427 my $lead = $fixed[$fixlinenr] =~
6428 /(^\+\s*(?:static\s+))/;
6430 $lead = "$lead " if ($lead !~ /^\+$/);
6431 $lead = "${lead}const ";
6432 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6436 # check for __read_mostly with const non-pointer (should just be const)
6437 if ($line =~ /\b__read_mostly\b/ &&
6438 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6439 if (ERROR("CONST_READ_MOSTLY",
6440 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6442 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6446 # don't use __constant_<foo> functions outside of include/uapi/
6447 if ($realfile !~ m@^include/uapi/@ &&
6448 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6449 my $constant_func = $1;
6450 my $func = $constant_func;
6451 $func =~ s/^__constant_//;
6452 if (WARN("CONSTANT_CONVERSION",
6453 "$constant_func should be $func\n" . $herecurr) &&
6455 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6459 # prefer usleep_range over udelay
6460 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6462 # ignore udelay's < 10, however
6463 if (! ($delay < 10) ) {
6465 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6467 if ($delay > 2000) {
6469 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6473 # warn about unexpectedly long msleep's
6474 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6477 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6481 # check for comparisons of jiffies
6482 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6483 WARN("JIFFIES_COMPARISON",
6484 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6487 # check for comparisons of get_jiffies_64()
6488 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6489 WARN("JIFFIES_COMPARISON",
6490 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6493 # warn about #ifdefs in C files
6494 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6495 # print "#ifdef in C files should be avoided\n";
6496 # print "$herecurr";
6500 # warn about spacing in #ifdefs
6501 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6502 if (ERROR("SPACING",
6503 "exactly one space required after that #$1\n" . $herecurr) &&
6505 $fixed[$fixlinenr] =~
6506 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6511 # check for spinlock_t definitions without a comment.
6512 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6513 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6515 if (!ctx_has_comment($first_line, $linenr)) {
6516 CHK("UNCOMMENTED_DEFINITION",
6517 "$1 definition without comment\n" . $herecurr);
6520 # check for memory barriers without a comment.
6527 my $barrier_stems = qr{
6535 my $all_barriers = qr{
6537 smp_(?:$barrier_stems)|
6538 virt_(?:$barrier_stems)
6541 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6542 if (!ctx_has_comment($first_line, $linenr)) {
6543 WARN("MEMORY_BARRIER",
6544 "memory barrier without comment\n" . $herecurr);
6548 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6550 if ($realfile !~ m@^include/asm-generic/@ &&
6551 $realfile !~ m@/barrier\.h$@ &&
6552 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6553 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6554 WARN("MEMORY_BARRIER",
6555 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6558 # check for waitqueue_active without a comment.
6559 if ($line =~ /\bwaitqueue_active\s*\(/) {
6560 if (!ctx_has_comment($first_line, $linenr)) {
6561 WARN("WAITQUEUE_ACTIVE",
6562 "waitqueue_active without comment\n" . $herecurr);
6566 # check for data_race without a comment.
6567 if ($line =~ /\bdata_race\s*\(/) {
6568 if (!ctx_has_comment($first_line, $linenr)) {
6570 "data_race without comment\n" . $herecurr);
6574 # check of hardware specific defines
6575 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6577 "architecture specific defines should be avoided\n" . $herecurr);
6580 # check that the storage class is not after a type
6581 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6582 WARN("STORAGE_CLASS",
6583 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6585 # Check that the storage class is at the beginning of a declaration
6586 if ($line =~ /\b$Storage\b/ &&
6587 $line !~ /^.\s*$Storage/ &&
6588 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6589 $1 !~ /[\,\)]\s*$/) {
6590 WARN("STORAGE_CLASS",
6591 "storage class should be at the beginning of the declaration\n" . $herecurr);
6594 # check the location of the inline attribute, that it is between
6595 # storage class and type.
6596 if ($line =~ /\b$Type\s+$Inline\b/ ||
6597 $line =~ /\b$Inline\s+$Storage\b/) {
6598 ERROR("INLINE_LOCATION",
6599 "inline keyword should sit between storage class and type\n" . $herecurr);
6602 # Check for __inline__ and __inline, prefer inline
6603 if ($realfile !~ m@\binclude/uapi/@ &&
6604 $line =~ /\b(__inline__|__inline)\b/) {
6606 "plain inline is preferred over $1\n" . $herecurr) &&
6608 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6613 # Check for compiler attributes
6614 if ($realfile !~ m@\binclude/uapi/@ &&
6615 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6617 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6620 "alias" => "__alias",
6621 "aligned" => "__aligned",
6622 "always_inline" => "__always_inline",
6623 "assume_aligned" => "__assume_aligned",
6625 "const" => "__attribute_const__",
6627 "designated_init" => "__designated_init",
6628 "externally_visible" => "__visible",
6629 "format" => "printf|scanf",
6630 "gnu_inline" => "__gnu_inline",
6631 "malloc" => "__malloc",
6633 "no_caller_saved_registers" => "__no_caller_saved_registers",
6634 "noclone" => "__noclone",
6635 "noinline" => "noinline",
6636 "nonstring" => "__nonstring",
6637 "noreturn" => "__noreturn",
6638 "packed" => "__packed",
6640 "section" => "__section",
6645 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6648 $params = $2 if defined($2);
6649 my $curr_attr = $orig_attr;
6650 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6651 if (exists($attr_list{$curr_attr})) {
6652 my $new = $attr_list{$curr_attr};
6653 if ($curr_attr eq "format" && $params) {
6654 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6657 $new = "$new$params";
6659 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6660 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6662 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6663 $fixed[$fixlinenr] =~ s/$remove//;
6664 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6665 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6666 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6671 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6672 if ($attr =~ /^_*unused/) {
6673 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6674 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6678 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6679 if ($perl_version_ok &&
6680 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6681 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6682 $line =~ /\b__weak\b/)) {
6683 ERROR("WEAK_DECLARATION",
6684 "Using weak declarations can have unintended link defects\n" . $herecurr);
6687 # check for c99 types like uint8_t used outside of uapi/ and tools/
6688 if ($realfile !~ m@\binclude/uapi/@ &&
6689 $realfile !~ m@\btools/@ &&
6690 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6692 if ($type =~ /\b($typeC99Typedefs)\b/) {
6694 my $kernel_type = 'u';
6695 $kernel_type = 's' if ($type =~ /^_*[si]/);
6698 if (CHK("PREFER_KERNEL_TYPES",
6699 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6701 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6706 # check for cast of C90 native int or longer types constants
6707 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6711 my $newconst = $const;
6712 $newconst =~ s/${Int_type}$//;
6713 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6714 if ($cast =~ /\blong\s+long\b/) {
6716 } elsif ($cast =~ /\blong\b/) {
6719 if (WARN("TYPECAST_INT_CONSTANT",
6720 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6722 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6726 # check for sizeof(&)
6727 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6728 WARN("SIZEOF_ADDRESS",
6729 "sizeof(& should be avoided\n" . $herecurr);
6732 # check for sizeof without parenthesis
6733 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6734 if (WARN("SIZEOF_PARENTHESIS",
6735 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6737 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6741 # check for struct spinlock declarations
6742 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6743 WARN("USE_SPINLOCK_T",
6744 "struct spinlock should be spinlock_t\n" . $herecurr);
6747 # check for seq_printf uses that could be seq_puts
6748 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6749 my $fmt = get_quoted_string($line, $rawline);
6752 if (WARN("PREFER_SEQ_PUTS",
6753 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6755 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6760 # check for vsprintf extension %p<foo> misuses
6761 if ($perl_version_ok &&
6763 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6764 $1 !~ /^_*volatile_*$/) {
6767 my $lc = $stat =~ tr@\n@@;
6768 $lc = $lc + $linenr;
6769 for (my $count = $linenr; $count <= $lc; $count++) {
6773 my $bad_specifier = "";
6774 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6777 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6781 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6782 ($extension eq "f" &&
6783 defined $qualifier && $qualifier !~ /^w/) ||
6784 ($extension eq "4" &&
6785 defined $qualifier && $qualifier !~ /^cc/)) {
6786 $bad_specifier = $specifier;
6789 if ($extension eq "x" && !defined($stat_real)) {
6790 if (!defined($stat_real)) {
6791 $stat_real = get_stat_real($linenr, $lc);
6793 WARN("VSPRINTF_SPECIFIER_PX",
6794 "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");
6797 if ($bad_specifier ne "") {
6798 my $stat_real = get_stat_real($linenr, $lc);
6799 my $ext_type = "Invalid";
6801 if ($bad_specifier =~ /p[Ff]/) {
6802 $use = " - use %pS instead";
6803 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6806 WARN("VSPRINTF_POINTER_EXTENSION",
6807 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6812 # Check for misused memsets
6813 if ($perl_version_ok &&
6815 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6821 if ($ms_size =~ /^(0x|)0$/i) {
6823 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6824 } elsif ($ms_size =~ /^(0x|)1$/i) {
6826 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6830 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6831 # if ($perl_version_ok &&
6833 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6834 # if (WARN("PREFER_ETHER_ADDR_COPY",
6835 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6837 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6841 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6842 # if ($perl_version_ok &&
6844 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6845 # WARN("PREFER_ETHER_ADDR_EQUAL",
6846 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6849 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6850 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6851 # if ($perl_version_ok &&
6853 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6857 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6858 # if (WARN("PREFER_ETH_ZERO_ADDR",
6859 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6861 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6863 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6864 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6865 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6867 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6872 # strlcpy uses that should likely be strscpy
6873 if ($line =~ /\bstrlcpy\s*\(/) {
6875 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6878 # typecasts on min/max could be min_t/max_t
6879 if ($perl_version_ok &&
6881 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6882 if (defined $2 || defined $7) {
6884 my $cast1 = deparenthesize($2);
6886 my $cast2 = deparenthesize($7);
6890 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6891 $cast = "$cast1 or $cast2";
6892 } elsif ($cast1 ne "") {
6898 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6902 # check usleep_range arguments
6903 if ($perl_version_ok &&
6905 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6909 WARN("USLEEP_RANGE",
6910 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6911 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6913 WARN("USLEEP_RANGE",
6914 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6918 # check for naked sscanf
6919 if ($perl_version_ok &&
6921 $line =~ /\bsscanf\b/ &&
6922 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6923 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6924 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6925 my $lc = $stat =~ tr@\n@@;
6926 $lc = $lc + $linenr;
6927 my $stat_real = get_stat_real($linenr, $lc);
6928 WARN("NAKED_SSCANF",
6929 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6932 # check for simple sscanf that should be kstrto<foo>
6933 if ($perl_version_ok &&
6935 $line =~ /\bsscanf\b/) {
6936 my $lc = $stat =~ tr@\n@@;
6937 $lc = $lc + $linenr;
6938 my $stat_real = get_stat_real($linenr, $lc);
6939 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6941 my $count = $format =~ tr@%@%@;
6943 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6944 WARN("SSCANF_TO_KSTRTO",
6945 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6950 # check for new externs in .h files.
6951 if ($realfile =~ /\.h$/ &&
6952 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6953 if (CHK("AVOID_EXTERNS",
6954 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6956 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6960 # check for new externs in .c files.
6961 if ($realfile =~ /\.c$/ && defined $stat &&
6962 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6964 my $function_name = $1;
6965 my $paren_space = $2;
6968 if (defined $cond) {
6969 substr($s, 0, length($cond), '');
6973 WARN("AVOID_EXTERNS",
6974 "externs should be avoided in .c files\n" . $herecurr);
6977 if ($paren_space =~ /\n/) {
6978 WARN("FUNCTION_ARGUMENTS",
6979 "arguments for function declarations should follow identifier\n" . $herecurr);
6982 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6983 $stat =~ /^.\s*extern\s+/)
6985 WARN("AVOID_EXTERNS",
6986 "externs should be avoided in .c files\n" . $herecurr);
6989 # check for function declarations that have arguments without identifier names
6990 if (defined $stat &&
6991 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6993 my $args = trim($1);
6994 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6996 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6997 WARN("FUNCTION_ARGUMENTS",
6998 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7003 # check for function definitions
7004 if ($perl_version_ok &&
7006 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7007 $context_function = $1;
7009 # check for multiline function definition with misplaced open brace
7011 my $cnt = statement_rawlines($stat);
7012 my $herectx = $here . "\n";
7013 for (my $n = 0; $n < $cnt; $n++) {
7014 my $rl = raw_line($linenr, $n);
7015 $herectx .= $rl . "\n";
7016 $ok = 1 if ($rl =~ /^[ \+]\{/);
7017 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7018 last if $rl =~ /^[ \+].*\{/;
7022 "open brace '{' following function definitions go on the next line\n" . $herectx);
7026 # checks for new __setup's
7027 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7030 if (!grep(/$name/, @setup_docs)) {
7031 CHK("UNDOCUMENTED_SETUP",
7032 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7036 # check for pointless casting of alloc functions
7037 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7038 WARN("UNNECESSARY_CASTS",
7039 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7043 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7044 if ($perl_version_ok &&
7045 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7046 CHK("ALLOC_SIZEOF_STRUCT",
7047 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7050 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7051 if ($perl_version_ok &&
7053 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7057 my $newfunc = "kmalloc_array";
7058 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7059 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7060 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7063 if ($a1 =~ /^sizeof\s*\S/) {
7067 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7068 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7069 my $cnt = statement_rawlines($stat);
7070 my $herectx = get_stat_here($linenr, $cnt, $here);
7072 if (WARN("ALLOC_WITH_MULTIPLY",
7073 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7076 $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;
7081 # check for krealloc arg reuse
7082 if ($perl_version_ok &&
7083 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7085 WARN("KREALLOC_ARG_REUSE",
7086 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7089 # check for alloc argument mismatch
7090 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7091 WARN("ALLOC_ARRAY_ARGS",
7092 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7095 # check for multiple semicolons
7096 if ($line =~ /;\s*;\s*$/) {
7097 if (WARN("ONE_SEMICOLON",
7098 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7100 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7104 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7105 if ($realfile !~ m@^include/uapi/@ &&
7106 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7108 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7109 if (CHK("BIT_MACRO",
7110 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7112 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7116 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7117 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7118 WARN("IS_ENABLED_CONFIG",
7119 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7122 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7123 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7125 if (WARN("PREFER_IS_ENABLED",
7126 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7128 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7132 # check for /* fallthrough */ like comment, prefer fallthrough;
7133 my @fallthroughs = (
7136 'lint -fallthrough[ \t]*',
7137 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7138 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7139 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7140 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7142 if ($raw_comment ne '') {
7143 foreach my $ft (@fallthroughs) {
7144 if ($raw_comment =~ /$ft/) {
7145 my $msg_level = \&WARN;
7146 $msg_level = \&CHK if ($file);
7147 &{$msg_level}("PREFER_FALLTHROUGH",
7148 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7154 # check for switch/default statements without a break;
7155 if ($perl_version_ok &&
7157 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7158 my $cnt = statement_rawlines($stat);
7159 my $herectx = get_stat_here($linenr, $cnt, $here);
7161 WARN("DEFAULT_NO_BREAK",
7162 "switch default: should use break\n" . $herectx);
7165 # check for gcc specific __FUNCTION__
7166 if ($line =~ /\b__FUNCTION__\b/) {
7167 if (WARN("USE_FUNC",
7168 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7170 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7174 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7175 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7177 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7180 # check for use of yield()
7181 if ($line =~ /\byield\s*\(\s*\)/) {
7183 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7186 # check for comparisons against true and false
7187 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7195 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7197 my $type = lc($otype);
7198 if ($type =~ /^(?:true|false)$/) {
7199 if (("$test" eq "==" && "$type" eq "true") ||
7200 ("$test" eq "!=" && "$type" eq "false")) {
7204 CHK("BOOL_COMPARISON",
7205 "Using comparison to $otype is error prone\n" . $herecurr);
7207 ## maybe suggesting a correct construct would better
7208 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7213 # check for semaphores initialized locked
7214 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7215 WARN("CONSIDER_COMPLETION",
7216 "consider using a completion\n" . $herecurr);
7219 # recommend kstrto* over simple_strto* and strict_strto*
7220 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7221 WARN("CONSIDER_KSTRTO",
7222 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7225 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7226 if ($line =~ /^.\s*__initcall\s*\(/) {
7227 WARN("USE_DEVICE_INITCALL",
7228 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7231 # check for spin_is_locked(), suggest lockdep instead
7232 if ($line =~ /\bspin_is_locked\(/) {
7234 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7237 # check for deprecated apis
7238 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7239 my $deprecated_api = $1;
7240 my $new_api = $deprecated_apis{$deprecated_api};
7241 WARN("DEPRECATED_API",
7242 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7245 # check for various structs that are normally const (ops, kgdb, device_tree)
7246 # and avoid what seem like struct definitions 'struct foo {'
7247 if (defined($const_structs) &&
7248 $line !~ /\bconst\b/ &&
7249 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7250 WARN("CONST_STRUCT",
7251 "struct $1 should normally be const\n" . $herecurr);
7254 # use of NR_CPUS is usually wrong
7255 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7256 # ignore designated initializers using NR_CPUS
7257 if ($line =~ /\bNR_CPUS\b/ &&
7258 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7259 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7260 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7261 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7262 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7263 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7266 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7269 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7270 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7271 ERROR("DEFINE_ARCH_HAS",
7272 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7275 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7276 if ($perl_version_ok &&
7277 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7278 WARN("LIKELY_MISUSE",
7279 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7282 # return sysfs_emit(foo, fmt, ...) fmt without newline
7283 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7284 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7285 my $offset = $+[6] - 1;
7286 if (WARN("SYSFS_EMIT",
7287 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7289 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7293 # nested likely/unlikely calls
7294 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7295 WARN("LIKELY_MISUSE",
7296 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7299 # whine mightly about in_atomic
7300 if ($line =~ /\bin_atomic\s*\(/) {
7301 if ($realfile =~ m@^drivers/@) {
7303 "do not use in_atomic in drivers\n" . $herecurr);
7304 } elsif ($realfile !~ m@^kernel/@) {
7306 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7310 # check for lockdep_set_novalidate_class
7311 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7312 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7313 if ($realfile !~ m@^kernel/lockdep@ &&
7314 $realfile !~ m@^include/linux/lockdep@ &&
7315 $realfile !~ m@^drivers/base/core@) {
7317 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7321 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7322 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7323 WARN("EXPORTED_WORLD_WRITABLE",
7324 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7327 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7328 # and whether or not function naming is typical and if
7329 # DEVICE_ATTR permissions uses are unusual too
7330 if ($perl_version_ok &&
7332 $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*\)/) {
7337 my $octal_perms = perms_to_octal($perms);
7338 if ($show =~ /^${var}_show$/ &&
7339 $store =~ /^${var}_store$/ &&
7340 $octal_perms eq "0644") {
7341 if (WARN("DEVICE_ATTR_RW",
7342 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7344 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7346 } elsif ($show =~ /^${var}_show$/ &&
7347 $store =~ /^NULL$/ &&
7348 $octal_perms eq "0444") {
7349 if (WARN("DEVICE_ATTR_RO",
7350 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7352 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7354 } elsif ($show =~ /^NULL$/ &&
7355 $store =~ /^${var}_store$/ &&
7356 $octal_perms eq "0200") {
7357 if (WARN("DEVICE_ATTR_WO",
7358 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7360 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7362 } elsif ($octal_perms eq "0644" ||
7363 $octal_perms eq "0444" ||
7364 $octal_perms eq "0200") {
7365 my $newshow = "$show";
7366 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7367 my $newstore = $store;
7368 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7370 if ($show ne $newshow) {
7371 $rename .= " '$show' to '$newshow'";
7373 if ($store ne $newstore) {
7374 $rename .= " '$store' to '$newstore'";
7376 WARN("DEVICE_ATTR_FUNCTIONS",
7377 "Consider renaming function(s)$rename\n" . $herecurr);
7379 WARN("DEVICE_ATTR_PERMS",
7380 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7384 # Mode permission misuses where it seems decimal should be octal
7385 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7386 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7387 # specific definition of not visible in sysfs.
7388 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7389 # use the default permissions
7390 if ($perl_version_ok &&
7392 $line =~ /$mode_perms_search/) {
7393 foreach my $entry (@mode_permission_funcs) {
7394 my $func = $entry->[0];
7395 my $arg_pos = $entry->[1];
7397 my $lc = $stat =~ tr@\n@@;
7398 $lc = $lc + $linenr;
7399 my $stat_real = get_stat_real($linenr, $lc);
7404 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7406 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7407 if ($stat =~ /$test/) {
7409 $val = $6 if ($skip_args ne "");
7410 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7411 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7412 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7413 ERROR("NON_OCTAL_PERMISSIONS",
7414 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7416 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7417 ERROR("EXPORTED_WORLD_WRITABLE",
7418 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7424 # check for uses of S_<PERMS> that could be octal for readability
7425 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7427 my $octal = perms_to_octal($oval);
7428 if (WARN("SYMBOLIC_PERMS",
7429 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7431 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7435 # validate content of MODULE_LICENSE against list from include/linux/module.h
7436 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7437 my $extracted_string = get_quoted_string($line, $rawline);
7438 my $valid_licenses = qr{
7441 GPL\ and\ additional\ rights|
7447 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7448 WARN("MODULE_LICENSE",
7449 "unknown module license " . $extracted_string . "\n" . $herecurr);
7451 if (!$file && $extracted_string eq '"GPL v2"') {
7452 if (WARN("MODULE_LICENSE",
7453 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7455 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7460 # check for sysctl duplicate constants
7461 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7462 WARN("DUPLICATED_SYSCTL_CONST",
7463 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7467 # If we have no input at all, then there is nothing to report on
7468 # so just keep quiet.
7469 if ($#rawlines == -1) {
7473 # In mailback mode only produce a report in the negative, for
7474 # things that appear to be patches.
7475 if ($mailback && ($clean == 1 || !$is_patch)) {
7479 # This is not a patch, and we are in 'no-patch' mode so
7481 if (!$chk_patch && !$is_patch) {
7485 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7486 ERROR("NOT_UNIFIED_DIFF",
7487 "Does not appear to be a unified-diff format patch\n");
7489 if ($is_patch && $has_commit_log && $chk_signoff) {
7490 if ($signoff == 0) {
7491 ERROR("MISSING_SIGN_OFF",
7492 "Missing Signed-off-by: line(s)\n");
7493 } elsif ($authorsignoff != 1) {
7494 # authorsignoff values:
7495 # 0 -> missing sign off
7496 # 1 -> sign off identical
7497 # 2 -> names and addresses match, comments mismatch
7498 # 3 -> addresses match, names different
7499 # 4 -> names match, addresses different
7500 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7502 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7504 if ($authorsignoff == 0) {
7505 ERROR("NO_AUTHOR_SIGN_OFF",
7506 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7507 } elsif ($authorsignoff == 2) {
7508 CHK("FROM_SIGN_OFF_MISMATCH",
7509 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7510 } elsif ($authorsignoff == 3) {
7511 WARN("FROM_SIGN_OFF_MISMATCH",
7512 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7513 } elsif ($authorsignoff == 4) {
7514 WARN("FROM_SIGN_OFF_MISMATCH",
7515 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7516 } elsif ($authorsignoff == 5) {
7517 WARN("FROM_SIGN_OFF_MISMATCH",
7518 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7523 print report_dump();
7524 if ($summary && !($clean == 1 && $quiet == 1)) {
7525 print "$filename " if ($summary_file);
7526 print "total: $cnt_error errors, $cnt_warn warnings, " .
7527 (($check)? "$cnt_chk checks, " : "") .
7528 "$cnt_lines lines checked\n";
7532 # If there were any defects found and not already fixing them
7533 if (!$clean and !$fix) {
7536 NOTE: For some of the reported defects, checkpatch may be able to
7537 mechanically convert to the typical style using --fix or --fix-inplace.
7540 # If there were whitespace errors which cleanpatch can fix
7541 # then suggest that.
7542 if ($rpt_cleaners) {
7546 NOTE: Whitespace errors detected.
7547 You may wish to use scripts/cleanpatch or scripts/cleanfile
7552 if ($clean == 0 && $fix &&
7553 ("@rawlines" ne "@fixed" ||
7554 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7555 my $newfile = $filename;
7556 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7560 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7562 open($f, '>', $newfile)
7563 or die "$P: Can't open $newfile for write\n";
7564 foreach my $fixed_line (@fixed) {
7567 if ($linecount > 3) {
7568 $fixed_line =~ s/^\+//;
7569 print $f $fixed_line . "\n";
7572 print $f $fixed_line . "\n";
7580 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7582 Do _NOT_ trust the results written to this file.
7583 Do _NOT_ submit these changes without inspecting them for correctness.
7585 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7586 No warranties, expressed or implied...
7594 print "$vname has no obvious style problems and is ready for submission.\n";
7596 print "$vname has style problems, please review.\n";