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};
601 our $logFunctions = qr{(?x:
602 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
603 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
605 WARN(?:_RATELIMIT|_ONCE|)|
608 seq_vprintf|seq_printf|seq_puts
611 # OpenOCD specific: Begin: list log functions
612 our $logFunctions = qr{(?x:
613 LOG_(?:TARGET_|)(?:DEBUG_IO|DEBUG|INFO|WARNING|ERROR|USER|USER_N|OUTPUT)
615 # OpenOCD specific: End
617 our $allocFunctions = qr{(?x:
619 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
622 (?:\w+)?alloc_skb(?:_ip_align)? |
623 # dev_alloc_skb/netdev_alloc_skb, et al
627 our $signature_tags = qr{(?xi:
639 our $tracing_logging_tags = qr{(?xi:
663 sub edit_distance_min {
665 my $len = scalar @arr;
666 if ((scalar @arr) < 1) {
667 # if underflow, return
671 for my $i (0 .. ($len-1)) {
672 if ($arr[$i] < $min) {
679 sub get_edit_distance {
680 my ($str1, $str2) = @_;
685 my $len1 = length($str1);
686 my $len2 = length($str2);
687 # two dimensional array storing minimum edit distance
689 for my $i (0 .. $len1) {
690 for my $j (0 .. $len2) {
692 $distance[$i][$j] = $j;
694 $distance[$i][$j] = $i;
695 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
696 $distance[$i][$j] = $distance[$i - 1][$j - 1];
698 my $dist1 = $distance[$i][$j - 1]; #insert distance
699 my $dist2 = $distance[$i - 1][$j]; # remove
700 my $dist3 = $distance[$i - 1][$j - 1]; #replace
701 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
705 return $distance[$len1][$len2];
708 sub find_standard_signature {
710 my @standard_signature_tags = (
711 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
712 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
714 foreach my $signature (@standard_signature_tags) {
715 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
721 our @typeListMisordered = (
722 qr{char\s+(?:un)?signed},
723 qr{int\s+(?:(?:un)?signed\s+)?short\s},
724 qr{int\s+short(?:\s+(?:un)?signed)},
725 qr{short\s+int(?:\s+(?:un)?signed)},
726 qr{(?:un)?signed\s+int\s+short},
727 qr{short\s+(?:un)?signed},
728 qr{long\s+int\s+(?:un)?signed},
729 qr{int\s+long\s+(?:un)?signed},
730 qr{long\s+(?:un)?signed\s+int},
731 qr{int\s+(?:un)?signed\s+long},
732 qr{int\s+(?:un)?signed},
733 qr{int\s+long\s+long\s+(?:un)?signed},
734 qr{long\s+long\s+int\s+(?:un)?signed},
735 qr{long\s+long\s+(?:un)?signed\s+int},
736 qr{long\s+long\s+(?:un)?signed},
737 qr{long\s+(?:un)?signed},
742 qr{(?:(?:un)?signed\s+)?char},
743 qr{(?:(?:un)?signed\s+)?short\s+int},
744 qr{(?:(?:un)?signed\s+)?short},
745 qr{(?:(?:un)?signed\s+)?int},
746 qr{(?:(?:un)?signed\s+)?long\s+int},
747 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
748 qr{(?:(?:un)?signed\s+)?long\s+long},
749 qr{(?:(?:un)?signed\s+)?long},
758 qr{${Ident}_handler},
759 qr{${Ident}_handler_fn},
763 our $C90_int_types = qr{(?x:
764 long\s+long\s+int\s+(?:un)?signed|
765 long\s+long\s+(?:un)?signed\s+int|
766 long\s+long\s+(?:un)?signed|
767 (?:(?:un)?signed\s+)?long\s+long\s+int|
768 (?:(?:un)?signed\s+)?long\s+long|
769 int\s+long\s+long\s+(?:un)?signed|
770 int\s+(?:(?:un)?signed\s+)?long\s+long|
772 long\s+int\s+(?:un)?signed|
773 long\s+(?:un)?signed\s+int|
774 long\s+(?:un)?signed|
775 (?:(?:un)?signed\s+)?long\s+int|
776 (?:(?:un)?signed\s+)?long|
777 int\s+long\s+(?:un)?signed|
778 int\s+(?:(?:un)?signed\s+)?long|
781 (?:(?:un)?signed\s+)?int
784 our @typeListFile = ();
785 our @typeListWithAttr = (
787 qr{struct\s+$InitAttribute\s+$Ident},
788 qr{union\s+$InitAttribute\s+$Ident},
791 our @modifierList = (
794 our @modifierListFile = ();
796 our @mode_permission_funcs = (
798 ["module_param_(?:array|named|string)", 4],
799 ["module_param_array_named", 5],
800 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
801 ["proc_create(?:_data|)", 2],
802 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
803 ["IIO_DEV_ATTR_[A-Z_]+", 1],
804 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
805 ["SENSOR_TEMPLATE(?:_2|)", 3],
809 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
811 #Create a search pattern for all these functions to speed up a loop below
812 our $mode_perms_search = "";
813 foreach my $entry (@mode_permission_funcs) {
814 $mode_perms_search .= '|' if ($mode_perms_search ne "");
815 $mode_perms_search .= $entry->[0];
817 $mode_perms_search = "(?:${mode_perms_search})";
819 our %deprecated_apis = (
820 "synchronize_rcu_bh" => "synchronize_rcu",
821 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
822 "call_rcu_bh" => "call_rcu",
823 "rcu_barrier_bh" => "rcu_barrier",
824 "synchronize_sched" => "synchronize_rcu",
825 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
826 "call_rcu_sched" => "call_rcu",
827 "rcu_barrier_sched" => "rcu_barrier",
828 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
829 "cond_synchronize_sched" => "cond_synchronize_rcu",
832 #Create a search pattern for all these strings to speed up a loop below
833 our $deprecated_apis_search = "";
834 foreach my $entry (keys %deprecated_apis) {
835 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
836 $deprecated_apis_search .= $entry;
838 $deprecated_apis_search = "(?:${deprecated_apis_search})";
840 our $mode_perms_world_writable = qr{
848 our %mode_permission_string_types = (
867 #Create a search pattern for all these strings to speed up a loop below
868 our $mode_perms_string_search = "";
869 foreach my $entry (keys %mode_permission_string_types) {
870 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
871 $mode_perms_string_search .= $entry;
873 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
874 our $multi_mode_perms_string_search = qr{
875 ${single_mode_perms_string_search}
876 (?:\s*\|\s*${single_mode_perms_string_search})*
882 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
889 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
890 $curpos = pos($string);
893 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
895 $to |= $mode_permission_string_types{$match};
896 $val .= '\s*\|\s*' if ($val ne "");
900 $oval =~ s/^\s*\|\s*//;
901 $oval =~ s/\s*\|\s*$//;
902 return sprintf("%04o", $to);
905 our $allowed_asm_includes = qr{(?x:
911 # memory.h: ARM has a custom one
913 # Load common spelling mistakes and build regular expression list.
917 if (open(my $spelling, '<', $spelling_file)) {
918 while (<$spelling>) {
921 $line =~ s/\s*\n?$//g;
924 next if ($line =~ m/^\s*#/);
925 next if ($line =~ m/^\s*$/);
927 my ($suspect, $fix) = split(/\|\|/, $line);
929 $spelling_fix{$suspect} = $fix;
933 warn "No typos will be found - file '$spelling_file': $!\n";
937 if (open(my $spelling, '<', $codespellfile)) {
938 while (<$spelling>) {
941 $line =~ s/\s*\n?$//g;
944 next if ($line =~ m/^\s*#/);
945 next if ($line =~ m/^\s*$/);
946 next if ($line =~ m/, disabled/i);
950 my ($suspect, $fix) = split(/->/, $line);
952 $spelling_fix{$suspect} = $fix;
956 warn "No codespell typos will be found - file '$codespellfile': $!\n";
960 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
963 my ($wordsRef, $file) = @_;
965 if (open(my $words, '<', $file)) {
969 $line =~ s/\s*\n?$//g;
972 next if ($line =~ m/^\s*#/);
973 next if ($line =~ m/^\s*$/);
975 print("$file: '$line' invalid - ignored\n");
979 $$wordsRef .= '|' if (defined $$wordsRef);
990 if (show_type("CONST_STRUCT")) {
991 read_words(\$const_structs, $conststructsfile)
992 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
995 if (defined($typedefsfile)) {
996 my $typeOtherTypedefs;
997 read_words(\$typeOtherTypedefs, $typedefsfile)
998 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
999 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1003 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1004 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1005 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
1006 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1007 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1009 (?:$typeTypedefs\b)|
1013 (?:$Modifier\s+|const\s+)*
1015 (?:typeof|__typeof__)\s*\([^\)]*\)|
1016 (?:$typeTypedefs\b)|
1019 (?:\s+$Modifier|\s+const)*
1021 $NonptrTypeMisordered = qr{
1022 (?:$Modifier\s+|const\s+)*
1026 (?:\s+$Modifier|\s+const)*
1028 $NonptrTypeWithAttr = qr{
1029 (?:$Modifier\s+|const\s+)*
1031 (?:typeof|__typeof__)\s*\([^\)]*\)|
1032 (?:$typeTypedefs\b)|
1033 (?:${allWithAttr}\b)
1035 (?:\s+$Modifier|\s+const)*
1039 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1040 (?:\s+$Inline|\s+$Modifier)*
1042 $TypeMisordered = qr{
1043 $NonptrTypeMisordered
1044 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1045 (?:\s+$Inline|\s+$Modifier)*
1047 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1048 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1052 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1054 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1055 # requires at least perl version v5.10.0
1056 # Any use must be runtime checked with $^V
1058 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1059 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1060 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1062 our $declaration_macros = qr{(?x:
1063 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1064 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1065 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1066 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1069 our %allow_repeated_words = (
1076 sub deparenthesize {
1078 return "" if (!defined($string));
1080 while ($string =~ /^\s*\(.*\)\s*$/) {
1081 $string =~ s@^\s*\(\s*@@;
1082 $string =~ s@\s*\)\s*$@@;
1085 $string =~ s@\s+@ @g;
1090 sub seed_camelcase_file {
1093 return if (!(-f $file));
1097 open(my $include_file, '<', "$file")
1098 or warn "$P: Can't read '$file' $!\n";
1099 my $text = <$include_file>;
1100 close($include_file);
1102 my @lines = split('\n', $text);
1104 foreach my $line (@lines) {
1105 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1106 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1108 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1110 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1116 our %maintained_status = ();
1118 sub is_maintained_obsolete {
1119 my ($filename) = @_;
1121 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1123 if (!exists($maintained_status{$filename})) {
1124 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1127 return $maintained_status{$filename} =~ /obsolete/i;
1130 sub is_SPDX_License_valid {
1133 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1135 my $root_path = abs_path($root);
1136 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1137 return 0 if ($status ne "");
1141 my $camelcase_seeded = 0;
1142 sub seed_camelcase_includes {
1143 return if ($camelcase_seeded);
1146 my $camelcase_cache = "";
1147 my @include_files = ();
1149 $camelcase_seeded = 1;
1151 if (-e "$gitroot") {
1152 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1153 chomp $git_last_include_commit;
1154 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1156 my $last_mod_date = 0;
1157 $files = `find $root/include -name "*.h"`;
1158 @include_files = split('\n', $files);
1159 foreach my $file (@include_files) {
1160 my $date = POSIX::strftime("%Y%m%d%H%M",
1161 localtime((stat $file)[9]));
1162 $last_mod_date = $date if ($last_mod_date < $date);
1164 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1167 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1168 open(my $camelcase_file, '<', "$camelcase_cache")
1169 or warn "$P: Can't read '$camelcase_cache' $!\n";
1170 while (<$camelcase_file>) {
1174 close($camelcase_file);
1179 if (-e "$gitroot") {
1180 $files = `${git_command} ls-files "include/*.h"`;
1181 @include_files = split('\n', $files);
1184 foreach my $file (@include_files) {
1185 seed_camelcase_file($file);
1188 if ($camelcase_cache ne "") {
1189 unlink glob ".checkpatch-camelcase.*";
1190 open(my $camelcase_file, '>', "$camelcase_cache")
1191 or warn "$P: Can't write '$camelcase_cache' $!\n";
1192 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1193 print $camelcase_file ("$_\n");
1195 close($camelcase_file);
1199 sub git_is_single_file {
1200 my ($filename) = @_;
1202 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1204 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1205 my $count = $output =~ tr/\n//;
1206 return $count eq 1 && $output =~ m{^${filename}$};
1209 sub git_commit_info {
1210 my ($commit, $id, $desc) = @_;
1212 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1214 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1215 $output =~ s/^\s*//gm;
1216 my @lines = split("\n", $output);
1218 return ($id, $desc) if ($#lines < 0);
1220 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1221 # Maybe one day convert this block of bash into something that returns
1222 # all matching commit ids, but it's very slow...
1224 # echo "checking commits $1..."
1225 # git rev-list --remotes | grep -i "^$1" |
1226 # while read line ; do
1227 # git log --format='%H %s' -1 $line |
1228 # echo "commit $(cut -c 1-12,41-)"
1230 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1231 $lines[0] =~ /^fatal: bad object $commit/) {
1234 $id = substr($lines[0], 0, 12);
1235 $desc = substr($lines[0], 41);
1238 return ($id, $desc);
1241 $chk_signoff = 0 if ($file);
1246 my @fixed_inserted = ();
1247 my @fixed_deleted = ();
1250 # If input is git commits, extract all commits from the commit expressions.
1251 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1252 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1256 foreach my $commit_expr (@ARGV) {
1258 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1259 $git_range = "-$2 $1";
1260 } elsif ($commit_expr =~ m/\.\./) {
1261 $git_range = "$commit_expr";
1263 $git_range = "-1 $commit_expr";
1265 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1266 foreach my $line (split(/\n/, $lines)) {
1267 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1268 next if (!defined($1) || !defined($2));
1271 unshift(@commits, $sha1);
1272 $git_commits{$sha1} = $subject;
1275 die "$P: no git commits after extraction!\n" if (@commits == 0);
1280 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1281 for my $filename (@ARGV) {
1283 my $is_git_file = git_is_single_file($filename);
1284 my $oldfile = $file;
1285 $file = 1 if ($is_git_file);
1287 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1288 die "$P: $filename: git format-patch failed - $!\n";
1290 open($FILE, '-|', "diff -u /dev/null $filename") ||
1291 die "$P: $filename: diff failed - $!\n";
1292 } elsif ($filename eq '-') {
1293 open($FILE, '<&STDIN');
1295 open($FILE, '<', "$filename") ||
1296 die "$P: $filename: open failed - $!\n";
1298 if ($filename eq '-') {
1299 $vname = 'Your patch';
1301 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1307 push(@rawlines, $_);
1308 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1312 if ($#ARGV > 0 && $quiet == 0) {
1313 print '-' x length($vname) . "\n";
1315 print '-' x length($vname) . "\n";
1318 if (!process($filename)) {
1324 @fixed_inserted = ();
1325 @fixed_deleted = ();
1327 @modifierListFile = ();
1330 $file = $oldfile if ($is_git_file);
1334 hash_show_words(\%use_type, "Used");
1335 hash_show_words(\%ignore_type, "Ignored");
1337 if (!$perl_version_ok) {
1340 NOTE: perl $^V is not modern enough to detect all possible issues.
1341 An upgrade to at least perl $minimum_perl_version is suggested.
1347 NOTE: If any of the errors are false positives, please report
1348 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1355 sub top_of_kernel_tree {
1359 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1360 "README", "Documentation", "arch", "include", "drivers",
1361 "fs", "init", "ipc", "kernel", "lib", "scripts",
1364 foreach my $check (@tree_check) {
1365 if (! -e $root . '/' . $check) {
1373 my ($formatted_email) = @_;
1377 my $name_comment = "";
1381 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1384 $comment = $3 if defined $3;
1385 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1387 $comment = $2 if defined $2;
1388 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1390 $comment = $2 if defined $2;
1391 $formatted_email =~ s/\Q$address\E.*$//;
1392 $name = $formatted_email;
1393 $name = trim($name);
1394 $name =~ s/^\"|\"$//g;
1395 # If there's a name left after stripping spaces and
1396 # leading quotes, and the address doesn't have both
1397 # leading and trailing angle brackets, the address
1399 # "joe smith joe@smith.com" bad
1400 # "joe smith <joe@smith.com" bad
1401 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1408 # Extract comments from names excluding quoted parts
1409 # "John D. (Doe)" - Do not extract
1410 if ($name =~ s/\"(.+)\"//) {
1413 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1414 $name_comment .= trim($1);
1416 $name =~ s/^[ \"]+|[ \"]+$//g;
1417 $name = trim("$quoted $name");
1419 $address = trim($address);
1420 $address =~ s/^\<|\>$//g;
1421 $comment = trim($comment);
1423 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1424 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1425 $name = "\"$name\"";
1428 return ($name, $name_comment, $address, $comment);
1432 my ($name, $name_comment, $address, $comment) = @_;
1434 my $formatted_email;
1436 $name =~ s/^[ \"]+|[ \"]+$//g;
1437 $address = trim($address);
1438 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1440 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1441 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1442 $name = "\"$name\"";
1445 $name_comment = trim($name_comment);
1446 $name_comment = " $name_comment" if ($name_comment ne "");
1447 $comment = trim($comment);
1448 $comment = " $comment" if ($comment ne "");
1450 if ("$name" eq "") {
1451 $formatted_email = "$address";
1453 $formatted_email = "$name$name_comment <$address>";
1455 $formatted_email .= "$comment";
1456 return $formatted_email;
1459 sub reformat_email {
1462 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1463 return format_email($email_name, $name_comment, $email_address, $comment);
1466 sub same_email_addresses {
1467 my ($email1, $email2) = @_;
1469 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1470 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1472 return $email1_name eq $email2_name &&
1473 $email1_address eq $email2_address &&
1474 $name1_comment eq $name2_comment &&
1475 $comment1 eq $comment2;
1481 foreach my $path (split(/:/, $ENV{PATH})) {
1482 if (-e "$path/$bin") {
1483 return "$path/$bin";
1493 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1494 if (-e "$path/$conf") {
1495 return "$path/$conf";
1507 for my $c (split(//, $str)) {
1511 for (; ($n % $tabsize) != 0; $n++) {
1523 (my $res = shift) =~ tr/\t/ /c;
1530 # Drop the diff line leader and expand tabs
1532 $line = expand_tabs($line);
1534 # Pick the indent from the front of the line.
1535 my ($white) = ($line =~ /^(\s*)/);
1537 return (length($line), length($white));
1540 my $sanitise_quote = '';
1542 sub sanitise_line_reset {
1543 my ($in_comment) = @_;
1546 $sanitise_quote = '*/';
1548 $sanitise_quote = '';
1561 # Always copy over the diff marker.
1562 $res = substr($line, 0, 1);
1564 for ($off = 1; $off < length($line); $off++) {
1565 $c = substr($line, $off, 1);
1567 # Comments we are whacking completely including the begin
1568 # and end, all to $;.
1569 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1570 $sanitise_quote = '*/';
1572 substr($res, $off, 2, "$;$;");
1576 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1577 $sanitise_quote = '';
1578 substr($res, $off, 2, "$;$;");
1582 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1583 $sanitise_quote = '//';
1585 substr($res, $off, 2, $sanitise_quote);
1590 # A \ in a string means ignore the next character.
1591 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1593 substr($res, $off, 2, 'XX');
1598 if ($c eq "'" || $c eq '"') {
1599 if ($sanitise_quote eq '') {
1600 $sanitise_quote = $c;
1602 substr($res, $off, 1, $c);
1604 } elsif ($sanitise_quote eq $c) {
1605 $sanitise_quote = '';
1609 #print "c<$c> SQ<$sanitise_quote>\n";
1610 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1611 substr($res, $off, 1, $;);
1612 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1613 substr($res, $off, 1, $;);
1614 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1615 substr($res, $off, 1, 'X');
1617 substr($res, $off, 1, $c);
1621 if ($sanitise_quote eq '//') {
1622 $sanitise_quote = '';
1625 # The pathname on a #include may be surrounded by '<' and '>'.
1626 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1627 my $clean = 'X' x length($1);
1628 $res =~ s@\<.*\>@<$clean>@;
1630 # The whole of a #error is a string.
1631 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1632 my $clean = 'X' x length($1);
1633 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1636 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1638 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1644 sub get_quoted_string {
1645 my ($line, $rawline) = @_;
1647 return "" if (!defined($line) || !defined($rawline));
1648 return "" if ($line !~ m/($String)/g);
1649 return substr($rawline, $-[0], $+[0] - $-[0]);
1652 sub ctx_statement_block {
1653 my ($linenr, $remain, $off) = @_;
1654 my $line = $linenr - 1;
1657 my $coff = $off - 1;
1671 @stack = (['', 0]) if ($#stack == -1);
1673 #warn "CSB: blk<$blk> remain<$remain>\n";
1674 # If we are about to drop off the end, pull in more
1677 for (; $remain > 0; $line++) {
1678 last if (!defined $lines[$line]);
1679 next if ($lines[$line] =~ /^-/);
1682 $blk .= $lines[$line] . "\n";
1683 $len = length($blk);
1687 # Bail if there is no further context.
1688 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1692 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1698 $c = substr($blk, $off, 1);
1699 $remainder = substr($blk, $off);
1701 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1703 # Handle nested #if/#else.
1704 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1705 push(@stack, [ $type, $level ]);
1706 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1707 ($type, $level) = @{$stack[$#stack - 1]};
1708 } elsif ($remainder =~ /^#\s*endif\b/) {
1709 ($type, $level) = @{pop(@stack)};
1712 # Statement ends at the ';' or a close '}' at the
1714 if ($level == 0 && $c eq ';') {
1718 # An else is really a conditional as long as its not else if
1719 if ($level == 0 && $coff_set == 0 &&
1720 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1721 $remainder =~ /^(else)(?:\s|{)/ &&
1722 $remainder !~ /^else\s+if\b/) {
1723 $coff = $off + length($1) - 1;
1725 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1726 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1729 if (($type eq '' || $type eq '(') && $c eq '(') {
1733 if ($type eq '(' && $c eq ')') {
1735 $type = ($level != 0)? '(' : '';
1737 if ($level == 0 && $coff < $soff) {
1740 #warn "CSB: mark coff<$coff>\n";
1743 if (($type eq '' || $type eq '{') && $c eq '{') {
1747 if ($type eq '{' && $c eq '}') {
1749 $type = ($level != 0)? '{' : '';
1752 if (substr($blk, $off + 1, 1) eq ';') {
1758 # Preprocessor commands end at the newline unless escaped.
1759 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1767 # We are truly at the end, so shuffle to the next line.
1774 my $statement = substr($blk, $soff, $off - $soff + 1);
1775 my $condition = substr($blk, $soff, $coff - $soff + 1);
1777 #warn "STATEMENT<$statement>\n";
1778 #warn "CONDITION<$condition>\n";
1780 #print "coff<$coff> soff<$off> loff<$loff>\n";
1782 return ($statement, $condition,
1783 $line, $remain + 1, $off - $loff + 1, $level);
1786 sub statement_lines {
1789 # Strip the diff line prefixes and rip blank lines at start and end.
1790 $stmt =~ s/(^|\n)./$1/g;
1794 my @stmt_lines = ($stmt =~ /\n/g);
1796 return $#stmt_lines + 2;
1799 sub statement_rawlines {
1802 my @stmt_lines = ($stmt =~ /\n/g);
1804 return $#stmt_lines + 2;
1807 sub statement_block_size {
1810 $stmt =~ s/(^|\n)./$1/g;
1816 my @stmt_lines = ($stmt =~ /\n/g);
1817 my @stmt_statements = ($stmt =~ /;/g);
1819 my $stmt_lines = $#stmt_lines + 2;
1820 my $stmt_statements = $#stmt_statements + 1;
1822 if ($stmt_lines > $stmt_statements) {
1825 return $stmt_statements;
1829 sub ctx_statement_full {
1830 my ($linenr, $remain, $off) = @_;
1831 my ($statement, $condition, $level);
1835 # Grab the first conditional/block pair.
1836 ($statement, $condition, $linenr, $remain, $off, $level) =
1837 ctx_statement_block($linenr, $remain, $off);
1838 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1839 push(@chunks, [ $condition, $statement ]);
1840 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1841 return ($level, $linenr, @chunks);
1844 # Pull in the following conditional/block pairs and see if they
1845 # could continue the statement.
1847 ($statement, $condition, $linenr, $remain, $off, $level) =
1848 ctx_statement_block($linenr, $remain, $off);
1849 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1850 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1852 push(@chunks, [ $condition, $statement ]);
1855 return ($level, $linenr, @chunks);
1859 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1861 my $start = $linenr - 1;
1868 my @stack = ($level);
1869 for ($line = $start; $remain > 0; $line++) {
1870 next if ($rawlines[$line] =~ /^-/);
1873 $blk .= $rawlines[$line];
1875 # Handle nested #if/#else.
1876 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1877 push(@stack, $level);
1878 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1879 $level = $stack[$#stack - 1];
1880 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1881 $level = pop(@stack);
1884 foreach my $c (split(//, $lines[$line])) {
1885 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1891 if ($c eq $close && $level > 0) {
1893 last if ($level == 0);
1894 } elsif ($c eq $open) {
1899 if (!$outer || $level <= 1) {
1900 push(@res, $rawlines[$line]);
1903 last if ($level == 0);
1906 return ($level, @res);
1908 sub ctx_block_outer {
1909 my ($linenr, $remain) = @_;
1911 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1915 my ($linenr, $remain) = @_;
1917 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1921 my ($linenr, $remain, $off) = @_;
1923 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1926 sub ctx_block_level {
1927 my ($linenr, $remain) = @_;
1929 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1931 sub ctx_statement_level {
1932 my ($linenr, $remain, $off) = @_;
1934 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1937 sub ctx_locate_comment {
1938 my ($first_line, $end_line) = @_;
1940 # If c99 comment on the current line, or the line before or after
1941 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1942 return $current_comment if (defined $current_comment);
1943 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1944 return $current_comment if (defined $current_comment);
1945 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1946 return $current_comment if (defined $current_comment);
1948 # Catch a comment on the end of the line itself.
1949 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1950 return $current_comment if (defined $current_comment);
1952 # Look through the context and try and figure out if there is a
1955 $current_comment = '';
1956 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1957 my $line = $rawlines[$linenr - 1];
1959 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1962 if ($line =~ m@/\*@) {
1965 if (!$in_comment && $current_comment ne '') {
1966 $current_comment = '';
1968 $current_comment .= $line . "\n" if ($in_comment);
1969 if ($line =~ m@\*/@) {
1974 chomp($current_comment);
1975 return($current_comment);
1977 sub ctx_has_comment {
1978 my ($first_line, $end_line) = @_;
1979 my $cmt = ctx_locate_comment($first_line, $end_line);
1981 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1982 ##print "CMMT: $cmt\n";
1984 return ($cmt ne '');
1988 my ($linenr, $cnt) = @_;
1990 my $offset = $linenr - 1;
1995 $line = $rawlines[$offset++];
1996 next if (defined($line) && $line =~ /^-/);
2004 my ($linenr, $lc) = @_;
2006 my $stat_real = raw_line($linenr, 0);
2007 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2008 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2015 my ($linenr, $cnt, $here) = @_;
2017 my $herectx = $here . "\n";
2018 for (my $n = 0; $n < $cnt; $n++) {
2019 $herectx .= raw_line($linenr, $n) . "\n";
2030 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2033 $coded = sprintf("^%c", unpack('C', $2) + 64);
2042 my $av_preprocessor = 0;
2047 sub annotate_reset {
2048 $av_preprocessor = 0;
2050 @av_paren_type = ('E');
2051 $av_pend_colon = 'O';
2054 sub annotate_values {
2055 my ($stream, $type) = @_;
2058 my $var = '_' x length($stream);
2061 print "$stream\n" if ($dbg_values > 1);
2063 while (length($cur)) {
2064 @av_paren_type = ('E') if ($#av_paren_type < 0);
2065 print " <" . join('', @av_paren_type) .
2066 "> <$type> <$av_pending>" if ($dbg_values > 1);
2067 if ($cur =~ /^(\s+)/o) {
2068 print "WS($1)\n" if ($dbg_values > 1);
2069 if ($1 =~ /\n/ && $av_preprocessor) {
2070 $type = pop(@av_paren_type);
2071 $av_preprocessor = 0;
2074 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2075 print "CAST($1)\n" if ($dbg_values > 1);
2076 push(@av_paren_type, $type);
2079 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2080 print "DECLARE($1)\n" if ($dbg_values > 1);
2083 } elsif ($cur =~ /^($Modifier)\s*/) {
2084 print "MODIFIER($1)\n" if ($dbg_values > 1);
2087 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2088 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2089 $av_preprocessor = 1;
2090 push(@av_paren_type, $type);
2096 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2097 print "UNDEF($1)\n" if ($dbg_values > 1);
2098 $av_preprocessor = 1;
2099 push(@av_paren_type, $type);
2101 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2102 print "PRE_START($1)\n" if ($dbg_values > 1);
2103 $av_preprocessor = 1;
2105 push(@av_paren_type, $type);
2106 push(@av_paren_type, $type);
2109 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2110 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2111 $av_preprocessor = 1;
2113 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2117 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2118 print "PRE_END($1)\n" if ($dbg_values > 1);
2120 $av_preprocessor = 1;
2122 # Assume all arms of the conditional end as this
2123 # one does, and continue as if the #endif was not here.
2124 pop(@av_paren_type);
2125 push(@av_paren_type, $type);
2128 } elsif ($cur =~ /^(\\\n)/o) {
2129 print "PRECONT($1)\n" if ($dbg_values > 1);
2131 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2132 print "ATTR($1)\n" if ($dbg_values > 1);
2133 $av_pending = $type;
2136 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2137 print "SIZEOF($1)\n" if ($dbg_values > 1);
2143 } elsif ($cur =~ /^(if|while|for)\b/o) {
2144 print "COND($1)\n" if ($dbg_values > 1);
2148 } elsif ($cur =~/^(case)/o) {
2149 print "CASE($1)\n" if ($dbg_values > 1);
2150 $av_pend_colon = 'C';
2153 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2154 print "KEYWORD($1)\n" if ($dbg_values > 1);
2157 } elsif ($cur =~ /^(\()/o) {
2158 print "PAREN('$1')\n" if ($dbg_values > 1);
2159 push(@av_paren_type, $av_pending);
2163 } elsif ($cur =~ /^(\))/o) {
2164 my $new_type = pop(@av_paren_type);
2165 if ($new_type ne '_') {
2167 print "PAREN('$1') -> $type\n"
2168 if ($dbg_values > 1);
2170 print "PAREN('$1')\n" if ($dbg_values > 1);
2173 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2174 print "FUNC($1)\n" if ($dbg_values > 1);
2178 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2179 if (defined $2 && $type eq 'C' || $type eq 'T') {
2180 $av_pend_colon = 'B';
2181 } elsif ($type eq 'E') {
2182 $av_pend_colon = 'L';
2184 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2187 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2188 print "IDENT($1)\n" if ($dbg_values > 1);
2191 } elsif ($cur =~ /^($Assignment)/o) {
2192 print "ASSIGN($1)\n" if ($dbg_values > 1);
2195 } elsif ($cur =~/^(;|{|})/) {
2196 print "END($1)\n" if ($dbg_values > 1);
2198 $av_pend_colon = 'O';
2200 } elsif ($cur =~/^(,)/) {
2201 print "COMMA($1)\n" if ($dbg_values > 1);
2204 } elsif ($cur =~ /^(\?)/o) {
2205 print "QUESTION($1)\n" if ($dbg_values > 1);
2208 } elsif ($cur =~ /^(:)/o) {
2209 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2211 substr($var, length($res), 1, $av_pend_colon);
2212 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2217 $av_pend_colon = 'O';
2219 } elsif ($cur =~ /^(\[)/o) {
2220 print "CLOSE($1)\n" if ($dbg_values > 1);
2223 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2226 print "OPV($1)\n" if ($dbg_values > 1);
2233 substr($var, length($res), 1, $variant);
2236 } elsif ($cur =~ /^($Operators)/o) {
2237 print "OP($1)\n" if ($dbg_values > 1);
2238 if ($1 ne '++' && $1 ne '--') {
2242 } elsif ($cur =~ /(^.)/o) {
2243 print "C($1)\n" if ($dbg_values > 1);
2246 $cur = substr($cur, length($1));
2247 $res .= $type x length($1);
2251 return ($res, $var);
2255 my ($possible, $line) = @_;
2256 my $notPermitted = qr{(?:
2273 ^(?:typedef|struct|enum)\b
2275 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2276 if ($possible !~ $notPermitted) {
2277 # Check for modifiers.
2278 $possible =~ s/\s*$Storage\s*//g;
2279 $possible =~ s/\s*$Sparse\s*//g;
2280 if ($possible =~ /^\s*$/) {
2282 } elsif ($possible =~ /\s/) {
2283 $possible =~ s/\s*$Type\s*//g;
2284 for my $modifier (split(' ', $possible)) {
2285 if ($modifier !~ $notPermitted) {
2286 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2287 push(@modifierListFile, $modifier);
2292 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2293 push(@typeListFile, $possible);
2297 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2306 $type =~ tr/[a-z]/[A-Z]/;
2308 return defined $use_type{$type} if (scalar keys %use_type > 0);
2310 return !defined $ignore_type{$type};
2314 my ($level, $type, $msg) = @_;
2316 if (!show_type($type) ||
2317 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2322 if ($level eq 'ERROR') {
2324 } elsif ($level eq 'WARNING') {
2330 $output .= $prefix . $level . ':';
2332 $output .= BLUE if ($color);
2333 $output .= "$type:";
2335 $output .= RESET if ($color);
2336 $output .= ' ' . $msg . "\n";
2339 my @lines = split("\n", $output, -1);
2340 splice(@lines, 1, 1);
2341 $output = join("\n", @lines);
2345 $output = (split('\n', $output))[0] . "\n";
2348 if ($verbose && exists($verbose_messages{$type}) &&
2349 !exists($verbose_emitted{$type})) {
2350 $output .= $verbose_messages{$type} . "\n\n";
2351 $verbose_emitted{$type} = 1;
2354 push(our @report, $output);
2363 sub fixup_current_range {
2364 my ($lineRef, $offset, $length) = @_;
2366 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2369 my $no = $o + $offset;
2370 my $nl = $l + $length;
2371 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2375 sub fix_inserted_deleted_lines {
2376 my ($linesRef, $insertedRef, $deletedRef) = @_;
2378 my $range_last_linenr = 0;
2379 my $delta_offset = 0;
2384 my $next_insert = 0;
2385 my $next_delete = 0;
2389 my $inserted = @{$insertedRef}[$next_insert++];
2390 my $deleted = @{$deletedRef}[$next_delete++];
2392 foreach my $old_line (@{$linesRef}) {
2394 my $line = $old_line; #don't modify the array
2395 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2397 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2398 $range_last_linenr = $new_linenr;
2399 fixup_current_range(\$line, $delta_offset, 0);
2402 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2403 $deleted = @{$deletedRef}[$next_delete++];
2405 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2408 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2409 push(@lines, ${$inserted}{'LINE'});
2410 $inserted = @{$insertedRef}[$next_insert++];
2412 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2416 push(@lines, $line);
2426 sub fix_insert_line {
2427 my ($linenr, $line) = @_;
2433 push(@fixed_inserted, $inserted);
2436 sub fix_delete_line {
2437 my ($linenr, $line) = @_;
2444 push(@fixed_deleted, $deleted);
2448 my ($type, $msg) = @_;
2450 if (report("ERROR", $type, $msg)) {
2458 my ($type, $msg) = @_;
2460 if (report("WARNING", $type, $msg)) {
2468 my ($type, $msg) = @_;
2470 if ($check && report("CHECK", $type, $msg)) {
2478 sub check_absolute_file {
2479 my ($absolute, $herecurr) = @_;
2480 my $file = $absolute;
2482 ##print "absolute<$absolute>\n";
2484 # See if any suffix of this path is a path within the tree.
2485 while ($file =~ s@^[^/]*/@@) {
2486 if (-f "$root/$file") {
2487 ##print "file<$file>\n";
2495 # It is, so see if the prefix is acceptable.
2496 my $prefix = $absolute;
2497 substr($prefix, -length($file)) = '';
2499 ##print "prefix<$prefix>\n";
2500 if ($prefix ne ".../") {
2501 WARN("USE_RELATIVE_PATH",
2502 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2509 $string =~ s/^\s+|\s+$//g;
2517 $string =~ s/^\s+//;
2525 $string =~ s/\s+$//;
2530 sub string_find_replace {
2531 my ($string, $find, $replace) = @_;
2533 $string =~ s/$find/$replace/g;
2541 my $source_indent = $tabsize;
2542 my $max_spaces_before_tab = $source_indent - 1;
2543 my $spaces_to_tab = " " x $source_indent;
2545 #convert leading spaces to tabs
2546 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2547 #Remove spaces before a tab
2548 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2553 sub pos_last_openparen {
2558 my $opens = $line =~ tr/\(/\(/;
2559 my $closes = $line =~ tr/\)/\)/;
2561 my $last_openparen = 0;
2563 if (($opens == 0) || ($closes >= $opens)) {
2567 my $len = length($line);
2569 for ($pos = 0; $pos < $len; $pos++) {
2570 my $string = substr($line, $pos);
2571 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2572 $pos += length($1) - 1;
2573 } elsif (substr($line, $pos, 1) eq '(') {
2574 $last_openparen = $pos;
2575 } elsif (index($string, '(') == -1) {
2580 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2583 sub get_raw_comment {
2584 my ($line, $rawline) = @_;
2587 for my $i (0 .. (length($line) - 1)) {
2588 if (substr($line, $i, 1) eq "$;") {
2589 $comment .= substr($rawline, $i, 1);
2596 sub exclude_global_initialisers {
2597 my ($realfile) = @_;
2599 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2600 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2601 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2602 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2606 my $filename = shift;
2612 my $stashrawline="";
2622 my $authorsignoff = 0;
2623 my $author_sob = '';
2625 my $is_binding_patch = -1;
2626 my $in_header_lines = $file ? 0 : 1;
2627 my $in_commit_log = 0; #Scanning lines before patch
2628 my $has_patch_separator = 0; #Found a --- line
2629 my $has_commit_log = 0; #Encountered lines before patch
2630 my $commit_log_lines = 0; #Number of commit log lines
2631 my $commit_log_possible_stack_dump = 0;
2632 my $commit_log_long_line = 0;
2633 my $commit_log_has_diff = 0;
2634 my $reported_maintainer_file = 0;
2635 my $non_utf8_charset = 0;
2637 my $last_git_commit_id_linenr = -1;
2639 my $last_blank_line = 0;
2640 my $last_coalesced_string_linenr = -1;
2648 # Trace the real file/line as we go.
2653 my $context_function; #undef'd unless there's a known function
2655 my $comment_edge = 0;
2659 my $prev_values = 'E';
2662 my %suppress_ifbraces;
2663 my %suppress_whiletrailers;
2664 my %suppress_export;
2665 my $suppress_statement = 0;
2667 my %signatures = ();
2669 # Pre-scan the patch sanitizing the lines.
2670 # Pre-scan the patch looking for any __setup documentation.
2672 my @setup_docs = ();
2675 my $camelcase_file_seeded = 0;
2677 my $checklicenseline = 1;
2679 sanitise_line_reset();
2681 foreach my $rawline (@rawlines) {
2685 push(@fixed, $rawline) if ($fix);
2687 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2689 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2694 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2703 # Guestimate if this is a continuing comment. Run
2704 # the context looking for a comment "edge". If this
2705 # edge is a close comment then we must be in a comment
2709 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2710 next if (defined $rawlines[$ln - 1] &&
2711 $rawlines[$ln - 1] =~ /^-/);
2713 #print "RAW<$rawlines[$ln - 1]>\n";
2714 last if (!defined $rawlines[$ln - 1]);
2715 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2716 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2721 if (defined $edge && $edge eq '*/') {
2725 # Guestimate if this is a continuing comment. If this
2726 # is the start of a diff block and this line starts
2727 # ' *' then it is very likely a comment.
2728 if (!defined $edge &&
2729 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2734 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2735 sanitise_line_reset($in_comment);
2737 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2738 # Standardise the strings and chars within the input to
2739 # simplify matching -- only bother with positive lines.
2740 $line = sanitise_line($rawline);
2742 push(@lines, $line);
2745 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2750 #print "==>$rawline\n";
2751 #print "-->$line\n";
2753 if ($setup_docs && $line =~ /^\+/) {
2754 push(@setup_docs, $line);
2763 foreach my $line (@lines) {
2766 my $sline = $line; #copy of $line
2767 $sline =~ s/$;/ /g; #with comments as spaces
2769 my $rawline = $rawlines[$linenr - 1];
2770 my $raw_comment = get_raw_comment($line, $rawline);
2772 # check if it's a mode change, rename or start of a patch
2773 if (!$in_commit_log &&
2774 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2775 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2776 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2780 #extract the line range in the file after the patch is applied
2781 if (!$in_commit_log &&
2782 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2785 $first_line = $linenr + 1;
2795 %suppress_ifbraces = ();
2796 %suppress_whiletrailers = ();
2797 %suppress_export = ();
2798 $suppress_statement = 0;
2799 if ($context =~ /\b(\w+)\s*\(/) {
2800 $context_function = $1;
2802 undef $context_function;
2806 # track the line number as we move through the hunk, note that
2807 # new versions of GNU diff omit the leading space on completely
2808 # blank context lines so we need to count that too.
2809 } elsif ($line =~ /^( |\+|$)/) {
2811 $realcnt-- if ($realcnt != 0);
2813 # Measure the line length and indent.
2814 ($length, $indent) = line_stats($rawline);
2816 # Track the previous line.
2817 ($prevline, $stashline) = ($stashline, $line);
2818 ($previndent, $stashindent) = ($stashindent, $indent);
2819 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2821 #warn "line<$line>\n";
2823 } elsif ($realcnt == 1) {
2827 my $hunk_line = ($realcnt != 0);
2829 $here = "#$linenr: " if (!$file);
2830 $here = "#$realline: " if ($file);
2833 # extract the filename as it passes
2834 if ($line =~ /^diff --git.*?(\S+)$/) {
2836 $realfile =~ s@^([^/]*)/@@ if (!$file);
2839 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2841 $realfile =~ s@^([^/]*)/@@ if (!$file);
2845 if (!$file && $tree && $p1_prefix ne '' &&
2846 -e "$root/$p1_prefix") {
2847 WARN("PATCH_PREFIX",
2848 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2851 if ($realfile =~ m@^include/asm/@) {
2852 ERROR("MODIFIED_INCLUDE_ASM",
2853 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2858 #make up the handle for any error we report on this line
2860 $prefix = "$realfile:$realline: "
2863 $prefix = "$filename:$realline: ";
2865 $prefix = "$filename:$linenr: ";
2870 if (is_maintained_obsolete($realfile)) {
2872 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2874 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2877 $check = $check_orig;
2879 $checklicenseline = 1;
2881 if ($realfile !~ /^MAINTAINERS/) {
2882 my $last_binding_patch = $is_binding_patch;
2884 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2886 if (($last_binding_patch != -1) &&
2887 ($last_binding_patch ^ $is_binding_patch)) {
2888 WARN("DT_SPLIT_BINDING_PATCH",
2889 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2896 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2898 my $hereline = "$here\n$rawline\n";
2899 my $herecurr = "$here\n$rawline\n";
2900 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2902 $cnt_lines++ if ($realcnt != 0);
2904 # Verify the existence of a commit log if appropriate
2905 # 2 is used because a $signature is counted in $commit_log_lines
2906 if ($in_commit_log) {
2907 if ($line !~ /^\s*$/) {
2908 $commit_log_lines++; #could be a $signature
2910 } elsif ($has_commit_log && $commit_log_lines < 2) {
2911 WARN("COMMIT_MESSAGE",
2912 "Missing commit description - Add an appropriate one\n");
2913 $commit_log_lines = 2; #warn only once
2916 # Check if the commit log has what seems like a diff which can confuse patch
2917 if ($in_commit_log && !$commit_log_has_diff &&
2918 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2919 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2920 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2921 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2922 ERROR("DIFF_IN_COMMIT_MSG",
2923 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2924 $commit_log_has_diff = 1;
2927 # Check for incorrect file permissions
2928 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2929 my $permhere = $here . "FILE: $realfile\n";
2930 if ($realfile !~ m@scripts/@ &&
2931 $realfile !~ /\.(py|pl|awk|sh)$/) {
2932 ERROR("EXECUTE_PERMISSIONS",
2933 "do not set execute permissions for source files\n" . $permhere);
2937 # Check the patch for a From:
2938 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2940 my $curline = $linenr;
2941 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2944 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2946 $author = reformat_email($author);
2949 # Check the patch for a signoff:
2950 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2953 if ($author ne '' && $authorsignoff != 1) {
2954 if (same_email_addresses($1, $author)) {
2958 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2959 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2961 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2964 } elsif (lc $email_address eq lc $author_address) {
2967 } elsif ($email_name eq $author_name) {
2971 my $address1 = $email_address;
2972 my $address2 = $author_address;
2974 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2977 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2980 if ($address1 eq $address2) {
2988 # Check for patch separator
2989 if ($line =~ /^---$/) {
2990 $has_patch_separator = 1;
2994 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2995 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2996 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2997 $reported_maintainer_file = 1;
3000 # Check signature styles
3001 if (!$in_header_lines &&
3002 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3003 my $space_before = $1;
3005 my $space_after = $3;
3007 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3009 if ($sign_off !~ /$signature_tags/) {
3010 my $suggested_signature = find_standard_signature($sign_off);
3011 if ($suggested_signature eq "") {
3012 WARN("BAD_SIGN_OFF",
3013 "Non-standard signature: $sign_off\n" . $herecurr);
3015 if (WARN("BAD_SIGN_OFF",
3016 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3018 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3022 if (defined $space_before && $space_before ne "") {
3023 if (WARN("BAD_SIGN_OFF",
3024 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3026 $fixed[$fixlinenr] =
3027 "$ucfirst_sign_off $email";
3030 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3031 if (WARN("BAD_SIGN_OFF",
3032 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3034 $fixed[$fixlinenr] =
3035 "$ucfirst_sign_off $email";
3039 if (!defined $space_after || $space_after ne " ") {
3040 if (WARN("BAD_SIGN_OFF",
3041 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3043 $fixed[$fixlinenr] =
3044 "$ucfirst_sign_off $email";
3048 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3049 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3050 if ($suggested_email eq "") {
3051 ERROR("BAD_SIGN_OFF",
3052 "Unrecognized email address: '$email'\n" . $herecurr);
3054 my $dequoted = $suggested_email;
3055 $dequoted =~ s/^"//;
3056 $dequoted =~ s/" </ </;
3057 # Don't force email to have quotes
3058 # Allow just an angle bracketed address
3059 if (!same_email_addresses($email, $suggested_email)) {
3060 if (WARN("BAD_SIGN_OFF",
3061 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3063 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3067 # Address part shouldn't have comments
3068 my $stripped_address = $email_address;
3069 $stripped_address =~ s/\([^\(\)]*\)//g;
3070 if ($email_address ne $stripped_address) {
3071 if (WARN("BAD_SIGN_OFF",
3072 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3074 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3078 # Only one name comment should be allowed
3079 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3080 if ($comment_count > 1) {
3081 WARN("BAD_SIGN_OFF",
3082 "Use a single name comment in email: '$email'\n" . $herecurr);
3086 # stable@vger.kernel.org or stable@kernel.org shouldn't
3087 # have an email name. In addition comments should strictly
3089 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3090 if (($comment ne "" && $comment !~ /^#.+/) ||
3091 ($email_name ne "")) {
3092 my $cur_name = $email_name;
3093 my $new_comment = $comment;
3094 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3096 # Remove brackets enclosing comment text
3097 # and # from start of comments to get comment text
3098 $new_comment =~ s/^\((.*)\)$/$1/;
3099 $new_comment =~ s/^\[(.*)\]$/$1/;
3100 $new_comment =~ s/^[\s\#]+|\s+$//g;
3102 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3103 $new_comment = " # $new_comment" if ($new_comment ne "");
3104 my $new_email = "$email_address$new_comment";
3106 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3107 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3109 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3112 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3113 my $new_comment = $comment;
3115 # Extract comment text from within brackets or
3116 # c89 style /*...*/ comments
3117 $new_comment =~ s/^\[(.*)\]$/$1/;
3118 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3120 $new_comment = trim($new_comment);
3121 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3122 $new_comment = "($new_comment)" if ($new_comment ne "");
3123 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3125 if (WARN("BAD_SIGN_OFF",
3126 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3128 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3133 # Check for duplicate signatures
3134 my $sig_nospace = $line;
3135 $sig_nospace =~ s/\s//g;
3136 $sig_nospace = lc($sig_nospace);
3137 if (defined $signatures{$sig_nospace}) {
3138 WARN("BAD_SIGN_OFF",
3139 "Duplicate signature\n" . $herecurr);
3141 $signatures{$sig_nospace} = 1;
3144 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3145 if ($sign_off =~ /^co-developed-by:$/i) {
3146 if ($email eq $author) {
3147 WARN("BAD_SIGN_OFF",
3148 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3150 if (!defined $lines[$linenr]) {
3151 WARN("BAD_SIGN_OFF",
3152 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3153 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3154 WARN("BAD_SIGN_OFF",
3155 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3156 } elsif ($1 ne $email) {
3157 WARN("BAD_SIGN_OFF",
3158 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3163 # Check email subject for common tools that don't need to be mentioned
3164 if ($in_header_lines &&
3165 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3166 WARN("EMAIL_SUBJECT",
3167 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3170 # Check for Gerrit Change-Ids not in any patch context
3171 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3172 if (ERROR("GERRIT_CHANGE_ID",
3173 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3175 fix_delete_line($fixlinenr, $rawline);
3179 # Check if the commit log is in a possible stack dump
3180 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3181 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3182 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3184 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3185 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3186 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3187 # stack dump address styles
3188 $commit_log_possible_stack_dump = 1;
3191 # Check for line lengths > 75 in commit log, warn once
3192 if ($in_commit_log && !$commit_log_long_line &&
3193 length($line) > 75 &&
3194 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3195 # file delta changes
3196 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3198 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3199 # A Fixes: or Link: line or signature tag line
3200 $commit_log_possible_stack_dump)) {
3201 WARN("COMMIT_LOG_LONG_LINE",
3202 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3203 $commit_log_long_line = 1;
3206 # Reset possible stack dump if a blank line is found
3207 if ($in_commit_log && $commit_log_possible_stack_dump &&
3209 $commit_log_possible_stack_dump = 0;
3212 # Check for lines starting with a #
3213 if ($in_commit_log && $line =~ /^#/) {
3214 if (WARN("COMMIT_COMMENT_SYMBOL",
3215 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3217 $fixed[$fixlinenr] =~ s/^/ /;
3221 # Check for git id commit length and improperly formed commit descriptions
3222 # A correctly formed commit description is:
3223 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3224 # with the commit subject '("' prefix and '")' suffix
3225 # This is a fairly compilicated block as it tests for what appears to be
3226 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3227 # possible SHA-1 matches.
3228 # A commit match can span multiple lines so this block attempts to find a
3229 # complete typical commit on a maximum of 3 lines
3230 if ($perl_version_ok &&
3231 $in_commit_log && !$commit_log_possible_stack_dump &&
3232 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3233 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3234 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3235 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3236 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3237 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3238 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3239 my $init_char = "c";
3240 my $orig_commit = "";
3245 my $id = '0123456789ab';
3246 my $orig_desc = "commit description";
3247 my $description = "";
3248 my $herectx = $herecurr;
3253 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3254 for (my $n = 0; $n < 2; $n++) {
3255 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3258 # Always strip leading/trailing parens then double quotes if existing
3259 $orig_desc = substr($orig_desc, 1, -1);
3260 if ($orig_desc =~ /^".*"$/) {
3261 $orig_desc = substr($orig_desc, 1, -1);
3266 last if ($#lines < $linenr + $n);
3267 $input .= " " . trim($rawlines[$linenr + $n]);
3268 $herectx .= "$rawlines[$linenr + $n]\n";
3270 $herectx = $herecurr if (!$has_parens);
3273 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3275 $orig_commit = lc($2);
3276 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3277 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3278 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3279 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3280 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3281 $orig_commit = lc($1);
3284 ($id, $description) = git_commit_info($orig_commit,
3288 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3289 $last_git_commit_id_linenr != $linenr - 1) {
3290 ERROR("GIT_COMMIT_ID",
3291 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3293 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3294 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3297 # Check for added, moved or deleted files
3298 if (!$reported_maintainer_file && !$in_commit_log &&
3299 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3300 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3301 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3302 (defined($1) || defined($2))))) {
3304 $reported_maintainer_file = 1;
3305 WARN("FILE_PATH_CHANGES",
3306 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3309 # Check for adding new DT bindings not in schema format
3310 if (!$in_commit_log &&
3311 ($line =~ /^new file mode\s*\d+\s*$/) &&
3312 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3313 WARN("DT_SCHEMA_BINDING_PATCH",
3314 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3317 # Check for wrappage within a valid hunk of the file
3318 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3319 ERROR("CORRUPTED_PATCH",
3320 "patch seems to be corrupt (line wrapped?)\n" .
3321 $herecurr) if (!$emitted_corrupt++);
3324 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3325 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3326 $rawline !~ m/^$UTF8*$/) {
3327 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3329 my $blank = copy_spacing($rawline);
3330 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3331 my $hereptr = "$hereline$ptr\n";
3334 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3337 # Check if it's the start of a commit log
3338 # (not a header line and we haven't seen the patch filename)
3339 if ($in_header_lines && $realfile =~ /^$/ &&
3340 !($rawline =~ /^\s+(?:\S|$)/ ||
3341 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3342 $in_header_lines = 0;
3344 $has_commit_log = 1;
3347 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3348 # declined it, i.e defined some charset where it is missing.
3349 if ($in_header_lines &&
3350 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3352 $non_utf8_charset = 1;
3355 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3356 $rawline =~ /$NON_ASCII_UTF8/) {
3357 WARN("UTF8_BEFORE_PATCH",
3358 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3361 # Check for absolute kernel paths in commit message
3362 if ($tree && $in_commit_log) {
3363 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3366 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3367 check_absolute_file($1, $herecurr)) {
3370 check_absolute_file($file, $herecurr);
3375 # Check for various typo / spelling mistakes
3376 if (defined($misspellings) &&
3377 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3378 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3380 my $blank = copy_spacing($rawline);
3381 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3382 my $hereptr = "$hereline$ptr\n";
3383 my $typo_fix = $spelling_fix{lc($typo)};
3384 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3385 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3386 my $msg_level = \&WARN;
3387 $msg_level = \&CHK if ($file);
3388 if (&{$msg_level}("TYPO_SPELLING",
3389 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3391 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3396 # check for invalid commit id
3397 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3400 ($id, $description) = git_commit_info($2, undef, undef);
3401 if (!defined($id)) {
3402 WARN("UNKNOWN_COMMIT_ID",
3403 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3407 # check for repeated words separated by a single space
3408 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3409 if (($rawline =~ /^\+/ || $in_commit_log) &&
3410 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3411 pos($rawline) = 1 if (!$in_commit_log);
3412 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3416 my $start_pos = $-[1];
3417 my $end_pos = $+[2];
3418 if ($first =~ /(?:struct|union|enum)/) {
3419 pos($rawline) += length($first) + length($second) + 1;
3423 next if (lc($first) ne lc($second));
3424 next if ($first eq 'long');
3426 # check for character before and after the word matches
3427 my $start_char = '';
3429 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3430 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3432 next if ($start_char =~ /^\S$/);
3433 next if (index(" \t.,;?!", $end_char) == -1);
3435 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3436 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3437 next if (!exists($allow_repeated_words{lc($first)}));
3440 if (WARN("REPEATED_WORD",
3441 "Possible repeated word: '$first'\n" . $herecurr) &&
3443 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3447 # if it's a repeated word on consecutive lines in a comment block
3448 if ($prevline =~ /$;+\s*$/ &&
3449 $prevrawline =~ /($word_pattern)\s*$/) {
3451 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3452 if (WARN("REPEATED_WORD",
3453 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3455 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3461 # ignore non-hunk lines and lines being removed
3462 next if (!$hunk_line || $line =~ /^-/);
3464 #trailing whitespace
3465 if ($line =~ /^\+.*\015/) {
3466 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3467 if (ERROR("DOS_LINE_ENDINGS",
3468 "DOS line endings\n" . $herevet) &&
3470 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3472 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3473 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3474 if (ERROR("TRAILING_WHITESPACE",
3475 "trailing whitespace\n" . $herevet) &&
3477 $fixed[$fixlinenr] =~ s/\s+$//;
3483 # Check for FSF mailing addresses.
3484 if ($rawline =~ /\bwrite to the Free/i ||
3485 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3486 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3487 $rawline =~ /\b51\s+Franklin\s+St/i) {
3488 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3489 my $msg_level = \&ERROR;
3490 $msg_level = \&CHK if ($file);
3491 &{$msg_level}("FSF_MAILING_ADDRESS",
3492 "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)
3495 # check for Kconfig help text having a real description
3496 # Only applies when adding the entry originally, after that we do not have
3497 # sufficient context to determine whether it is indeed long enough.
3498 if ($realfile =~ /Kconfig/ &&
3499 # 'choice' is usually the last thing on the line (though
3500 # Kconfig supports named choices), so use a word boundary
3501 # (\b) rather than a whitespace character (\s)
3502 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3506 my $help_length = 0;
3507 while (defined $lines[$ln]) {
3508 my $f = $lines[$ln++];
3510 next if ($f =~ /^-/);
3511 last if ($f !~ /^[\+ ]/); # !patch context
3513 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3517 if ($f =~ /^\+\s*help\s*$/) {
3522 $f =~ s/^.//; # strip patch context [+ ]
3523 $f =~ s/#.*//; # strip # directives
3524 $f =~ s/^\s+//; # strip leading blanks
3525 next if ($f =~ /^$/); # skip blank lines
3527 # At the end of this Kconfig block:
3528 # This only checks context lines in the patch
3529 # and so hopefully shouldn't trigger false
3530 # positives, even though some of these are
3531 # common words in help texts
3532 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3533 if|endif|menu|endmenu|source)\b/x) {
3536 $help_length++ if ($has_help);
3539 $help_length < $min_conf_desc_length) {
3540 my $stat_real = get_stat_real($linenr, $ln - 1);
3541 WARN("CONFIG_DESCRIPTION",
3542 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3546 # check MAINTAINERS entries
3547 if ($realfile =~ /^MAINTAINERS$/) {
3548 # check MAINTAINERS entries for the right form
3549 if ($rawline =~ /^\+[A-Z]:/ &&
3550 $rawline !~ /^\+[A-Z]:\t\S/) {
3551 if (WARN("MAINTAINERS_STYLE",
3552 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3554 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3557 # check MAINTAINERS entries for the right ordering too
3558 my $preferred_order = 'MRLSWQBCPTFXNK';
3559 if ($rawline =~ /^\+[A-Z]:/ &&
3560 $prevrawline =~ /^[\+ ][A-Z]:/) {
3561 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3564 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3567 my $curindex = index($preferred_order, $cur);
3568 my $previndex = index($preferred_order, $prev);
3569 if ($curindex < 0) {
3570 WARN("MAINTAINERS_STYLE",
3571 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3573 if ($previndex >= 0 && $curindex < $previndex) {
3574 WARN("MAINTAINERS_STYLE",
3575 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3576 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3577 ($prev eq 'X' && $cur eq 'X')) &&
3578 ($prevval cmp $curval) > 0) {
3579 WARN("MAINTAINERS_STYLE",
3580 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3586 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3587 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3590 'EXTRA_AFLAGS' => 'asflags-y',
3591 'EXTRA_CFLAGS' => 'ccflags-y',
3592 'EXTRA_CPPFLAGS' => 'cppflags-y',
3593 'EXTRA_LDFLAGS' => 'ldflags-y',
3596 WARN("DEPRECATED_VARIABLE",
3597 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3600 # check for DT compatible documentation
3601 if (defined $root &&
3602 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3603 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3605 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3607 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3608 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3610 foreach my $compat (@compats) {
3611 my $compat2 = $compat;
3612 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3613 my $compat3 = $compat;
3614 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3615 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3617 WARN("UNDOCUMENTED_DT_STRING",
3618 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3621 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3623 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3625 WARN("UNDOCUMENTED_DT_STRING",
3626 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3631 # check for using SPDX license tag at beginning of files
3632 if ($realline == $checklicenseline) {
3633 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3634 $checklicenseline = 2;
3635 } elsif ($rawline =~ /^\+/) {
3637 if ($realfile =~ /\.(h|s|S)$/) {
3639 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3641 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3643 } elsif ($realfile =~ /\.rst$/) {
3647 # check SPDX comment style for .[chsS] files
3648 if ($realfile =~ /\.[chsS]$/ &&
3649 $rawline =~ /SPDX-License-Identifier:/ &&
3650 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3651 WARN("SPDX_LICENSE_TAG",
3652 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3655 if ($comment !~ /^$/ &&
3656 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3657 WARN("SPDX_LICENSE_TAG",
3658 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3659 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3660 my $spdx_license = $1;
3661 if (!is_SPDX_License_valid($spdx_license)) {
3662 WARN("SPDX_LICENSE_TAG",
3663 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3665 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3666 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3667 my $msg_level = \&WARN;
3668 $msg_level = \&CHK if ($file);
3669 if (&{$msg_level}("SPDX_LICENSE_TAG",
3671 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3673 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3680 # check for embedded filenames
3681 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3682 WARN("EMBEDDED_FILENAME",
3683 "It's generally not useful to have the filename in the file\n" . $herecurr);
3686 # check we are in a valid source file if not then ignore this hunk
3687 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3689 # check for using SPDX-License-Identifier on the wrong line number
3690 if ($realline != $checklicenseline &&
3691 $rawline =~ /\bSPDX-License-Identifier:/ &&
3692 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3693 WARN("SPDX_LICENSE_TAG",
3694 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3697 # line length limit (with some exclusions)
3699 # There are a few types of lines that may extend beyond $max_line_length:
3700 # logging functions like pr_info that end in a string
3701 # lines with a single string
3702 # #defines that are a single string
3703 # lines with an RFC3986 like URL
3705 # There are 3 different line length message types:
3706 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3707 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3708 # LONG_LINE all other lines longer than $max_line_length
3710 # if LONG_LINE is ignored, the other 2 types are also ignored
3713 if ($line =~ /^\+/ && $length > $max_line_length) {
3714 my $msg_type = "LONG_LINE";
3716 # Check the allowed long line types first
3718 # logging functions that end in a string that starts
3719 # before $max_line_length
3720 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3721 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3724 # lines with only strings (w/ possible termination)
3725 # #defines with only strings
3726 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3727 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3730 # More special cases
3731 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3732 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3735 # URL ($rawline is used in case the URL is in a comment)
3736 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3739 # Otherwise set the alternate message types
3741 # a comment starts before $max_line_length
3742 } elsif ($line =~ /($;[\s$;]*)$/ &&
3743 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3744 $msg_type = "LONG_LINE_COMMENT"
3746 # a quoted string starts before $max_line_length
3747 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3748 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3749 $msg_type = "LONG_LINE_STRING"
3752 if ($msg_type ne "" &&
3753 (show_type("LONG_LINE") || show_type($msg_type))) {
3754 my $msg_level = \&WARN;
3755 $msg_level = \&CHK if ($file);
3756 &{$msg_level}($msg_type,
3757 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3761 # check for adding lines without a newline.
3762 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3763 if (WARN("MISSING_EOF_NEWLINE",
3764 "adding a line without newline at end of file\n" . $herecurr) &&
3766 fix_delete_line($fixlinenr+1, "No newline at end of file");
3770 # check for .L prefix local symbols in .S files
3771 if ($realfile =~ /\.S$/ &&
3772 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3773 WARN("AVOID_L_PREFIX",
3774 "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);
3777 # check we are in a valid source file C or perl if not then ignore this hunk
3778 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3780 # at the beginning of a line any tabs must come first and anything
3781 # more than $tabsize must use tabs.
3782 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3783 $rawline =~ /^\+\s* \s*/) {
3784 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3786 if (ERROR("CODE_INDENT",
3787 "code indent should use tabs where possible\n" . $herevet) &&
3789 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3793 # check for space before tabs.
3794 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3795 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3796 if (WARN("SPACE_BEFORE_TAB",
3797 "please, no space before tabs\n" . $herevet) &&
3799 while ($fixed[$fixlinenr] =~
3800 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3801 while ($fixed[$fixlinenr] =~
3802 s/(^\+.*) +\t/$1\t/) {}
3806 # check for assignments on the start of a line
3807 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3809 if (CHK("ASSIGNMENT_CONTINUATIONS",
3810 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3811 $fix && $prevrawline =~ /^\+/) {
3812 # add assignment operator to the previous line, remove from current line
3813 $fixed[$fixlinenr - 1] .= " $operator";
3814 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3818 # check for && or || at the start of a line
3819 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3821 if (CHK("LOGICAL_CONTINUATIONS",
3822 "Logical continuations should be on the previous line\n" . $hereprev) &&
3823 $fix && $prevrawline =~ /^\+/) {
3824 # insert logical operator at last non-comment, non-whitepsace char on previous line
3825 $prevline =~ /[\s$;]*$/;
3826 my $line_end = substr($prevrawline, $-[0]);
3827 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3828 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3832 # check indentation starts on a tab stop
3833 if ($perl_version_ok &&
3834 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3835 my $indent = length($1);
3836 if ($indent % $tabsize) {
3838 "Statements should start on a tabstop\n" . $herecurr) &&
3840 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3845 # check multi-line statement indentation matches previous line
3846 if ($perl_version_ok &&
3847 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3848 $prevline =~ /^\+(\t*)(.*)$/;
3852 my $pos = pos_last_openparen($rest);
3854 $line =~ /^(\+| )([ \t]*)/;
3857 my $goodtabindent = $oldindent .
3858 "\t" x ($pos / $tabsize) .
3859 " " x ($pos % $tabsize);
3860 my $goodspaceindent = $oldindent . " " x $pos;
3862 if ($newindent ne $goodtabindent &&
3863 $newindent ne $goodspaceindent) {
3865 if (CHK("PARENTHESIS_ALIGNMENT",
3866 "Alignment should match open parenthesis\n" . $hereprev) &&
3867 $fix && $line =~ /^\+/) {
3868 $fixed[$fixlinenr] =~
3869 s/^\+[ \t]*/\+$goodtabindent/;
3875 # check for space after cast like "(int) foo" or "(struct foo) bar"
3876 # avoid checking a few false positives:
3877 # "sizeof(<type>)" or "__alignof__(<type>)"
3878 # function pointer declarations like "(*foo)(int) = bar;"
3879 # structure definitions like "(struct foo) { 0 };"
3880 # multiline macros that define functions
3881 # known attributes or the __attribute__ keyword
3882 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3883 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3885 "No space is necessary after a cast\n" . $herecurr) &&
3887 $fixed[$fixlinenr] =~
3888 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3892 # Block comment styles
3893 # Networking with an initial /*
3894 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3895 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3896 $rawline =~ /^\+[ \t]*\*/ &&
3897 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3898 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3899 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3902 # Block comments use * on subsequent lines
3903 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3904 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3905 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3906 $rawline =~ /^\+/ && #line is new
3907 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3908 WARN("BLOCK_COMMENT_STYLE",
3909 "Block comments use * on subsequent lines\n" . $hereprev);
3912 # Block comments use */ on trailing lines
3913 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3914 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3915 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3916 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3917 WARN("BLOCK_COMMENT_STYLE",
3918 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3921 # Block comment * alignment
3922 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3923 $line =~ /^\+[ \t]*$;/ && #leading comment
3924 $rawline =~ /^\+[ \t]*\*/ && #leading *
3925 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3926 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3927 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3929 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3931 $oldindent = expand_tabs($1);
3933 $prevrawline =~ m@^\+(.*/?)\*@;
3934 $oldindent = expand_tabs($1);
3936 $rawline =~ m@^\+([ \t]*)\*@;
3938 $newindent = expand_tabs($newindent);
3939 if (length($oldindent) ne length($newindent)) {
3940 WARN("BLOCK_COMMENT_STYLE",
3941 "Block comments should align the * on each line\n" . $hereprev);
3945 # check for missing blank lines after struct/union declarations
3946 # with exceptions for various attributes and macros
3947 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3949 !($line =~ /^\+\s*$/ ||
3950 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
3951 $line =~ /^\+\s*MODULE_/i ||
3952 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3953 $line =~ /^\+[a-z_]*init/ ||
3954 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3955 $line =~ /^\+\s*DECLARE/ ||
3956 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3957 $line =~ /^\+\s*__setup/)) {
3958 if (CHK("LINE_SPACING",
3959 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3961 fix_insert_line($fixlinenr, "\+");
3965 # check for multiple consecutive blank lines
3966 if ($prevline =~ /^[\+ ]\s*$/ &&
3967 $line =~ /^\+\s*$/ &&
3968 $last_blank_line != ($linenr - 1)) {
3969 if (CHK("LINE_SPACING",
3970 "Please don't use multiple blank lines\n" . $hereprev) &&
3972 fix_delete_line($fixlinenr, $rawline);
3975 $last_blank_line = $linenr;
3978 # check for missing blank lines after declarations
3979 # (declarations must have the same indentation and not be at the start of line)
3980 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3984 # remove $Attribute/$Sparse uses to simplify comparisons
3985 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3986 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3987 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3988 # function pointer declarations
3989 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3990 # foo bar; where foo is some local typedef or #define
3991 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3992 # known declaration macros
3993 $pl =~ /^\+\s+$declaration_macros/) &&
3994 # for "else if" which can look like "$Ident $Ident"
3995 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3996 # other possible extensions of declaration lines
3997 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3998 # not starting a section or a macro "\" extended line
3999 $pl =~ /(?:\{\s*|\\)$/) &&
4000 # looks like a declaration
4001 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4002 # function pointer declarations
4003 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4004 # foo bar; where foo is some local typedef or #define
4005 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4006 # known declaration macros
4007 $sl =~ /^\+\s+$declaration_macros/ ||
4008 # start of struct or union or enum
4009 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4010 # start or end of block or continuation of declaration
4011 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4012 # bitfield continuation
4013 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4014 # other possible extensions of declaration lines
4015 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4016 if (WARN("LINE_SPACING",
4017 "Missing a blank line after declarations\n" . $hereprev) &&
4019 fix_insert_line($fixlinenr, "\+");
4024 # check for spaces at the beginning of a line.
4026 # 1) within comments
4027 # 2) indented preprocessor commands
4029 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4030 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4031 if (WARN("LEADING_SPACE",
4032 "please, no spaces at the start of a line\n" . $herevet) &&
4034 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4038 # check we are in a valid C source file if not then ignore this hunk
4039 next if ($realfile !~ /\.(h|c)$/);
4041 # check for unusual line ending [ or (
4042 if ($line =~ /^\+.*([\[\(])\s*$/) {
4043 CHK("OPEN_ENDED_LINE",
4044 "Lines should not end with a '$1'\n" . $herecurr);
4047 # check if this appears to be the start function declaration, save the name
4048 if ($sline =~ /^\+\{\s*$/ &&
4049 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4050 $context_function = $1;
4053 # check if this appears to be the end of function declaration
4054 if ($sline =~ /^\+\}\s*$/) {
4055 undef $context_function;
4058 # check indentation of any line with a bare else
4059 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4060 # if the previous line is a break or return and is indented 1 tab more...
4061 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4062 my $tabs = length($1) + 1;
4063 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4064 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4065 defined $lines[$linenr] &&
4066 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4067 WARN("UNNECESSARY_ELSE",
4068 "else is not generally useful after a break or return\n" . $hereprev);
4072 # check indentation of a line with a break;
4073 # if the previous line is a goto, return or break
4074 # and is indented the same # of tabs
4075 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4077 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4078 if (WARN("UNNECESSARY_BREAK",
4079 "break is not useful after a $1\n" . $hereprev) &&
4081 fix_delete_line($fixlinenr, $rawline);
4086 # check for RCS/CVS revision markers
4087 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4089 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4092 # check for old HOTPLUG __dev<foo> section markings
4093 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4094 WARN("HOTPLUG_SECTION",
4095 "Using $1 is unnecessary\n" . $herecurr);
4098 # Check for potential 'bare' types
4099 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4101 #print "LINE<$line>\n";
4102 if ($linenr > $suppress_statement &&
4103 $realcnt && $sline =~ /.\s*\S/) {
4104 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4105 ctx_statement_block($linenr, $realcnt, 0);
4106 $stat =~ s/\n./\n /g;
4107 $cond =~ s/\n./\n /g;
4109 #print "linenr<$linenr> <$stat>\n";
4110 # If this statement has no statement boundaries within
4111 # it there is no point in retrying a statement scan
4112 # until we hit end of it.
4113 my $frag = $stat; $frag =~ s/;+\s*$//;
4114 if ($frag !~ /(?:{|;)/) {
4115 #print "skip<$line_nr_next>\n";
4116 $suppress_statement = $line_nr_next;
4119 # Find the real next line.
4120 $realline_next = $line_nr_next;
4121 if (defined $realline_next &&
4122 (!defined $lines[$realline_next - 1] ||
4123 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4130 # Ignore goto labels.
4131 if ($s =~ /$Ident:\*$/s) {
4133 # Ignore functions being called
4134 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4136 } elsif ($s =~ /^.\s*else\b/s) {
4138 # declarations always start with types
4139 } 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) {
4142 possible($type, "A:" . $s);
4144 # definitions in global scope can only start with types
4145 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4146 possible($1, "B:" . $s);
4149 # any (foo ... *) is a pointer cast, and foo is a type
4150 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4151 possible($1, "C:" . $s);
4154 # Check for any sort of function declaration.
4155 # int foo(something bar, other baz);
4156 # void (*store_gdt)(x86_descr_ptr *);
4157 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4158 my ($name_len) = length($1);
4161 substr($ctx, 0, $name_len + 1, '');
4162 $ctx =~ s/\)[^\)]*$//;
4164 for my $arg (split(/\s*,\s*/, $ctx)) {
4165 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4167 possible($1, "D:" . $s);
4175 # Checks which may be anchored in the context.
4178 # Check for switch () and associated case and default
4179 # statements should be at the same indent.
4180 if ($line=~/\bswitch\s*\(.*\)/) {
4183 my @ctx = ctx_block_outer($linenr, $realcnt);
4185 for my $ctx (@ctx) {
4186 my ($clen, $cindent) = line_stats($ctx);
4187 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4188 $indent != $cindent) {
4189 $err .= "$sep$ctx\n";
4196 ERROR("SWITCH_CASE_INDENT_LEVEL",
4197 "switch and case should be at the same indent\n$hereline$err");
4201 # if/while/etc brace do not go on next line, unless defining a do while loop,
4202 # or if that brace on the next line is for something else
4203 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4204 my $pre_ctx = "$1$2";
4206 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4208 if ($line =~ /^\+\t{6,}/) {
4209 WARN("DEEP_INDENTATION",
4210 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4213 my $ctx_cnt = $realcnt - $#ctx - 1;
4214 my $ctx = join("\n", @ctx);
4216 my $ctx_ln = $linenr;
4217 my $ctx_skip = $realcnt;
4219 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4220 defined $lines[$ctx_ln - 1] &&
4221 $lines[$ctx_ln - 1] =~ /^-/)) {
4222 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4223 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4227 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4228 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4230 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4232 "that open brace { should be on the previous line\n" .
4233 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4235 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4236 $ctx =~ /\)\s*\;\s*$/ &&
4237 defined $lines[$ctx_ln - 1])
4239 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4240 if ($nindent > $indent) {
4241 WARN("TRAILING_SEMICOLON",
4242 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4243 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4248 # Check relative indent for conditionals and blocks.
4249 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4250 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4251 ctx_statement_block($linenr, $realcnt, 0)
4252 if (!defined $stat);
4253 my ($s, $c) = ($stat, $cond);
4255 substr($s, 0, length($c), '');
4257 # remove inline comments
4261 # Find out how long the conditional actually is.
4262 my @newlines = ($c =~ /\n/gs);
4263 my $cond_lines = 1 + $#newlines;
4265 # Make sure we remove the line prefixes as we have
4266 # none on the first line, and are going to readd them
4269 while ($s =~ /\n\s+\\\n/) {
4270 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4273 # We want to check the first line inside the block
4274 # starting at the end of the conditional, so remove:
4275 # 1) any blank line termination
4276 # 2) any opening brace { on end of the line
4278 my $continuation = 0;
4280 $s =~ s/^.*\bdo\b//;
4282 if ($s =~ s/^\s*\\//) {
4285 if ($s =~ s/^\s*?\n//) {
4290 # Also ignore a loop construct at the end of a
4291 # preprocessor statement.
4292 if (($prevline =~ /^.\s*#\s*define\s/ ||
4293 $prevline =~ /\\\s*$/) && $continuation == 0) {
4299 while ($cond_ptr != $cond_lines) {
4300 $cond_ptr = $cond_lines;
4302 # If we see an #else/#elif then the code
4304 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4309 # 1) blank lines, they should be at 0,
4310 # 2) preprocessor lines, and
4312 if ($continuation ||
4314 $s =~ /^\s*#\s*?/ ||
4315 $s =~ /^\s*$Ident\s*:/) {
4316 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4317 if ($s =~ s/^.*?\n//) {
4323 my (undef, $sindent) = line_stats("+" . $s);
4324 my $stat_real = raw_line($linenr, $cond_lines);
4326 # Check if either of these lines are modified, else
4327 # this is not this patch's fault.
4328 if (!defined($stat_real) ||
4329 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4332 if (defined($stat_real) && $cond_lines > 1) {
4333 $stat_real = "[...]\n$stat_real";
4336 #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";
4338 if ($check && $s ne '' &&
4339 (($sindent % $tabsize) != 0 ||
4340 ($sindent < $indent) ||
4341 ($sindent == $indent &&
4342 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4343 ($sindent > $indent + $tabsize))) {
4344 WARN("SUSPECT_CODE_INDENT",
4345 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4349 # Track the 'values' across context and added lines.
4350 my $opline = $line; $opline =~ s/^./ /;
4351 my ($curr_values, $curr_vars) =
4352 annotate_values($opline . "\n", $prev_values);
4353 $curr_values = $prev_values . $curr_values;
4355 my $outline = $opline; $outline =~ s/\t/ /g;
4356 print "$linenr > .$outline\n";
4357 print "$linenr > $curr_values\n";
4358 print "$linenr > $curr_vars\n";
4360 $prev_values = substr($curr_values, -1);
4362 #ignore lines not being added
4363 next if ($line =~ /^[^\+]/);
4365 # check for self assignments used to avoid compiler warnings
4366 # e.g.: int foo = foo, *bar = NULL;
4367 # struct foo bar = *(&(bar));
4368 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4370 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4371 WARN("SELF_ASSIGNMENT",
4372 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4376 # check for dereferences that span multiple lines
4377 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4378 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4379 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4381 $line =~ /^.\s*($Lval)/;
4384 WARN("MULTILINE_DEREFERENCE",
4385 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4388 # check for declarations of signed or unsigned without int
4389 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4392 $var = "" if (!defined $var);
4393 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4397 $pointer = "" if (!defined $pointer);
4399 if (WARN("UNSPECIFIED_INT",
4400 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4402 my $decl = trim($sign) . " int ";
4403 my $comp_pointer = $pointer;
4404 $comp_pointer =~ s/\s//g;
4405 $decl .= $comp_pointer;
4406 $decl = rtrim($decl) if ($var eq "");
4407 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4412 # TEST: allow direct testing of the type matcher.
4414 if ($line =~ /^.\s*$Declare\s*$/) {
4416 "TEST: is type\n" . $herecurr);
4417 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4418 ERROR("TEST_NOT_TYPE",
4419 "TEST: is not type ($1 is)\n". $herecurr);
4423 # TEST: allow direct testing of the attribute matcher.
4425 if ($line =~ /^.\s*$Modifier\s*$/) {
4427 "TEST: is attr\n" . $herecurr);
4428 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4429 ERROR("TEST_NOT_ATTR",
4430 "TEST: is not attr ($1 is)\n". $herecurr);
4435 # check for initialisation to aggregates open brace on the next line
4436 if ($line =~ /^.\s*{/ &&
4437 $prevline =~ /(?:^|[^=])=\s*$/) {
4438 if (ERROR("OPEN_BRACE",
4439 "that open brace { should be on the previous line\n" . $hereprev) &&
4440 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4441 fix_delete_line($fixlinenr - 1, $prevrawline);
4442 fix_delete_line($fixlinenr, $rawline);
4443 my $fixedline = $prevrawline;
4444 $fixedline =~ s/\s*=\s*$/ = {/;
4445 fix_insert_line($fixlinenr, $fixedline);
4447 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4448 fix_insert_line($fixlinenr, $fixedline);
4453 # Checks which are anchored on the added line.
4456 # check for malformed paths in #include statements (uses RAW line)
4457 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4459 if ($path =~ m{//}) {
4460 ERROR("MALFORMED_INCLUDE",
4461 "malformed #include filename\n" . $herecurr);
4463 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4464 ERROR("UAPI_INCLUDE",
4465 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4469 # no C99 // comments
4470 if ($line =~ m{//}) {
4471 if (ERROR("C99_COMMENTS",
4472 "do not use C99 // comments\n" . $herecurr) &&
4474 my $line = $fixed[$fixlinenr];
4475 if ($line =~ /\/\/(.*)$/) {
4476 my $comment = trim($1);
4477 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4481 # Remove C99 comments.
4483 $opline =~ s@//.*@@;
4485 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4486 # the whole statement.
4487 #print "APW <$lines[$realline_next - 1]>\n";
4488 if (defined $realline_next &&
4489 exists $lines[$realline_next - 1] &&
4490 !defined $suppress_export{$realline_next} &&
4491 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4492 # Handle definitions which produce identifiers with
4495 # EXPORT_SYMBOL(something_foo);
4497 $name =~ s/^\s*($Ident).*/$1/;
4498 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4499 $name =~ /^${Ident}_$2/) {
4500 #print "FOO C name<$name>\n";
4501 $suppress_export{$realline_next} = 1;
4503 } elsif ($stat !~ /(?:
4505 ^.DEFINE_$Ident\(\Q$name\E\)|
4506 ^.DECLARE_$Ident\(\Q$name\E\)|
4507 ^.LIST_HEAD\(\Q$name\E\)|
4508 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4509 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4511 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4512 $suppress_export{$realline_next} = 2;
4514 $suppress_export{$realline_next} = 1;
4517 if (!defined $suppress_export{$linenr} &&
4518 $prevline =~ /^.\s*$/ &&
4519 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4520 #print "FOO B <$lines[$linenr - 1]>\n";
4521 $suppress_export{$linenr} = 2;
4523 if (defined $suppress_export{$linenr} &&
4524 $suppress_export{$linenr} == 2) {
4525 WARN("EXPORT_SYMBOL",
4526 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4529 # check for global initialisers.
4530 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4531 !exclude_global_initialisers($realfile)) {
4532 if (ERROR("GLOBAL_INITIALISERS",
4533 "do not initialise globals to $1\n" . $herecurr) &&
4535 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4538 # check for static initialisers.
4539 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4540 if (ERROR("INITIALISED_STATIC",
4541 "do not initialise statics to $1\n" .
4544 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4548 # check for misordered declarations of char/short/int/long with signed/unsigned
4549 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4551 WARN("MISORDERED_TYPE",
4552 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4555 # check for unnecessary <signed> int declarations of short/long/long long
4556 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4557 my $type = trim($1);
4558 next if ($type !~ /\bint\b/);
4559 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4560 my $new_type = $type;
4561 $new_type =~ s/\b\s*int\s*\b/ /;
4562 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4563 $new_type =~ s/^const\s+//;
4564 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4565 $new_type = "const $new_type" if ($type =~ /^const\b/);
4566 $new_type =~ s/\s+/ /g;
4567 $new_type = trim($new_type);
4568 if (WARN("UNNECESSARY_INT",
4569 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4571 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4575 # check for static const char * arrays.
4576 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4577 WARN("STATIC_CONST_CHAR_ARRAY",
4578 "static const char * array should probably be static const char * const\n" .
4582 # check for initialized const char arrays that should be static const
4583 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4584 if (WARN("STATIC_CONST_CHAR_ARRAY",
4585 "const array should probably be static const\n" . $herecurr) &&
4587 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4591 # check for static char foo[] = "bar" declarations.
4592 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4593 WARN("STATIC_CONST_CHAR_ARRAY",
4594 "static char array declaration should probably be static const char\n" .
4598 # check for const <foo> const where <foo> is not a pointer or array type
4599 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4601 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4603 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4604 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4606 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4610 # check for const static or static <non ptr type> const declarations
4611 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4612 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4613 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4614 if (WARN("STATIC_CONST",
4615 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4617 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4618 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4622 # check for non-global char *foo[] = {"bar", ...} declarations.
4623 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4624 WARN("STATIC_CONST_CHAR_ARRAY",
4625 "char * array declaration might be better as static const\n" .
4629 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4630 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4632 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4634 if (WARN("ARRAY_SIZE",
4635 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4637 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4642 # check for function declarations without arguments like "int foo()"
4643 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4644 if (ERROR("FUNCTION_WITHOUT_ARGS",
4645 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4647 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4651 # check for new typedefs, only function parameters and sparse annotations
4653 if ($line =~ /\btypedef\s/ &&
4654 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4655 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4656 $line !~ /\b$typeTypedefs\b/ &&
4657 $line !~ /\b__bitwise\b/) {
4658 WARN("NEW_TYPEDEFS",
4659 "do not add new typedefs\n" . $herecurr);
4662 # * goes on variable not on type
4664 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4666 my ($ident, $from, $to) = ($1, $2, $2);
4668 # Should start with a space.
4669 $to =~ s/^(\S)/ $1/;
4670 # Should not end with a space.
4672 # '*'s should not have spaces between.
4673 while ($to =~ s/\*\s+\*/\*\*/) {
4676 ## print "1: from<$from> to<$to> ident<$ident>\n";
4678 if (ERROR("POINTER_LOCATION",
4679 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4681 my $sub_from = $ident;
4682 my $sub_to = $ident;
4683 $sub_to =~ s/\Q$from\E/$to/;
4684 $fixed[$fixlinenr] =~
4685 s@\Q$sub_from\E@$sub_to@;
4689 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4691 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4693 # Should start with a space.
4694 $to =~ s/^(\S)/ $1/;
4695 # Should not end with a space.
4697 # '*'s should not have spaces between.
4698 while ($to =~ s/\*\s+\*/\*\*/) {
4700 # Modifiers should have spaces.
4701 $to =~ s/(\b$Modifier$)/$1 /;
4703 ## print "2: from<$from> to<$to> ident<$ident>\n";
4704 if ($from ne $to && $ident !~ /^$Modifier$/) {
4705 if (ERROR("POINTER_LOCATION",
4706 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4709 my $sub_from = $match;
4710 my $sub_to = $match;
4711 $sub_to =~ s/\Q$from\E/$to/;
4712 $fixed[$fixlinenr] =~
4713 s@\Q$sub_from\E@$sub_to@;
4718 # avoid BUG() or BUG_ON()
4719 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4720 my $msg_level = \&WARN;
4721 $msg_level = \&CHK if ($file);
4722 &{$msg_level}("AVOID_BUG",
4723 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4726 # avoid LINUX_VERSION_CODE
4727 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4728 WARN("LINUX_VERSION_CODE",
4729 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4732 # check for uses of printk_ratelimit
4733 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4734 WARN("PRINTK_RATELIMITED",
4735 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4738 # printk should use KERN_* levels
4739 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4740 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4741 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4744 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4745 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4749 $modifier = "" if (!defined($modifier));
4750 my $level = lc($orig);
4751 $level = "warn" if ($level eq "warning");
4752 my $level2 = $level;
4753 $level2 = "dbg" if ($level eq "debug");
4754 $level .= $modifier;
4755 $level2 .= $modifier;
4756 WARN("PREFER_PR_LEVEL",
4757 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4760 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4761 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4763 my $level = lc($orig);
4764 $level = "warn" if ($level eq "warning");
4765 $level = "dbg" if ($level eq "debug");
4766 WARN("PREFER_DEV_LEVEL",
4767 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4770 # trace_printk should not be used in production code.
4771 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4772 WARN("TRACE_PRINTK",
4773 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4776 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4777 # number of false positives, but assembly files are not checked, so at
4778 # least the arch entry code will not trigger this warning.
4779 if ($line =~ /\bENOSYS\b/) {
4781 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4784 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4785 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4786 # Similarly to ENOSYS warning a small number of false positives is expected.
4787 if (!$file && $line =~ /\bENOTSUPP\b/) {
4788 if (WARN("ENOTSUPP",
4789 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4791 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4795 # function brace can't be on same line, except for #defines of do while,
4796 # or if closed on same line
4797 if ($perl_version_ok &&
4798 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4799 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4801 if (ERROR("OPEN_BRACE",
4802 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4804 fix_delete_line($fixlinenr, $rawline);
4805 my $fixed_line = $rawline;
4806 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4809 fix_insert_line($fixlinenr, ltrim($line1));
4810 fix_insert_line($fixlinenr, "\+{");
4811 if ($line2 !~ /^\s*$/) {
4812 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4817 # open braces for enum, union and struct go on the same line.
4818 if ($line =~ /^.\s*{/ &&
4819 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4820 if (ERROR("OPEN_BRACE",
4821 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4822 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4823 fix_delete_line($fixlinenr - 1, $prevrawline);
4824 fix_delete_line($fixlinenr, $rawline);
4825 my $fixedline = rtrim($prevrawline) . " {";
4826 fix_insert_line($fixlinenr, $fixedline);
4827 $fixedline = $rawline;
4828 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4829 if ($fixedline !~ /^\+\s*$/) {
4830 fix_insert_line($fixlinenr, $fixedline);
4835 # missing space after union, struct or enum definition
4836 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4838 "missing space after $1 definition\n" . $herecurr) &&
4840 $fixed[$fixlinenr] =~
4841 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4845 # Function pointer declarations
4846 # check spacing between type, funcptr, and args
4847 # canonical declaration is "type (*funcptr)(args...)"
4848 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4850 my $pre_pointer_space = $2;
4851 my $post_pointer_space = $3;
4853 my $post_funcname_space = $5;
4854 my $pre_args_space = $6;
4856 # the $Declare variable will capture all spaces after the type
4857 # so check it for a missing trailing missing space but pointer return types
4858 # don't need a space so don't warn for those.
4859 my $post_declare_space = "";
4860 if ($declare =~ /(\s+)$/) {
4861 $post_declare_space = $1;
4862 $declare = rtrim($declare);
4864 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4866 "missing space after return type\n" . $herecurr);
4867 $post_declare_space = " ";
4870 # unnecessary space "type (*funcptr)(args...)"
4871 # This test is not currently implemented because these declarations are
4873 # int foo(int bar, ...)
4874 # and this is form shouldn't/doesn't generate a checkpatch warning.
4876 # elsif ($declare =~ /\s{2,}$/) {
4878 # "Multiple spaces after return type\n" . $herecurr);
4881 # unnecessary space "type ( *funcptr)(args...)"
4882 if (defined $pre_pointer_space &&
4883 $pre_pointer_space =~ /^\s/) {
4885 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4888 # unnecessary space "type (* funcptr)(args...)"
4889 if (defined $post_pointer_space &&
4890 $post_pointer_space =~ /^\s/) {
4892 "Unnecessary space before function pointer name\n" . $herecurr);
4895 # unnecessary space "type (*funcptr )(args...)"
4896 if (defined $post_funcname_space &&
4897 $post_funcname_space =~ /^\s/) {
4899 "Unnecessary space after function pointer name\n" . $herecurr);
4902 # unnecessary space "type (*funcptr) (args...)"
4903 if (defined $pre_args_space &&
4904 $pre_args_space =~ /^\s/) {
4906 "Unnecessary space before function pointer arguments\n" . $herecurr);
4909 if (show_type("SPACING") && $fix) {
4910 $fixed[$fixlinenr] =~
4911 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4915 # check for spacing round square brackets; allowed:
4916 # 1. with a type on the left -- int [] a;
4917 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4918 # 3. inside a curly brace -- = { [0...10] = 5 }
4919 while ($line =~ /(.*?\s)\[/g) {
4920 my ($where, $prefix) = ($-[1], $1);
4921 if ($prefix !~ /$Type\s+$/ &&
4922 ($where != 0 || $prefix !~ /^.\s+$/) &&
4923 $prefix !~ /[{,:]\s+$/) {
4924 if (ERROR("BRACKET_SPACE",
4925 "space prohibited before open square bracket '['\n" . $herecurr) &&
4927 $fixed[$fixlinenr] =~
4928 s/^(\+.*?)\s+\[/$1\[/;
4933 # check for spaces between functions and their parentheses.
4934 while ($line =~ /($Ident)\s+\(/g) {
4936 my $ctx_before = substr($line, 0, $-[1]);
4937 my $ctx = "$ctx_before$name";
4939 # Ignore those directives where spaces _are_ permitted.
4941 if|for|while|switch|return|case|
4942 volatile|__volatile__|
4943 __attribute__|format|__extension__|
4946 # cpp #define statements have non-optional spaces, ie
4947 # if there is a space between the name and the open
4948 # parenthesis it is simply not a parameter group.
4949 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4951 # cpp #elif statement condition may start with a (
4952 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4954 # If this whole things ends with a type its most
4955 # likely a typedef for a function.
4956 } elsif ($ctx =~ /$Type$/) {
4960 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4962 $fixed[$fixlinenr] =~
4963 s/\b$name\s+\(/$name\(/;
4968 # Check operator spacing.
4969 if (!($line=~/\#\s*include/)) {
4970 my $fixed_line = "";
4974 <<=|>>=|<=|>=|==|!=|
4975 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4976 =>|->|<<|>>|<|>|=|!|~|
4977 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4980 my @elements = split(/($ops|;)/, $opline);
4982 ## print("element count: <" . $#elements . ">\n");
4983 ## foreach my $el (@elements) {
4984 ## print("el: <$el>\n");
4987 my @fix_elements = ();
4990 foreach my $el (@elements) {
4991 push(@fix_elements, substr($rawline, $off, length($el)));
4992 $off += length($el);
4997 my $blank = copy_spacing($opline);
4998 my $last_after = -1;
5000 for (my $n = 0; $n < $#elements; $n += 2) {
5002 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5004 ## print("n: <$n> good: <$good>\n");
5006 $off += length($elements[$n]);
5008 # Pick up the preceding and succeeding characters.
5009 my $ca = substr($opline, 0, $off);
5011 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5012 $cc = substr($opline, $off + length($elements[$n + 1]));
5014 my $cb = "$ca$;$cc";
5017 $a = 'V' if ($elements[$n] ne '');
5018 $a = 'W' if ($elements[$n] =~ /\s$/);
5019 $a = 'C' if ($elements[$n] =~ /$;$/);
5020 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5021 $a = 'O' if ($elements[$n] eq '');
5022 $a = 'E' if ($ca =~ /^\s*$/);
5024 my $op = $elements[$n + 1];
5027 if (defined $elements[$n + 2]) {
5028 $c = 'V' if ($elements[$n + 2] ne '');
5029 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5030 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5031 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5032 $c = 'O' if ($elements[$n + 2] eq '');
5033 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5038 my $ctx = "${a}x${c}";
5040 my $at = "(ctx:$ctx)";
5042 my $ptr = substr($blank, 0, $off) . "^";
5043 my $hereptr = "$hereline$ptr\n";
5045 # Pull out the value of this operator.
5046 my $op_type = substr($curr_values, $off + 1, 1);
5048 # Get the full operator variant.
5049 my $opv = $op . substr($curr_vars, $off, 1);
5051 # Ignore operators passed as parameters.
5052 if ($op_type ne 'V' &&
5053 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5056 # } elsif ($op =~ /^$;+$/) {
5058 # ; should have either the end of line or a space or \ after it
5059 } elsif ($op eq ';') {
5060 if ($ctx !~ /.x[WEBC]/ &&
5061 $cc !~ /^\\/ && $cc !~ /^;/) {
5062 if (ERROR("SPACING",
5063 "space required after that '$op' $at\n" . $hereptr)) {
5064 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5070 } elsif ($op eq '//') {
5072 # : when part of a bitfield
5073 } elsif ($opv eq ':B') {
5074 # skip the bitfield test for now
5078 } elsif ($op eq '->') {
5079 if ($ctx =~ /Wx.|.xW/) {
5080 if (ERROR("SPACING",
5081 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5082 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5083 if (defined $fix_elements[$n + 2]) {
5084 $fix_elements[$n + 2] =~ s/^\s+//;
5090 # , must not have a space before and must have a space on the right.
5091 } elsif ($op eq ',') {
5092 my $rtrim_before = 0;
5093 my $space_after = 0;
5094 if ($ctx =~ /Wx./) {
5095 if (ERROR("SPACING",
5096 "space prohibited before that '$op' $at\n" . $hereptr)) {
5101 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5102 if (ERROR("SPACING",
5103 "space required after that '$op' $at\n" . $hereptr)) {
5109 if ($rtrim_before || $space_after) {
5110 if ($rtrim_before) {
5111 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5113 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5120 # '*' as part of a type definition -- reported already.
5121 } elsif ($opv eq '*_') {
5122 #warn "'*' is part of type\n";
5124 # unary operators should have a space before and
5125 # none after. May be left adjacent to another
5126 # unary operator, or a cast
5127 } elsif ($op eq '!' || $op eq '~' ||
5128 $opv eq '*U' || $opv eq '-U' ||
5129 $opv eq '&U' || $opv eq '&&U') {
5130 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5131 if (ERROR("SPACING",
5132 "space required before that '$op' $at\n" . $hereptr)) {
5133 if ($n != $last_after + 2) {
5134 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5139 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5140 # A unary '*' may be const
5142 } elsif ($ctx =~ /.xW/) {
5143 if (ERROR("SPACING",
5144 "space prohibited after that '$op' $at\n" . $hereptr)) {
5145 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5146 if (defined $fix_elements[$n + 2]) {
5147 $fix_elements[$n + 2] =~ s/^\s+//;
5153 # unary ++ and unary -- are allowed no space on one side.
5154 } elsif ($op eq '++' or $op eq '--') {
5155 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5156 if (ERROR("SPACING",
5157 "space required one side of that '$op' $at\n" . $hereptr)) {
5158 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5162 if ($ctx =~ /Wx[BE]/ ||
5163 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5164 if (ERROR("SPACING",
5165 "space prohibited before that '$op' $at\n" . $hereptr)) {
5166 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5170 if ($ctx =~ /ExW/) {
5171 if (ERROR("SPACING",
5172 "space prohibited after that '$op' $at\n" . $hereptr)) {
5173 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5174 if (defined $fix_elements[$n + 2]) {
5175 $fix_elements[$n + 2] =~ s/^\s+//;
5181 # << and >> may either have or not have spaces both sides
5182 } elsif ($op eq '<<' or $op eq '>>' or
5183 $op eq '&' or $op eq '^' or $op eq '|' or
5184 $op eq '+' or $op eq '-' or
5185 $op eq '*' or $op eq '/' or
5189 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5191 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5192 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5193 $fix_elements[$n + 2] =~ s/^\s+//;
5196 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5198 "space preferred before that '$op' $at\n" . $hereptr)) {
5199 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5203 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5204 if (ERROR("SPACING",
5205 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5206 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5207 if (defined $fix_elements[$n + 2]) {
5208 $fix_elements[$n + 2] =~ s/^\s+//;
5214 # A colon needs no spaces before when it is
5215 # terminating a case value or a label.
5216 } elsif ($opv eq ':C' || $opv eq ':L') {
5217 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5218 if (ERROR("SPACING",
5219 "space prohibited before that '$op' $at\n" . $hereptr)) {
5220 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5225 # All the others need spaces both sides.
5226 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5229 # Ignore email addresses <foo@bar>
5231 $cc =~ /^\S+\@\S+>/) ||
5233 $ca =~ /<\S+\@\S+$/))
5238 # for asm volatile statements
5239 # ignore a colon with another
5240 # colon immediately before or after
5242 ($ca =~ /:$/ || $cc =~ /^:/)) {
5246 # messages are ERROR, but ?: are CHK
5248 my $msg_level = \&ERROR;
5249 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5251 if (&{$msg_level}("SPACING",
5252 "spaces required around that '$op' $at\n" . $hereptr)) {
5253 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5254 if (defined $fix_elements[$n + 2]) {
5255 $fix_elements[$n + 2] =~ s/^\s+//;
5261 $off += length($elements[$n + 1]);
5263 ## print("n: <$n> GOOD: <$good>\n");
5265 $fixed_line = $fixed_line . $good;
5268 if (($#elements % 2) == 0) {
5269 $fixed_line = $fixed_line . $fix_elements[$#elements];
5272 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5273 $fixed[$fixlinenr] = $fixed_line;
5279 # check for whitespace before a non-naked semicolon
5280 if ($line =~ /^\+.*\S\s+;\s*$/) {
5282 "space prohibited before semicolon\n" . $herecurr) &&
5284 1 while $fixed[$fixlinenr] =~
5285 s/^(\+.*\S)\s+;/$1;/;
5289 # check for multiple assignments
5290 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5291 CHK("MULTIPLE_ASSIGNMENTS",
5292 "multiple assignments should be avoided\n" . $herecurr);
5295 ## # check for multiple declarations, allowing for a function declaration
5297 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5298 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5300 ## # Remove any bracketed sections to ensure we do not
5301 ## # falsely report the parameters of functions.
5303 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5305 ## if ($ln =~ /,/) {
5306 ## WARN("MULTIPLE_DECLARATION",
5307 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5311 #need space before brace following if, while, etc
5312 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5313 $line =~ /\b(?:else|do)\{/) {
5314 if (ERROR("SPACING",
5315 "space required before the open brace '{'\n" . $herecurr) &&
5317 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5321 ## # check for blank lines before declarations
5322 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5323 ## $prevrawline =~ /^.\s*$/) {
5325 ## "No blank lines before declarations\n" . $hereprev);
5329 # closing brace should have a space following it when it has anything
5331 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5332 if (ERROR("SPACING",
5333 "space required after that close brace '}'\n" . $herecurr) &&
5335 $fixed[$fixlinenr] =~
5336 s/}((?!(?:,|;|\)))\S)/} $1/;
5340 # check spacing on square brackets
5341 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5342 if (ERROR("SPACING",
5343 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5345 $fixed[$fixlinenr] =~
5349 if ($line =~ /\s\]/) {
5350 if (ERROR("SPACING",
5351 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5353 $fixed[$fixlinenr] =~
5358 # check spacing on parentheses
5359 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5360 $line !~ /for\s*\(\s+;/) {
5361 if (ERROR("SPACING",
5362 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5364 $fixed[$fixlinenr] =~
5368 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5369 $line !~ /for\s*\(.*;\s+\)/ &&
5370 $line !~ /:\s+\)/) {
5371 if (ERROR("SPACING",
5372 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5374 $fixed[$fixlinenr] =~
5379 # check unnecessary parentheses around addressof/dereference single $Lvals
5380 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5382 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5384 if (CHK("UNNECESSARY_PARENTHESES",
5385 "Unnecessary parentheses around $var\n" . $herecurr) &&
5387 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5391 # check for unnecessary parentheses around function pointer uses
5392 # ie: (foo->bar)(); should be foo->bar();
5393 # but not "if (foo->bar) (" to avoid some false positives
5394 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5396 if (CHK("UNNECESSARY_PARENTHESES",
5397 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5399 my $var2 = deparenthesize($var);
5401 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5405 # check for unnecessary parentheses around comparisons in if uses
5406 # when !drivers/staging or command-line uses --strict
5407 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5408 $perl_version_ok && defined($stat) &&
5409 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5411 my $test = substr($2, 1, -1);
5413 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5415 # avoid parentheses around potential macro args
5416 next if ($match =~ /^\s*\w+\s*$/);
5417 if (!defined($herectx)) {
5418 $herectx = $here . "\n";
5419 my $cnt = statement_rawlines($if_stat);
5420 for (my $n = 0; $n < $cnt; $n++) {
5421 my $rl = raw_line($linenr, $n);
5422 $herectx .= $rl . "\n";
5423 last if $rl =~ /^[ \+].*\{/;
5426 CHK("UNNECESSARY_PARENTHESES",
5427 "Unnecessary parentheses around '$match'\n" . $herectx);
5431 # check that goto labels aren't indented (allow a single space indentation)
5432 # and ignore bitfield definitions like foo:1
5433 # Strictly, labels can have whitespace after the identifier and before the :
5434 # but this is not allowed here as many ?: uses would appear to be labels
5435 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5436 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5437 $sline !~ /^.\s+default:/) {
5438 if (WARN("INDENTED_LABEL",
5439 "labels should not be indented\n" . $herecurr) &&
5441 $fixed[$fixlinenr] =~
5446 # check if a statement with a comma should be two statements like:
5447 # foo = bar(), /* comma should be semicolon */
5449 if (defined($stat) &&
5450 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5451 my $cnt = statement_rawlines($stat);
5452 my $herectx = get_stat_here($linenr, $cnt, $here);
5453 WARN("SUSPECT_COMMA_SEMICOLON",
5454 "Possible comma where semicolon could be used\n" . $herectx);
5457 # return is not a function
5458 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5460 if ($perl_version_ok &&
5461 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5463 $value = deparenthesize($value);
5464 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5465 ERROR("RETURN_PARENTHESES",
5466 "return is not a function, parentheses are not required\n" . $herecurr);
5468 } elsif ($spacing !~ /\s+/) {
5470 "space required before the open parenthesis '('\n" . $herecurr);
5474 # unnecessary return in a void function
5475 # at end-of-function, with the previous line a single leading tab, then return;
5476 # and the line before that not a goto label target like "out:"
5477 if ($sline =~ /^[ \+]}\s*$/ &&
5478 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5480 $lines[$linenr - 3] =~ /^[ +]/ &&
5481 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5483 "void function return statements are not generally useful\n" . $hereprev);
5486 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5487 if ($perl_version_ok &&
5488 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5489 my $openparens = $1;
5490 my $count = $openparens =~ tr@\(@\(@;
5492 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5493 my $comp = $4; #Not $1 because of $LvalOrFunc
5494 $msg = " - maybe == should be = ?" if ($comp eq "==");
5495 WARN("UNNECESSARY_PARENTHESES",
5496 "Unnecessary parentheses$msg\n" . $herecurr);
5500 # comparisons with a constant or upper case identifier on the left
5501 # avoid cases like "foo + BAR < baz"
5502 # only fix matches surrounded by parentheses to avoid incorrect
5503 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5504 if ($perl_version_ok &&
5505 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5510 my $newcomp = $comp;
5511 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5512 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5513 WARN("CONSTANT_COMPARISON",
5514 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5518 } elsif ($comp eq "<=") {
5520 } elsif ($comp eq ">") {
5522 } elsif ($comp eq ">=") {
5525 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5529 # Return of what appears to be an errno should normally be negative
5530 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5532 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5533 WARN("USE_NEGATIVE_ERRNO",
5534 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5538 # Need a space before open parenthesis after if, while etc
5539 if ($line =~ /\b(if|while|for|switch)\(/) {
5540 if (ERROR("SPACING",
5541 "space required before the open parenthesis '('\n" . $herecurr) &&
5543 $fixed[$fixlinenr] =~
5544 s/\b(if|while|for|switch)\(/$1 \(/;
5548 # Check for illegal assignment in if conditional -- and check for trailing
5549 # statements after the conditional.
5550 if ($line =~ /do\s*(?!{)/) {
5551 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5552 ctx_statement_block($linenr, $realcnt, 0)
5553 if (!defined $stat);
5554 my ($stat_next) = ctx_statement_block($line_nr_next,
5555 $remain_next, $off_next);
5556 $stat_next =~ s/\n./\n /g;
5557 ##print "stat<$stat> stat_next<$stat_next>\n";
5559 if ($stat_next =~ /^\s*while\b/) {
5560 # If the statement carries leading newlines,
5561 # then count those as offsets.
5563 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5565 statement_rawlines($whitespace) - 1;
5567 $suppress_whiletrailers{$line_nr_next +
5571 if (!defined $suppress_whiletrailers{$linenr} &&
5572 defined($stat) && defined($cond) &&
5573 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5574 my ($s, $c) = ($stat, $cond);
5575 my $fixed_assign_in_if = 0;
5577 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5578 if (ERROR("ASSIGN_IN_IF",
5579 "do not use assignment in if condition\n" . $herecurr) &&
5580 $fix && $perl_version_ok) {
5581 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5589 fix_delete_line($fixlinenr, $rawline);
5590 fix_insert_line($fixlinenr, "$space$statement;");
5591 my $newline = "${space}if (";
5592 $newline .= '!' if defined($not);
5593 $newline .= '(' if (defined $not && defined($test) && defined($against));
5594 $newline .= "$assigned";
5595 $newline .= " $test $against" if (defined($test) && defined($against));
5596 $newline .= ')' if (defined $not && defined($test) && defined($against));
5598 $newline .= " {" if (defined($brace));
5599 fix_insert_line($fixlinenr + 1, $newline);
5600 $fixed_assign_in_if = 1;
5605 # Find out what is on the end of the line after the
5607 substr($s, 0, length($c), '');
5609 $s =~ s/$;//g; # Remove any comments
5610 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5611 $c !~ /}\s*while\s*/)
5613 # Find out how long the conditional actually is.
5614 my @newlines = ($c =~ /\n/gs);
5615 my $cond_lines = 1 + $#newlines;
5618 $stat_real = raw_line($linenr, $cond_lines)
5619 . "\n" if ($cond_lines);
5620 if (defined($stat_real) && $cond_lines > 1) {
5621 $stat_real = "[...]\n$stat_real";
5624 if (ERROR("TRAILING_STATEMENTS",
5625 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5626 !$fixed_assign_in_if &&
5628 $fix && $perl_version_ok &&
5629 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5632 my $rest = rtrim($4);
5633 if ($rest =~ /;$/) {
5634 $fixed[$fixlinenr] = "\+$indent$test";
5635 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5641 # Check for bitwise tests written as boolean
5653 WARN("HEXADECIMAL_BOOLEAN_TEST",
5654 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5657 # if and else should not have general statements after it
5658 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5660 $s =~ s/$;//g; # Remove any comments
5661 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5662 ERROR("TRAILING_STATEMENTS",
5663 "trailing statements should be on next line\n" . $herecurr);
5666 # if should not continue a brace
5667 if ($line =~ /}\s*if\b/) {
5668 ERROR("TRAILING_STATEMENTS",
5669 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5672 # case and default should not have general statements after them
5673 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5675 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5679 ERROR("TRAILING_STATEMENTS",
5680 "trailing statements should be on next line\n" . $herecurr);
5683 # Check for }<nl>else {, these must be at the same
5684 # indent level to be relevant to each other.
5685 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5686 $previndent == $indent) {
5687 if (ERROR("ELSE_AFTER_BRACE",
5688 "else should follow close brace '}'\n" . $hereprev) &&
5689 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5690 fix_delete_line($fixlinenr - 1, $prevrawline);
5691 fix_delete_line($fixlinenr, $rawline);
5692 my $fixedline = $prevrawline;
5693 $fixedline =~ s/}\s*$//;
5694 if ($fixedline !~ /^\+\s*$/) {
5695 fix_insert_line($fixlinenr, $fixedline);
5697 $fixedline = $rawline;
5698 $fixedline =~ s/^(.\s*)else/$1} else/;
5699 fix_insert_line($fixlinenr, $fixedline);
5703 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5704 $previndent == $indent) {
5705 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5707 # Find out what is on the end of the line after the
5709 substr($s, 0, length($c), '');
5712 if ($s =~ /^\s*;/) {
5713 if (ERROR("WHILE_AFTER_BRACE",
5714 "while should follow close brace '}'\n" . $hereprev) &&
5715 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5716 fix_delete_line($fixlinenr - 1, $prevrawline);
5717 fix_delete_line($fixlinenr, $rawline);
5718 my $fixedline = $prevrawline;
5719 my $trailing = $rawline;
5720 $trailing =~ s/^\+//;
5721 $trailing = trim($trailing);
5722 $fixedline =~ s/}\s*$/} $trailing/;
5723 fix_insert_line($fixlinenr, $fixedline);
5728 #Specific variable tests
5729 while ($line =~ m{($Constant|$Lval)}g) {
5733 if ($var !~ /^$Constant$/ &&
5734 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5735 #Ignore some autogenerated defines and enum values
5736 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5737 #Ignore Page<foo> variants
5738 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5739 #Ignore SI style variants like nS, mV and dB
5740 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5741 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5742 #Ignore some three character SI units explicitly, like MiB and KHz
5743 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5744 while ($var =~ m{\b($Ident)}g) {
5746 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5748 seed_camelcase_includes();
5749 if (!$file && !$camelcase_file_seeded) {
5750 seed_camelcase_file($realfile);
5751 $camelcase_file_seeded = 1;
5754 if (!defined $camelcase{$word}) {
5755 $camelcase{$word} = 1;
5757 "Avoid CamelCase: <$word>\n" . $herecurr);
5763 #no spaces allowed after \ in define
5764 if ($line =~ /\#\s*define.*\\\s+$/) {
5765 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5766 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5768 $fixed[$fixlinenr] =~ s/\s+$//;
5772 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5773 # itself <asm/foo.h> (uses RAW line)
5774 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5776 my $checkfile = "include/linux/$file";
5777 if (-f "$root/$checkfile" &&
5778 $realfile ne $checkfile &&
5779 $1 !~ /$allowed_asm_includes/)
5781 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5782 if ($asminclude > 0) {
5783 if ($realfile =~ m{^arch/}) {
5784 CHK("ARCH_INCLUDE_LINUX",
5785 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5787 WARN("INCLUDE_LINUX",
5788 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5794 # multi-statement macros should be enclosed in a do while loop, grab the
5795 # first statement and ensure its the whole macro if its not enclosed
5796 # in a known good container
5797 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5798 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5801 my ($off, $dstat, $dcond, $rest);
5803 my $has_flow_statement = 0;
5804 my $has_arg_concat = 0;
5805 ($dstat, $dcond, $ln, $cnt, $off) =
5806 ctx_statement_block($linenr, $realcnt, 0);
5808 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5809 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5811 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5812 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5814 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5815 my $define_args = $1;
5816 my $define_stmt = $dstat;
5819 if (defined $define_args && $define_args ne "") {
5820 $define_args = substr($define_args, 1, length($define_args) - 2);
5821 $define_args =~ s/\s*//g;
5822 $define_args =~ s/\\\+?//g;
5823 @def_args = split(",", $define_args);
5827 $dstat =~ s/\\\n.//g;
5828 $dstat =~ s/^\s*//s;
5829 $dstat =~ s/\s*$//s;
5831 # Flatten any parentheses and braces
5832 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5833 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5834 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5838 # Flatten any obvious string concatenation.
5839 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5840 $dstat =~ s/$Ident\s*($String)/$1/)
5844 # Make asm volatile uses seem like a generic function
5845 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5847 my $exceptions = qr{
5860 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5863 my $stmt_cnt = statement_rawlines($ctx);
5864 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5867 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5868 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5869 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5870 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5871 $dstat !~ /$exceptions/ &&
5872 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5873 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5874 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5875 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5876 $dstat !~ /^for\s*$Constant$/ && # for (...)
5877 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5878 $dstat !~ /^do\s*{/ && # do {...
5879 $dstat !~ /^\(\{/ && # ({...
5880 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5882 if ($dstat =~ /^\s*if\b/) {
5883 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5884 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5885 } elsif ($dstat =~ /;/) {
5886 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5887 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5889 ERROR("COMPLEX_MACRO",
5890 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5895 # Make $define_stmt single line, comment-free, etc
5896 my @stmt_array = split('\n', $define_stmt);
5899 foreach my $l (@stmt_array) {
5904 } elsif ($l =~ /^[\+ ]/) {
5905 $define_stmt .= substr($l, 1);
5908 $define_stmt =~ s/$;//g;
5909 $define_stmt =~ s/\s+/ /g;
5910 $define_stmt = trim($define_stmt);
5912 # check if any macro arguments are reused (ignore '...' and 'type')
5913 foreach my $arg (@def_args) {
5914 next if ($arg =~ /\.\.\./);
5915 next if ($arg =~ /^type$/i);
5916 my $tmp_stmt = $define_stmt;
5917 $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;
5918 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5919 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5920 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5922 CHK("MACRO_ARG_REUSE",
5923 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5925 # check if any macro arguments may have other precedence issues
5926 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5927 ((defined($1) && $1 ne ',') ||
5928 (defined($2) && $2 ne ','))) {
5929 CHK("MACRO_ARG_PRECEDENCE",
5930 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5934 # check for macros with flow control, but without ## concatenation
5935 # ## concatenation is commonly a macro that defines a function so ignore those
5936 if ($has_flow_statement && !$has_arg_concat) {
5937 my $cnt = statement_rawlines($ctx);
5938 my $herectx = get_stat_here($linenr, $cnt, $here);
5940 WARN("MACRO_WITH_FLOW_CONTROL",
5941 "Macros with flow control statements should be avoided\n" . "$herectx");
5944 # check for line continuations outside of #defines, preprocessor #, and asm
5947 if ($prevline !~ /^..*\\$/ &&
5948 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5949 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5950 $line =~ /^\+.*\\$/) {
5951 WARN("LINE_CONTINUATIONS",
5952 "Avoid unnecessary line continuations\n" . $herecurr);
5956 # do {} while (0) macro tests:
5957 # single-statement macros do not need to be enclosed in do while (0) loop,
5958 # macro should not end with a semicolon
5959 if ($perl_version_ok &&
5960 $realfile !~ m@/vmlinux.lds.h$@ &&
5961 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5964 my ($off, $dstat, $dcond, $rest);
5966 ($dstat, $dcond, $ln, $cnt, $off) =
5967 ctx_statement_block($linenr, $realcnt, 0);
5970 $dstat =~ s/\\\n.//g;
5973 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5978 my $cnt = statement_rawlines($ctx);
5979 my $herectx = get_stat_here($linenr, $cnt, $here);
5981 if (($stmts =~ tr/;/;/) == 1 &&
5982 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5983 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5984 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5986 if (defined $semis && $semis ne "") {
5987 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5988 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5990 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5992 my $cnt = statement_rawlines($ctx);
5993 my $herectx = get_stat_here($linenr, $cnt, $here);
5995 WARN("TRAILING_SEMICOLON",
5996 "macros should not use a trailing semicolon\n" . "$herectx");
6000 # check for redundant bracing round if etc
6001 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6002 my ($level, $endln, @chunks) =
6003 ctx_statement_full($linenr, $realcnt, 1);
6004 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6005 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6006 if ($#chunks > 0 && $level == 0) {
6010 my $herectx = $here . "\n";
6011 my $ln = $linenr - 1;
6012 for my $chunk (@chunks) {
6013 my ($cond, $block) = @{$chunk};
6015 # If the condition carries leading newlines, then count those as offsets.
6016 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6017 my $offset = statement_rawlines($whitespace) - 1;
6019 $allowed[$allow] = 0;
6020 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6022 # We have looked at and allowed this specific line.
6023 $suppress_ifbraces{$ln + $offset} = 1;
6025 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6026 $ln += statement_rawlines($block) - 1;
6028 substr($block, 0, length($cond), '');
6030 $seen++ if ($block =~ /^\s*{/);
6032 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6033 if (statement_lines($cond) > 1) {
6034 #print "APW: ALLOWED: cond<$cond>\n";
6035 $allowed[$allow] = 1;
6037 if ($block =~/\b(?:if|for|while)\b/) {
6038 #print "APW: ALLOWED: block<$block>\n";
6039 $allowed[$allow] = 1;
6041 if (statement_block_size($block) > 1) {
6042 #print "APW: ALLOWED: lines block<$block>\n";
6043 $allowed[$allow] = 1;
6048 my $sum_allowed = 0;
6049 foreach (@allowed) {
6052 if ($sum_allowed == 0) {
6054 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6055 } elsif ($sum_allowed != $allow &&
6058 "braces {} should be used on all arms of this statement\n" . $herectx);
6063 if (!defined $suppress_ifbraces{$linenr - 1} &&
6064 $line =~ /\b(if|while|for|else)\b/) {
6067 # Check the pre-context.
6068 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6069 #print "APW: ALLOWED: pre<$1>\n";
6073 my ($level, $endln, @chunks) =
6074 ctx_statement_full($linenr, $realcnt, $-[0]);
6076 # Check the condition.
6077 my ($cond, $block) = @{$chunks[0]};
6078 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6079 if (defined $cond) {
6080 substr($block, 0, length($cond), '');
6082 if (statement_lines($cond) > 1) {
6083 #print "APW: ALLOWED: cond<$cond>\n";
6086 if ($block =~/\b(?:if|for|while)\b/) {
6087 #print "APW: ALLOWED: block<$block>\n";
6090 if (statement_block_size($block) > 1) {
6091 #print "APW: ALLOWED: lines block<$block>\n";
6094 # Check the post-context.
6095 if (defined $chunks[1]) {
6096 my ($cond, $block) = @{$chunks[1]};
6097 if (defined $cond) {
6098 substr($block, 0, length($cond), '');
6100 if ($block =~ /^\s*\{/) {
6101 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6105 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6106 my $cnt = statement_rawlines($block);
6107 my $herectx = get_stat_here($linenr, $cnt, $here);
6110 "braces {} are not necessary for single statement blocks\n" . $herectx);
6114 # check for single line unbalanced braces
6115 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6116 $sline =~ /^.\s*else\s*\{\s*$/) {
6117 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6120 # check for unnecessary blank lines around braces
6121 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6123 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6124 $fix && $prevrawline =~ /^\+/) {
6125 fix_delete_line($fixlinenr - 1, $prevrawline);
6128 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6130 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6132 fix_delete_line($fixlinenr, $rawline);
6136 # no volatiles please
6137 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6138 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6140 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6143 # Check for user-visible strings broken across lines, which breaks the ability
6144 # to grep for the string. Make exceptions when the previous string ends in a
6145 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6146 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6147 if ($line =~ /^\+\s*$String/ &&
6148 $prevline =~ /"\s*$/ &&
6149 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6150 if (WARN("SPLIT_STRING",
6151 "quoted string split across lines\n" . $hereprev) &&
6153 $prevrawline =~ /^\+.*"\s*$/ &&
6154 $last_coalesced_string_linenr != $linenr - 1) {
6155 my $extracted_string = get_quoted_string($line, $rawline);
6156 my $comma_close = "";
6157 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6161 fix_delete_line($fixlinenr - 1, $prevrawline);
6162 fix_delete_line($fixlinenr, $rawline);
6163 my $fixedline = $prevrawline;
6164 $fixedline =~ s/"\s*$//;
6165 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6166 fix_insert_line($fixlinenr - 1, $fixedline);
6167 $fixedline = $rawline;
6168 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6169 if ($fixedline !~ /\+\s*$/) {
6170 fix_insert_line($fixlinenr, $fixedline);
6172 $last_coalesced_string_linenr = $linenr;
6176 # check for missing a space in a string concatenation
6177 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6178 WARN('MISSING_SPACE',
6179 "break quoted strings at a space character\n" . $hereprev);
6182 # check for an embedded function name in a string when the function is known
6183 # This does not work very well for -f --file checking as it depends on patch
6184 # context providing the function name or a single line form for in-file
6185 # function declarations
6186 if ($line =~ /^\+.*$String/ &&
6187 defined($context_function) &&
6188 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6189 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6190 WARN("EMBEDDED_FUNCTION_NAME",
6191 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6194 # check for unnecessary function tracing like uses
6195 # This does not use $logFunctions because there are many instances like
6196 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6197 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6198 if (WARN("TRACING_LOGGING",
6199 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6201 fix_delete_line($fixlinenr, $rawline);
6205 # check for spaces before a quoted newline
6206 if ($rawline =~ /^.*\".*\s\\n/) {
6207 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6208 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6210 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6215 # concatenated string without spaces between elements
6216 if ($line =~ /$String[A-Z_]/ ||
6217 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6218 if (CHK("CONCATENATED_STRING",
6219 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6221 while ($line =~ /($String)/g) {
6222 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6223 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6224 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6229 # uncoalesced string fragments
6230 if ($line =~ /$String\s*[Lu]?"/) {
6231 if (WARN("STRING_FRAGMENTS",
6232 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6234 while ($line =~ /($String)(?=\s*")/g) {
6235 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6236 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6241 # check for non-standard and hex prefixed decimal printf formats
6242 my $show_L = 1; #don't show the same defect twice
6244 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6245 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6246 $string =~ s/%%/__/g;
6248 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6250 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6254 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6256 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6259 # check for 0x<decimal>
6260 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6261 ERROR("PRINTF_0XDECIMAL",
6262 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6266 # check for line continuations in quoted strings with odd counts of "
6267 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6268 WARN("LINE_CONTINUATIONS",
6269 "Avoid line continuations in quoted strings\n" . $herecurr);
6273 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6275 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6279 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6281 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6284 # check for needless "if (<foo>) fn(<foo>)" uses
6285 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6286 my $tested = quotemeta($1);
6287 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6288 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6290 if (WARN('NEEDLESS_IF',
6291 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6294 my $leading_tabs = "";
6295 my $new_leading_tabs = "";
6296 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6301 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6302 $new_leading_tabs = $1;
6303 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6310 fix_delete_line($fixlinenr - 1, $prevrawline);
6311 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6317 # check for unnecessary "Out of Memory" messages
6318 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6319 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6320 (defined $1 || defined $3) &&
6323 my $testline = $lines[$linenr - 3];
6325 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6326 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6328 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6329 $s !~ /\b__GFP_NOWARN\b/ ) {
6331 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6335 # check for logging functions with KERN_<LEVEL>
6336 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6337 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6339 if (WARN("UNNECESSARY_KERN_LEVEL",
6340 "Possible unnecessary $level\n" . $herecurr) &&
6342 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6346 # check for logging continuations
6347 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6348 WARN("LOGGING_CONTINUATION",
6349 "Avoid logging continuation uses where feasible\n" . $herecurr);
6352 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6353 if (defined $stat &&
6354 $line =~ /\b$logFunctions\s*\(/ &&
6355 index($stat, '"') >= 0) {
6356 my $lc = $stat =~ tr@\n@@;
6357 $lc = $lc + $linenr;
6358 my $stat_real = get_stat_real($linenr, $lc);
6359 pos($stat_real) = index($stat_real, '"');
6360 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6363 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6364 if (WARN("UNNECESSARY_MODIFIER",
6365 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6366 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6369 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6374 # check for mask then right shift without a parentheses
6375 if ($perl_version_ok &&
6376 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6377 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6378 WARN("MASK_THEN_SHIFT",
6379 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6382 # check for pointer comparisons to NULL
6383 if ($perl_version_ok) {
6384 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6387 $equal = "" if ($4 eq "!=");
6388 if (CHK("COMPARISON_TO_NULL",
6389 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6391 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6396 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6397 if ($line =~ /(\b$InitAttribute\b)/) {
6399 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6402 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6403 ERROR("MISPLACED_INIT",
6404 "$attr should be placed after $var\n" . $herecurr)) ||
6405 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6406 WARN("MISPLACED_INIT",
6407 "$attr should be placed after $var\n" . $herecurr))) &&
6409 $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;
6414 # check for $InitAttributeData (ie: __initdata) with const
6415 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6417 $attr =~ /($InitAttributePrefix)(.*)/;
6418 my $attr_prefix = $1;
6420 if (ERROR("INIT_ATTRIBUTE",
6421 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6423 $fixed[$fixlinenr] =~
6424 s/$InitAttributeData/${attr_prefix}initconst/;
6428 # check for $InitAttributeConst (ie: __initconst) without const
6429 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6431 if (ERROR("INIT_ATTRIBUTE",
6432 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6434 my $lead = $fixed[$fixlinenr] =~
6435 /(^\+\s*(?:static\s+))/;
6437 $lead = "$lead " if ($lead !~ /^\+$/);
6438 $lead = "${lead}const ";
6439 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6443 # check for __read_mostly with const non-pointer (should just be const)
6444 if ($line =~ /\b__read_mostly\b/ &&
6445 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6446 if (ERROR("CONST_READ_MOSTLY",
6447 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6449 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6453 # don't use __constant_<foo> functions outside of include/uapi/
6454 if ($realfile !~ m@^include/uapi/@ &&
6455 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6456 my $constant_func = $1;
6457 my $func = $constant_func;
6458 $func =~ s/^__constant_//;
6459 if (WARN("CONSTANT_CONVERSION",
6460 "$constant_func should be $func\n" . $herecurr) &&
6462 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6466 # prefer usleep_range over udelay
6467 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6469 # ignore udelay's < 10, however
6470 if (! ($delay < 10) ) {
6472 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6474 if ($delay > 2000) {
6476 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6480 # warn about unexpectedly long msleep's
6481 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6484 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6488 # check for comparisons of jiffies
6489 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6490 WARN("JIFFIES_COMPARISON",
6491 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6494 # check for comparisons of get_jiffies_64()
6495 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6496 WARN("JIFFIES_COMPARISON",
6497 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6500 # warn about #ifdefs in C files
6501 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6502 # print "#ifdef in C files should be avoided\n";
6503 # print "$herecurr";
6507 # warn about spacing in #ifdefs
6508 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6509 if (ERROR("SPACING",
6510 "exactly one space required after that #$1\n" . $herecurr) &&
6512 $fixed[$fixlinenr] =~
6513 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6518 # check for spinlock_t definitions without a comment.
6519 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6520 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6522 if (!ctx_has_comment($first_line, $linenr)) {
6523 CHK("UNCOMMENTED_DEFINITION",
6524 "$1 definition without comment\n" . $herecurr);
6527 # check for memory barriers without a comment.
6534 my $barrier_stems = qr{
6542 my $all_barriers = qr{
6544 smp_(?:$barrier_stems)|
6545 virt_(?:$barrier_stems)
6548 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6549 if (!ctx_has_comment($first_line, $linenr)) {
6550 WARN("MEMORY_BARRIER",
6551 "memory barrier without comment\n" . $herecurr);
6555 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6557 if ($realfile !~ m@^include/asm-generic/@ &&
6558 $realfile !~ m@/barrier\.h$@ &&
6559 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6560 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6561 WARN("MEMORY_BARRIER",
6562 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6565 # check for waitqueue_active without a comment.
6566 if ($line =~ /\bwaitqueue_active\s*\(/) {
6567 if (!ctx_has_comment($first_line, $linenr)) {
6568 WARN("WAITQUEUE_ACTIVE",
6569 "waitqueue_active without comment\n" . $herecurr);
6573 # check for data_race without a comment.
6574 if ($line =~ /\bdata_race\s*\(/) {
6575 if (!ctx_has_comment($first_line, $linenr)) {
6577 "data_race without comment\n" . $herecurr);
6581 # check of hardware specific defines
6582 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6584 "architecture specific defines should be avoided\n" . $herecurr);
6587 # check that the storage class is not after a type
6588 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6589 WARN("STORAGE_CLASS",
6590 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6592 # Check that the storage class is at the beginning of a declaration
6593 if ($line =~ /\b$Storage\b/ &&
6594 $line !~ /^.\s*$Storage/ &&
6595 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6596 $1 !~ /[\,\)]\s*$/) {
6597 WARN("STORAGE_CLASS",
6598 "storage class should be at the beginning of the declaration\n" . $herecurr);
6601 # check the location of the inline attribute, that it is between
6602 # storage class and type.
6603 if ($line =~ /\b$Type\s+$Inline\b/ ||
6604 $line =~ /\b$Inline\s+$Storage\b/) {
6605 ERROR("INLINE_LOCATION",
6606 "inline keyword should sit between storage class and type\n" . $herecurr);
6609 # Check for __inline__ and __inline, prefer inline
6610 if ($realfile !~ m@\binclude/uapi/@ &&
6611 $line =~ /\b(__inline__|__inline)\b/) {
6613 "plain inline is preferred over $1\n" . $herecurr) &&
6615 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6620 # Check for compiler attributes
6621 if ($realfile !~ m@\binclude/uapi/@ &&
6622 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6624 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6627 "alias" => "__alias",
6628 "aligned" => "__aligned",
6629 "always_inline" => "__always_inline",
6630 "assume_aligned" => "__assume_aligned",
6632 "const" => "__attribute_const__",
6634 "designated_init" => "__designated_init",
6635 "externally_visible" => "__visible",
6636 "format" => "printf|scanf",
6637 "gnu_inline" => "__gnu_inline",
6638 "malloc" => "__malloc",
6640 "no_caller_saved_registers" => "__no_caller_saved_registers",
6641 "noclone" => "__noclone",
6642 "noinline" => "noinline",
6643 "nonstring" => "__nonstring",
6644 "noreturn" => "__noreturn",
6645 "packed" => "__packed",
6647 "section" => "__section",
6652 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6655 $params = $2 if defined($2);
6656 my $curr_attr = $orig_attr;
6657 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6658 if (exists($attr_list{$curr_attr})) {
6659 my $new = $attr_list{$curr_attr};
6660 if ($curr_attr eq "format" && $params) {
6661 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6664 $new = "$new$params";
6666 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6667 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6669 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6670 $fixed[$fixlinenr] =~ s/$remove//;
6671 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6672 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6673 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6678 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6679 if ($attr =~ /^_*unused/) {
6680 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6681 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6685 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6686 if ($perl_version_ok &&
6687 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6688 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6689 $line =~ /\b__weak\b/)) {
6690 ERROR("WEAK_DECLARATION",
6691 "Using weak declarations can have unintended link defects\n" . $herecurr);
6694 # check for c99 types like uint8_t used outside of uapi/ and tools/
6695 if ($realfile !~ m@\binclude/uapi/@ &&
6696 $realfile !~ m@\btools/@ &&
6697 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6699 if ($type =~ /\b($typeC99Typedefs)\b/) {
6701 my $kernel_type = 'u';
6702 $kernel_type = 's' if ($type =~ /^_*[si]/);
6705 if (CHK("PREFER_KERNEL_TYPES",
6706 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6708 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6713 # check for cast of C90 native int or longer types constants
6714 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6718 my $newconst = $const;
6719 $newconst =~ s/${Int_type}$//;
6720 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6721 if ($cast =~ /\blong\s+long\b/) {
6723 } elsif ($cast =~ /\blong\b/) {
6726 if (WARN("TYPECAST_INT_CONSTANT",
6727 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6729 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6733 # check for sizeof(&)
6734 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6735 WARN("SIZEOF_ADDRESS",
6736 "sizeof(& should be avoided\n" . $herecurr);
6739 # check for sizeof without parenthesis
6740 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6741 if (WARN("SIZEOF_PARENTHESIS",
6742 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6744 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6748 # check for struct spinlock declarations
6749 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6750 WARN("USE_SPINLOCK_T",
6751 "struct spinlock should be spinlock_t\n" . $herecurr);
6754 # check for seq_printf uses that could be seq_puts
6755 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6756 my $fmt = get_quoted_string($line, $rawline);
6759 if (WARN("PREFER_SEQ_PUTS",
6760 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6762 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6767 # check for vsprintf extension %p<foo> misuses
6768 if ($perl_version_ok &&
6770 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6771 $1 !~ /^_*volatile_*$/) {
6774 my $lc = $stat =~ tr@\n@@;
6775 $lc = $lc + $linenr;
6776 for (my $count = $linenr; $count <= $lc; $count++) {
6780 my $bad_specifier = "";
6781 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6784 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6788 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6789 ($extension eq "f" &&
6790 defined $qualifier && $qualifier !~ /^w/) ||
6791 ($extension eq "4" &&
6792 defined $qualifier && $qualifier !~ /^cc/)) {
6793 $bad_specifier = $specifier;
6796 if ($extension eq "x" && !defined($stat_real)) {
6797 if (!defined($stat_real)) {
6798 $stat_real = get_stat_real($linenr, $lc);
6800 WARN("VSPRINTF_SPECIFIER_PX",
6801 "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");
6804 if ($bad_specifier ne "") {
6805 my $stat_real = get_stat_real($linenr, $lc);
6806 my $ext_type = "Invalid";
6808 if ($bad_specifier =~ /p[Ff]/) {
6809 $use = " - use %pS instead";
6810 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6813 WARN("VSPRINTF_POINTER_EXTENSION",
6814 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6819 # Check for misused memsets
6820 if ($perl_version_ok &&
6822 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6828 if ($ms_size =~ /^(0x|)0$/i) {
6830 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6831 } elsif ($ms_size =~ /^(0x|)1$/i) {
6833 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6837 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6838 # if ($perl_version_ok &&
6840 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6841 # if (WARN("PREFER_ETHER_ADDR_COPY",
6842 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6844 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6848 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6849 # if ($perl_version_ok &&
6851 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6852 # WARN("PREFER_ETHER_ADDR_EQUAL",
6853 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6856 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6857 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6858 # if ($perl_version_ok &&
6860 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6864 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6865 # if (WARN("PREFER_ETH_ZERO_ADDR",
6866 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6868 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6870 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6871 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6872 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6874 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6879 # strlcpy uses that should likely be strscpy
6880 if ($line =~ /\bstrlcpy\s*\(/) {
6882 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6885 # typecasts on min/max could be min_t/max_t
6886 if ($perl_version_ok &&
6888 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6889 if (defined $2 || defined $7) {
6891 my $cast1 = deparenthesize($2);
6893 my $cast2 = deparenthesize($7);
6897 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6898 $cast = "$cast1 or $cast2";
6899 } elsif ($cast1 ne "") {
6905 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6909 # check usleep_range arguments
6910 if ($perl_version_ok &&
6912 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6916 WARN("USLEEP_RANGE",
6917 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6918 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6920 WARN("USLEEP_RANGE",
6921 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6925 # check for naked sscanf
6926 if ($perl_version_ok &&
6928 $line =~ /\bsscanf\b/ &&
6929 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6930 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6931 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6932 my $lc = $stat =~ tr@\n@@;
6933 $lc = $lc + $linenr;
6934 my $stat_real = get_stat_real($linenr, $lc);
6935 WARN("NAKED_SSCANF",
6936 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6939 # check for simple sscanf that should be kstrto<foo>
6940 if ($perl_version_ok &&
6942 $line =~ /\bsscanf\b/) {
6943 my $lc = $stat =~ tr@\n@@;
6944 $lc = $lc + $linenr;
6945 my $stat_real = get_stat_real($linenr, $lc);
6946 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6948 my $count = $format =~ tr@%@%@;
6950 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6951 WARN("SSCANF_TO_KSTRTO",
6952 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6957 # check for new externs in .h files.
6958 if ($realfile =~ /\.h$/ &&
6959 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6960 if (CHK("AVOID_EXTERNS",
6961 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6963 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6967 # check for new externs in .c files.
6968 if ($realfile =~ /\.c$/ && defined $stat &&
6969 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6971 my $function_name = $1;
6972 my $paren_space = $2;
6975 if (defined $cond) {
6976 substr($s, 0, length($cond), '');
6980 WARN("AVOID_EXTERNS",
6981 "externs should be avoided in .c files\n" . $herecurr);
6984 if ($paren_space =~ /\n/) {
6985 WARN("FUNCTION_ARGUMENTS",
6986 "arguments for function declarations should follow identifier\n" . $herecurr);
6989 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6990 $stat =~ /^.\s*extern\s+/)
6992 WARN("AVOID_EXTERNS",
6993 "externs should be avoided in .c files\n" . $herecurr);
6996 # check for function declarations that have arguments without identifier names
6997 if (defined $stat &&
6998 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7000 my $args = trim($1);
7001 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7003 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7004 WARN("FUNCTION_ARGUMENTS",
7005 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7010 # check for function definitions
7011 if ($perl_version_ok &&
7013 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7014 $context_function = $1;
7016 # check for multiline function definition with misplaced open brace
7018 my $cnt = statement_rawlines($stat);
7019 my $herectx = $here . "\n";
7020 for (my $n = 0; $n < $cnt; $n++) {
7021 my $rl = raw_line($linenr, $n);
7022 $herectx .= $rl . "\n";
7023 $ok = 1 if ($rl =~ /^[ \+]\{/);
7024 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7025 last if $rl =~ /^[ \+].*\{/;
7029 "open brace '{' following function definitions go on the next line\n" . $herectx);
7033 # checks for new __setup's
7034 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7037 if (!grep(/$name/, @setup_docs)) {
7038 CHK("UNDOCUMENTED_SETUP",
7039 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7043 # check for pointless casting of alloc functions
7044 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7045 WARN("UNNECESSARY_CASTS",
7046 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7050 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7051 if ($perl_version_ok &&
7052 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7053 CHK("ALLOC_SIZEOF_STRUCT",
7054 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7057 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7058 if ($perl_version_ok &&
7060 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7064 my $newfunc = "kmalloc_array";
7065 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7066 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7067 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7070 if ($a1 =~ /^sizeof\s*\S/) {
7074 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7075 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7076 my $cnt = statement_rawlines($stat);
7077 my $herectx = get_stat_here($linenr, $cnt, $here);
7079 if (WARN("ALLOC_WITH_MULTIPLY",
7080 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7083 $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;
7088 # check for krealloc arg reuse
7089 if ($perl_version_ok &&
7090 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7092 WARN("KREALLOC_ARG_REUSE",
7093 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7096 # check for alloc argument mismatch
7097 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7098 WARN("ALLOC_ARRAY_ARGS",
7099 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7102 # check for multiple semicolons
7103 if ($line =~ /;\s*;\s*$/) {
7104 if (WARN("ONE_SEMICOLON",
7105 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7107 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7111 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7112 if ($realfile !~ m@^include/uapi/@ &&
7113 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7115 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7116 if (CHK("BIT_MACRO",
7117 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7119 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7123 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7124 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7125 WARN("IS_ENABLED_CONFIG",
7126 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7129 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7130 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7132 if (WARN("PREFER_IS_ENABLED",
7133 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7135 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7139 # check for /* fallthrough */ like comment, prefer fallthrough;
7140 my @fallthroughs = (
7143 'lint -fallthrough[ \t]*',
7144 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7145 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7146 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7147 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7149 if ($raw_comment ne '') {
7150 foreach my $ft (@fallthroughs) {
7151 if ($raw_comment =~ /$ft/) {
7152 my $msg_level = \&WARN;
7153 $msg_level = \&CHK if ($file);
7154 &{$msg_level}("PREFER_FALLTHROUGH",
7155 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7161 # check for switch/default statements without a break;
7162 if ($perl_version_ok &&
7164 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7165 my $cnt = statement_rawlines($stat);
7166 my $herectx = get_stat_here($linenr, $cnt, $here);
7168 WARN("DEFAULT_NO_BREAK",
7169 "switch default: should use break\n" . $herectx);
7172 # check for gcc specific __FUNCTION__
7173 if ($line =~ /\b__FUNCTION__\b/) {
7174 if (WARN("USE_FUNC",
7175 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7177 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7181 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7182 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7184 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7187 # check for use of yield()
7188 if ($line =~ /\byield\s*\(\s*\)/) {
7190 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7193 # check for comparisons against true and false
7194 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7202 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7204 my $type = lc($otype);
7205 if ($type =~ /^(?:true|false)$/) {
7206 if (("$test" eq "==" && "$type" eq "true") ||
7207 ("$test" eq "!=" && "$type" eq "false")) {
7211 CHK("BOOL_COMPARISON",
7212 "Using comparison to $otype is error prone\n" . $herecurr);
7214 ## maybe suggesting a correct construct would better
7215 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7220 # check for semaphores initialized locked
7221 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7222 WARN("CONSIDER_COMPLETION",
7223 "consider using a completion\n" . $herecurr);
7226 # recommend kstrto* over simple_strto* and strict_strto*
7227 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7228 WARN("CONSIDER_KSTRTO",
7229 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7232 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7233 if ($line =~ /^.\s*__initcall\s*\(/) {
7234 WARN("USE_DEVICE_INITCALL",
7235 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7238 # check for spin_is_locked(), suggest lockdep instead
7239 if ($line =~ /\bspin_is_locked\(/) {
7241 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7244 # check for deprecated apis
7245 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7246 my $deprecated_api = $1;
7247 my $new_api = $deprecated_apis{$deprecated_api};
7248 WARN("DEPRECATED_API",
7249 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7252 # check for various structs that are normally const (ops, kgdb, device_tree)
7253 # and avoid what seem like struct definitions 'struct foo {'
7254 if (defined($const_structs) &&
7255 $line !~ /\bconst\b/ &&
7256 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7257 WARN("CONST_STRUCT",
7258 "struct $1 should normally be const\n" . $herecurr);
7261 # use of NR_CPUS is usually wrong
7262 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7263 # ignore designated initializers using NR_CPUS
7264 if ($line =~ /\bNR_CPUS\b/ &&
7265 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7266 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7267 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7268 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7269 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7270 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7273 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7276 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7277 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7278 ERROR("DEFINE_ARCH_HAS",
7279 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7282 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7283 if ($perl_version_ok &&
7284 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7285 WARN("LIKELY_MISUSE",
7286 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7289 # return sysfs_emit(foo, fmt, ...) fmt without newline
7290 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7291 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7292 my $offset = $+[6] - 1;
7293 if (WARN("SYSFS_EMIT",
7294 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7296 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7300 # nested likely/unlikely calls
7301 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7302 WARN("LIKELY_MISUSE",
7303 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7306 # whine mightly about in_atomic
7307 if ($line =~ /\bin_atomic\s*\(/) {
7308 if ($realfile =~ m@^drivers/@) {
7310 "do not use in_atomic in drivers\n" . $herecurr);
7311 } elsif ($realfile !~ m@^kernel/@) {
7313 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7317 # check for lockdep_set_novalidate_class
7318 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7319 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7320 if ($realfile !~ m@^kernel/lockdep@ &&
7321 $realfile !~ m@^include/linux/lockdep@ &&
7322 $realfile !~ m@^drivers/base/core@) {
7324 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7328 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7329 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7330 WARN("EXPORTED_WORLD_WRITABLE",
7331 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7334 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7335 # and whether or not function naming is typical and if
7336 # DEVICE_ATTR permissions uses are unusual too
7337 if ($perl_version_ok &&
7339 $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*\)/) {
7344 my $octal_perms = perms_to_octal($perms);
7345 if ($show =~ /^${var}_show$/ &&
7346 $store =~ /^${var}_store$/ &&
7347 $octal_perms eq "0644") {
7348 if (WARN("DEVICE_ATTR_RW",
7349 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7351 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7353 } elsif ($show =~ /^${var}_show$/ &&
7354 $store =~ /^NULL$/ &&
7355 $octal_perms eq "0444") {
7356 if (WARN("DEVICE_ATTR_RO",
7357 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7359 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7361 } elsif ($show =~ /^NULL$/ &&
7362 $store =~ /^${var}_store$/ &&
7363 $octal_perms eq "0200") {
7364 if (WARN("DEVICE_ATTR_WO",
7365 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7367 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7369 } elsif ($octal_perms eq "0644" ||
7370 $octal_perms eq "0444" ||
7371 $octal_perms eq "0200") {
7372 my $newshow = "$show";
7373 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7374 my $newstore = $store;
7375 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7377 if ($show ne $newshow) {
7378 $rename .= " '$show' to '$newshow'";
7380 if ($store ne $newstore) {
7381 $rename .= " '$store' to '$newstore'";
7383 WARN("DEVICE_ATTR_FUNCTIONS",
7384 "Consider renaming function(s)$rename\n" . $herecurr);
7386 WARN("DEVICE_ATTR_PERMS",
7387 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7391 # Mode permission misuses where it seems decimal should be octal
7392 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7393 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7394 # specific definition of not visible in sysfs.
7395 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7396 # use the default permissions
7397 if ($perl_version_ok &&
7399 $line =~ /$mode_perms_search/) {
7400 foreach my $entry (@mode_permission_funcs) {
7401 my $func = $entry->[0];
7402 my $arg_pos = $entry->[1];
7404 my $lc = $stat =~ tr@\n@@;
7405 $lc = $lc + $linenr;
7406 my $stat_real = get_stat_real($linenr, $lc);
7411 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7413 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7414 if ($stat =~ /$test/) {
7416 $val = $6 if ($skip_args ne "");
7417 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7418 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7419 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7420 ERROR("NON_OCTAL_PERMISSIONS",
7421 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7423 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7424 ERROR("EXPORTED_WORLD_WRITABLE",
7425 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7431 # check for uses of S_<PERMS> that could be octal for readability
7432 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7434 my $octal = perms_to_octal($oval);
7435 if (WARN("SYMBOLIC_PERMS",
7436 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7438 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7442 # validate content of MODULE_LICENSE against list from include/linux/module.h
7443 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7444 my $extracted_string = get_quoted_string($line, $rawline);
7445 my $valid_licenses = qr{
7448 GPL\ and\ additional\ rights|
7454 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7455 WARN("MODULE_LICENSE",
7456 "unknown module license " . $extracted_string . "\n" . $herecurr);
7458 if (!$file && $extracted_string eq '"GPL v2"') {
7459 if (WARN("MODULE_LICENSE",
7460 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7462 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7467 # check for sysctl duplicate constants
7468 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7469 WARN("DUPLICATED_SYSCTL_CONST",
7470 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7474 # If we have no input at all, then there is nothing to report on
7475 # so just keep quiet.
7476 if ($#rawlines == -1) {
7480 # In mailback mode only produce a report in the negative, for
7481 # things that appear to be patches.
7482 if ($mailback && ($clean == 1 || !$is_patch)) {
7486 # This is not a patch, and we are in 'no-patch' mode so
7488 if (!$chk_patch && !$is_patch) {
7492 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7493 ERROR("NOT_UNIFIED_DIFF",
7494 "Does not appear to be a unified-diff format patch\n");
7496 if ($is_patch && $has_commit_log && $chk_signoff) {
7497 if ($signoff == 0) {
7498 ERROR("MISSING_SIGN_OFF",
7499 "Missing Signed-off-by: line(s)\n");
7500 } elsif ($authorsignoff != 1) {
7501 # authorsignoff values:
7502 # 0 -> missing sign off
7503 # 1 -> sign off identical
7504 # 2 -> names and addresses match, comments mismatch
7505 # 3 -> addresses match, names different
7506 # 4 -> names match, addresses different
7507 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7509 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7511 if ($authorsignoff == 0) {
7512 ERROR("NO_AUTHOR_SIGN_OFF",
7513 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7514 } elsif ($authorsignoff == 2) {
7515 CHK("FROM_SIGN_OFF_MISMATCH",
7516 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7517 } elsif ($authorsignoff == 3) {
7518 WARN("FROM_SIGN_OFF_MISMATCH",
7519 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7520 } elsif ($authorsignoff == 4) {
7521 WARN("FROM_SIGN_OFF_MISMATCH",
7522 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7523 } elsif ($authorsignoff == 5) {
7524 WARN("FROM_SIGN_OFF_MISMATCH",
7525 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7530 print report_dump();
7531 if ($summary && !($clean == 1 && $quiet == 1)) {
7532 print "$filename " if ($summary_file);
7533 print "total: $cnt_error errors, $cnt_warn warnings, " .
7534 (($check)? "$cnt_chk checks, " : "") .
7535 "$cnt_lines lines checked\n";
7539 # If there were any defects found and not already fixing them
7540 if (!$clean and !$fix) {
7543 NOTE: For some of the reported defects, checkpatch may be able to
7544 mechanically convert to the typical style using --fix or --fix-inplace.
7547 # If there were whitespace errors which cleanpatch can fix
7548 # then suggest that.
7549 if ($rpt_cleaners) {
7553 NOTE: Whitespace errors detected.
7554 You may wish to use scripts/cleanpatch or scripts/cleanfile
7559 if ($clean == 0 && $fix &&
7560 ("@rawlines" ne "@fixed" ||
7561 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7562 my $newfile = $filename;
7563 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7567 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7569 open($f, '>', $newfile)
7570 or die "$P: Can't open $newfile for write\n";
7571 foreach my $fixed_line (@fixed) {
7574 if ($linecount > 3) {
7575 $fixed_line =~ s/^\+//;
7576 print $f $fixed_line . "\n";
7579 print $f $fixed_line . "\n";
7587 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7589 Do _NOT_ trust the results written to this file.
7590 Do _NOT_ submit these changes without inspecting them for correctness.
7592 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7593 No warranties, expressed or implied...
7601 print "$vname has no obvious style problems and is ready for submission.\n";
7603 print "$vname has style problems, please review.\n";