2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
27 my %verbose_messages = ();
28 my %verbose_emitted = ();
49 my $gitroot = $ENV{'GIT_DIR'};
50 $gitroot = ".git" if !defined($gitroot);
58 my $configuration_file = ".checkpatch.conf";
59 my $max_line_length = 100;
60 my $ignore_perl_version = 0;
61 my $minimum_perl_version = 5.10.0;
62 my $min_conf_desc_length = 4;
63 my $spelling_file = "$D/spelling.txt";
65 my $codespellfile = "/usr/share/codespell/dictionary.txt";
66 my $user_codespellfile = "";
67 my $conststructsfile = "$D/const_structs.checkpatch";
68 my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
71 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
72 # git output parsing needs US English output, so first set backtick child process LANGUAGE
73 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
75 my ${CONFIG_} = "CONFIG_";
81 Usage: $P [OPTION]... [FILE]...
86 -v, --verbose verbose mode
87 --no-tree run without a kernel tree
88 --no-signoff do not check for 'Signed-off-by' line
89 --patch treat FILE as patchfile (default)
90 --emacs emacs compile window format
91 --terse one line per report
92 --showfile emit diffed file position, not input file position
93 -g, --git treat FILE as a single commit or git revision range
94 single git commit with:
98 multiple git commits with:
102 git merges are ignored
103 -f, --file treat FILE as regular source file
104 --subjective, --strict enable more subjective tests
105 --list-types list the possible message types
106 --types TYPE(,TYPE2...) show only these comma separated message types
107 --ignore TYPE(,TYPE2...) ignore various comma separated message types
108 --show-types show the specific message type in the output
109 --max-line-length=n set the maximum line length, (default $max_line_length)
110 if exceeded, warn on patches
111 requires --strict for use with --file
112 --min-conf-desc-length=n set the min description length, if shorter, warn
113 --tab-size=n set the number of spaces for tab (default $tabsize)
114 --root=PATH PATH to the kernel tree root
115 --no-summary suppress the per-file summary
116 --mailback only produce a report in case of warnings/errors
117 --summary-file include the filename in summary
118 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
119 'values', 'possible', 'type', and 'attr' (default
121 --test-only=WORD report only warnings/errors containing WORD
123 --fix EXPERIMENTAL - may create horrible results
124 If correctable single-line errors exist, create
125 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
126 with potential errors corrected to the preferred
128 --fix-inplace EXPERIMENTAL - may create horrible results
129 Is the same as --fix, but overwrites the input
130 file. It's your fault if there's no backup or git
131 --ignore-perl-version override checking of perl version. expect
133 --codespell Use the codespell dictionary for spelling/typos
134 (default:$codespellfile)
135 --codespellfile Use this codespell dictionary
136 --typedefsfile Read additional types from this file
137 --color[=WHEN] Use colors 'always', 'never', or only when output
138 is a terminal ('auto'). Default is 'auto'.
139 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
141 -h, --help, --version display this help and exit
143 When FILE is - read standard input.
151 return grep { !$seen{$_}++ } @_;
161 open(my $script, '<', abs_path($P)) or
162 die "$P: Can't read '$P' $!\n";
164 my $text = <$script>;
168 # Also catch when type or level is passed through a variable
169 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
171 if (exists($types{$2})) {
172 $types{$2} .= ",$1" if ($types{$2} ne $1);
177 $types{$2} = "UNDETERMINED";
181 print("#\tMessage type\n\n");
183 print(" ( Color coding: ");
184 print(RED . "ERROR" . RESET);
186 print(YELLOW . "WARNING" . RESET);
188 print(GREEN . "CHECK" . RESET);
190 print("Multiple levels / Undetermined");
194 foreach my $type (sort keys %types) {
195 my $orig_type = $type;
197 my $level = $types{$type};
198 if ($level eq "ERROR") {
199 $type = RED . $type . RESET;
200 } elsif ($level eq "WARN") {
201 $type = YELLOW . $type . RESET;
202 } elsif ($level eq "CHK") {
203 $type = GREEN . $type . RESET;
206 print(++$count . "\t" . $type . "\n");
207 if ($verbose && exists($verbose_messages{$orig_type})) {
208 my $message = $verbose_messages{$orig_type};
209 $message =~ s/\n/\n\t/g;
210 print("\t" . $message . "\n\n");
217 my $conf = which_conf($configuration_file);
220 open(my $conffile, '<', "$conf")
221 or warn "$P: Can't find a readable $configuration_file file $!\n";
223 while (<$conffile>) {
226 $line =~ s/\s*\n?$//g;
230 next if ($line =~ m/^\s*#/);
231 next if ($line =~ m/^\s*$/);
233 my @words = split(" ", $line);
234 foreach my $word (@words) {
235 last if ($word =~ m/^#/);
236 push (@conf_args, $word);
240 unshift(@ARGV, @conf_args) if @conf_args;
244 open(my $docs, '<', "$docsfile")
245 or warn "$P: Can't read the documentation file $docsfile $!\n";
256 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
258 $verbose_messages{$type} = trim($desc);
264 if ($line =~ /^(?:\s{4,}|$)/) {
269 $verbose_messages{$type} = trim($desc);
278 $verbose_messages{$type} = trim($desc);
283 # Perl's Getopt::Long allows options to take optional arguments after a space.
284 # Prevent --color by itself from consuming other arguments
286 if ($_ eq "--color" || $_ eq "-color") {
287 $_ = "--color=$color";
292 'q|quiet+' => \$quiet,
293 'v|verbose!' => \$verbose,
295 'signoff!' => \$chk_signoff,
296 'patch!' => \$chk_patch,
299 'showfile!' => \$showfile,
302 'subjective!' => \$check,
303 'strict!' => \$check,
304 'ignore=s' => \@ignore,
306 'show-types!' => \$show_types,
307 'list-types!' => \$list_types,
308 'max-line-length=i' => \$max_line_length,
309 'min-conf-desc-length=i' => \$min_conf_desc_length,
310 'tab-size=i' => \$tabsize,
312 'summary!' => \$summary,
313 'mailback!' => \$mailback,
314 'summary-file!' => \$summary_file,
316 'fix-inplace!' => \$fix_inplace,
317 'ignore-perl-version!' => \$ignore_perl_version,
318 'debug=s' => \%debug,
319 'test-only=s' => \$tst_only,
320 'codespell!' => \$codespell,
321 'codespellfile=s' => \$user_codespellfile,
322 'typedefsfile=s' => \$typedefsfile,
323 'color=s' => \$color,
324 'no-color' => \$color, #keep old behaviors of -nocolor
325 'nocolor' => \$color, #keep old behaviors of -nocolor
326 'kconfig-prefix=s' => \${CONFIG_},
331 if ($user_codespellfile) {
332 # Use the user provided codespell file unconditionally
333 $codespellfile = $user_codespellfile;
334 } elsif (!(-f $codespellfile)) {
335 # If /usr/share/codespell/dictionary.txt is not present, try to find it
336 # under codespell's install directory: <codespell_root>/data/dictionary.txt
337 if (($codespell || $help) && which("python3") ne "") {
338 my $python_codespell_dict = << "EOF";
342 codespell_dir = op.dirname(codespell_lib.__file__)
343 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
344 print(codespell_file, end='')
347 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
348 $codespellfile = $codespell_dict if (-f $codespell_dict);
352 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
353 # $help is 2 if invalid option is passed - exitcode: 1
354 help($help - 1) if ($help);
356 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
357 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
359 if ($color =~ /^[01]$/) {
361 } elsif ($color =~ /^always$/i) {
363 } elsif ($color =~ /^never$/i) {
365 } elsif ($color =~ /^auto$/i) {
366 $color = (-t STDOUT);
368 die "$P: Invalid color mode: $color\n";
371 load_docs() if ($verbose);
372 list_types(0) if ($list_types);
374 $fix = 1 if ($fix_inplace);
375 $check_orig = $check;
379 my $perl_version_ok = 1;
380 if ($^V && $^V lt $minimum_perl_version) {
381 $perl_version_ok = 0;
382 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
383 exit(1) if (!$ignore_perl_version);
386 #if no filenames are given, push '-' to read patch from stdin
391 # skip TAB size 1 to avoid additional checks on $tabsize - 1
392 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
394 sub hash_save_array_words {
395 my ($hashRef, $arrayRef) = @_;
397 my @array = split(/,/, join(',', @$arrayRef));
398 foreach my $word (@array) {
399 $word =~ s/\s*\n?$//g;
402 $word =~ tr/[a-z]/[A-Z]/;
404 next if ($word =~ m/^\s*#/);
405 next if ($word =~ m/^\s*$/);
411 sub hash_show_words {
412 my ($hashRef, $prefix) = @_;
414 if (keys %$hashRef) {
415 print "\nNOTE: $prefix message types:";
416 foreach my $word (sort keys %$hashRef) {
423 hash_save_array_words(\%ignore_type, \@ignore);
424 hash_save_array_words(\%use_type, \@use);
427 my $dbg_possible = 0;
430 for my $key (keys %debug) {
432 eval "\${dbg_$key} = '$debug{$key}';";
436 my $rpt_cleaners = 0;
445 if (!top_of_kernel_tree($root)) {
446 die "$P: $root: --root does not point at a valid tree\n";
449 if (top_of_kernel_tree('.')) {
451 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
452 top_of_kernel_tree($1)) {
457 if (!defined $root) {
458 print "Must be run from the top-level dir. of a kernel tree\n";
463 my $emitted_corrupt = 0;
466 [A-Za-z_][A-Za-z\d_]*
467 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
469 our $Storage = qr{extern|static|asmlinkage};
483 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
484 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
485 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
486 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
487 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
489 # Notes to $Attribute:
490 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
513 ____cacheline_aligned|
514 ____cacheline_aligned_in_smp|
515 ____cacheline_internodealigned_in_smp|
517 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
520 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
521 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
522 our $Lval = qr{$Ident(?:$Member)*};
524 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
525 our $Binary = qr{(?i)0b[01]+$Int_type?};
526 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
527 our $Int = qr{[0-9]+$Int_type?};
528 our $Octal = qr{0[0-7]+$Int_type?};
529 our $String = qr{(?:\b[Lu])?"[X\t]*"};
530 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
531 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
532 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
533 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
534 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
535 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
536 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
537 our $Arithmetic = qr{\+|-|\*|\/|%};
541 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
544 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
548 our $NonptrTypeMisordered;
549 our $NonptrTypeWithAttr;
553 our $DeclareMisordered;
555 our $NON_ASCII_UTF8 = qr{
556 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
557 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
558 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
559 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
560 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
561 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
562 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
566 [\x09\x0A\x0D\x20-\x7E] # ASCII
570 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
571 our $typeOtherOSTypedefs = qr{(?x:
572 u_(?:char|short|int|long) | # bsd
573 u(?:nchar|short|int|long) # sysv
575 our $typeKernelTypedefs = qr{(?x:
576 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
579 our $typeStdioTypedefs = qr{(?x:
582 our $typeTypedefs = qr{(?x:
584 $typeOtherOSTypedefs\b|
585 $typeKernelTypedefs\b|
589 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
591 our $logFunctions = qr{(?x:
592 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
593 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
595 WARN(?:_RATELIMIT|_ONCE|)|
598 seq_vprintf|seq_printf|seq_puts
601 our $allocFunctions = qr{(?x:
603 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
606 (?:\w+)?alloc_skb(?:_ip_align)? |
607 # dev_alloc_skb/netdev_alloc_skb, et al
611 our $signature_tags = qr{(?xi:
623 our $tracing_logging_tags = qr{(?xi:
647 sub edit_distance_min {
649 my $len = scalar @arr;
650 if ((scalar @arr) < 1) {
651 # if underflow, return
655 for my $i (0 .. ($len-1)) {
656 if ($arr[$i] < $min) {
663 sub get_edit_distance {
664 my ($str1, $str2) = @_;
669 my $len1 = length($str1);
670 my $len2 = length($str2);
671 # two dimensional array storing minimum edit distance
673 for my $i (0 .. $len1) {
674 for my $j (0 .. $len2) {
676 $distance[$i][$j] = $j;
678 $distance[$i][$j] = $i;
679 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
680 $distance[$i][$j] = $distance[$i - 1][$j - 1];
682 my $dist1 = $distance[$i][$j - 1]; #insert distance
683 my $dist2 = $distance[$i - 1][$j]; # remove
684 my $dist3 = $distance[$i - 1][$j - 1]; #replace
685 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
689 return $distance[$len1][$len2];
692 sub find_standard_signature {
694 my @standard_signature_tags = (
695 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
696 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
698 foreach my $signature (@standard_signature_tags) {
699 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
705 our @typeListMisordered = (
706 qr{char\s+(?:un)?signed},
707 qr{int\s+(?:(?:un)?signed\s+)?short\s},
708 qr{int\s+short(?:\s+(?:un)?signed)},
709 qr{short\s+int(?:\s+(?:un)?signed)},
710 qr{(?:un)?signed\s+int\s+short},
711 qr{short\s+(?:un)?signed},
712 qr{long\s+int\s+(?:un)?signed},
713 qr{int\s+long\s+(?:un)?signed},
714 qr{long\s+(?:un)?signed\s+int},
715 qr{int\s+(?:un)?signed\s+long},
716 qr{int\s+(?:un)?signed},
717 qr{int\s+long\s+long\s+(?:un)?signed},
718 qr{long\s+long\s+int\s+(?:un)?signed},
719 qr{long\s+long\s+(?:un)?signed\s+int},
720 qr{long\s+long\s+(?:un)?signed},
721 qr{long\s+(?:un)?signed},
726 qr{(?:(?:un)?signed\s+)?char},
727 qr{(?:(?:un)?signed\s+)?short\s+int},
728 qr{(?:(?:un)?signed\s+)?short},
729 qr{(?:(?:un)?signed\s+)?int},
730 qr{(?:(?:un)?signed\s+)?long\s+int},
731 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
732 qr{(?:(?:un)?signed\s+)?long\s+long},
733 qr{(?:(?:un)?signed\s+)?long},
742 qr{${Ident}_handler},
743 qr{${Ident}_handler_fn},
747 our $C90_int_types = qr{(?x:
748 long\s+long\s+int\s+(?:un)?signed|
749 long\s+long\s+(?:un)?signed\s+int|
750 long\s+long\s+(?:un)?signed|
751 (?:(?:un)?signed\s+)?long\s+long\s+int|
752 (?:(?:un)?signed\s+)?long\s+long|
753 int\s+long\s+long\s+(?:un)?signed|
754 int\s+(?:(?:un)?signed\s+)?long\s+long|
756 long\s+int\s+(?:un)?signed|
757 long\s+(?:un)?signed\s+int|
758 long\s+(?:un)?signed|
759 (?:(?:un)?signed\s+)?long\s+int|
760 (?:(?:un)?signed\s+)?long|
761 int\s+long\s+(?:un)?signed|
762 int\s+(?:(?:un)?signed\s+)?long|
765 (?:(?:un)?signed\s+)?int
768 our @typeListFile = ();
769 our @typeListWithAttr = (
771 qr{struct\s+$InitAttribute\s+$Ident},
772 qr{union\s+$InitAttribute\s+$Ident},
775 our @modifierList = (
778 our @modifierListFile = ();
780 our @mode_permission_funcs = (
782 ["module_param_(?:array|named|string)", 4],
783 ["module_param_array_named", 5],
784 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
785 ["proc_create(?:_data|)", 2],
786 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
787 ["IIO_DEV_ATTR_[A-Z_]+", 1],
788 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
789 ["SENSOR_TEMPLATE(?:_2|)", 3],
793 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
795 #Create a search pattern for all these functions to speed up a loop below
796 our $mode_perms_search = "";
797 foreach my $entry (@mode_permission_funcs) {
798 $mode_perms_search .= '|' if ($mode_perms_search ne "");
799 $mode_perms_search .= $entry->[0];
801 $mode_perms_search = "(?:${mode_perms_search})";
803 our %deprecated_apis = (
804 "synchronize_rcu_bh" => "synchronize_rcu",
805 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
806 "call_rcu_bh" => "call_rcu",
807 "rcu_barrier_bh" => "rcu_barrier",
808 "synchronize_sched" => "synchronize_rcu",
809 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
810 "call_rcu_sched" => "call_rcu",
811 "rcu_barrier_sched" => "rcu_barrier",
812 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
813 "cond_synchronize_sched" => "cond_synchronize_rcu",
814 "kmap" => "kmap_local_page",
815 "kmap_atomic" => "kmap_local_page",
818 #Create a search pattern for all these strings to speed up a loop below
819 our $deprecated_apis_search = "";
820 foreach my $entry (keys %deprecated_apis) {
821 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
822 $deprecated_apis_search .= $entry;
824 $deprecated_apis_search = "(?:${deprecated_apis_search})";
826 our $mode_perms_world_writable = qr{
834 our %mode_permission_string_types = (
853 #Create a search pattern for all these strings to speed up a loop below
854 our $mode_perms_string_search = "";
855 foreach my $entry (keys %mode_permission_string_types) {
856 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
857 $mode_perms_string_search .= $entry;
859 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
860 our $multi_mode_perms_string_search = qr{
861 ${single_mode_perms_string_search}
862 (?:\s*\|\s*${single_mode_perms_string_search})*
868 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
875 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
876 $curpos = pos($string);
879 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
881 $to |= $mode_permission_string_types{$match};
882 $val .= '\s*\|\s*' if ($val ne "");
886 $oval =~ s/^\s*\|\s*//;
887 $oval =~ s/\s*\|\s*$//;
888 return sprintf("%04o", $to);
891 our $allowed_asm_includes = qr{(?x:
897 # memory.h: ARM has a custom one
899 # Load common spelling mistakes and build regular expression list.
903 if (open(my $spelling, '<', $spelling_file)) {
904 while (<$spelling>) {
907 $line =~ s/\s*\n?$//g;
910 next if ($line =~ m/^\s*#/);
911 next if ($line =~ m/^\s*$/);
913 my ($suspect, $fix) = split(/\|\|/, $line);
915 $spelling_fix{$suspect} = $fix;
919 warn "No typos will be found - file '$spelling_file': $!\n";
923 if (open(my $spelling, '<', $codespellfile)) {
924 while (<$spelling>) {
927 $line =~ s/\s*\n?$//g;
930 next if ($line =~ m/^\s*#/);
931 next if ($line =~ m/^\s*$/);
932 next if ($line =~ m/, disabled/i);
936 my ($suspect, $fix) = split(/->/, $line);
938 $spelling_fix{$suspect} = $fix;
942 warn "No codespell typos will be found - file '$codespellfile': $!\n";
946 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
949 my ($wordsRef, $file) = @_;
951 if (open(my $words, '<', $file)) {
955 $line =~ s/\s*\n?$//g;
958 next if ($line =~ m/^\s*#/);
959 next if ($line =~ m/^\s*$/);
961 print("$file: '$line' invalid - ignored\n");
965 $$wordsRef .= '|' if (defined $$wordsRef);
976 if (show_type("CONST_STRUCT")) {
977 read_words(\$const_structs, $conststructsfile)
978 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
981 if (defined($typedefsfile)) {
982 my $typeOtherTypedefs;
983 read_words(\$typeOtherTypedefs, $typedefsfile)
984 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
985 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
989 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
990 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
991 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
992 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
993 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
999 (?:$Modifier\s+|const\s+)*
1001 (?:typeof|__typeof__)\s*\([^\)]*\)|
1002 (?:$typeTypedefs\b)|
1005 (?:\s+$Modifier|\s+const)*
1007 $NonptrTypeMisordered = qr{
1008 (?:$Modifier\s+|const\s+)*
1012 (?:\s+$Modifier|\s+const)*
1014 $NonptrTypeWithAttr = qr{
1015 (?:$Modifier\s+|const\s+)*
1017 (?:typeof|__typeof__)\s*\([^\)]*\)|
1018 (?:$typeTypedefs\b)|
1019 (?:${allWithAttr}\b)
1021 (?:\s+$Modifier|\s+const)*
1025 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1026 (?:\s+$Inline|\s+$Modifier)*
1028 $TypeMisordered = qr{
1029 $NonptrTypeMisordered
1030 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1031 (?:\s+$Inline|\s+$Modifier)*
1033 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1034 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1038 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1040 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1041 # requires at least perl version v5.10.0
1042 # Any use must be runtime checked with $^V
1044 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1045 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1046 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1048 our $declaration_macros = qr{(?x:
1049 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1050 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1051 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1052 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1055 our %allow_repeated_words = (
1062 sub deparenthesize {
1064 return "" if (!defined($string));
1066 while ($string =~ /^\s*\(.*\)\s*$/) {
1067 $string =~ s@^\s*\(\s*@@;
1068 $string =~ s@\s*\)\s*$@@;
1071 $string =~ s@\s+@ @g;
1076 sub seed_camelcase_file {
1079 return if (!(-f $file));
1083 open(my $include_file, '<', "$file")
1084 or warn "$P: Can't read '$file' $!\n";
1085 my $text = <$include_file>;
1086 close($include_file);
1088 my @lines = split('\n', $text);
1090 foreach my $line (@lines) {
1091 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1092 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1094 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1096 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1102 our %maintained_status = ();
1104 sub is_maintained_obsolete {
1105 my ($filename) = @_;
1107 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1109 if (!exists($maintained_status{$filename})) {
1110 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1113 return $maintained_status{$filename} =~ /obsolete/i;
1116 sub is_SPDX_License_valid {
1119 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1121 my $root_path = abs_path($root);
1122 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1123 return 0 if ($status ne "");
1127 my $camelcase_seeded = 0;
1128 sub seed_camelcase_includes {
1129 return if ($camelcase_seeded);
1132 my $camelcase_cache = "";
1133 my @include_files = ();
1135 $camelcase_seeded = 1;
1137 if (-e "$gitroot") {
1138 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1139 chomp $git_last_include_commit;
1140 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1142 my $last_mod_date = 0;
1143 $files = `find $root/include -name "*.h"`;
1144 @include_files = split('\n', $files);
1145 foreach my $file (@include_files) {
1146 my $date = POSIX::strftime("%Y%m%d%H%M",
1147 localtime((stat $file)[9]));
1148 $last_mod_date = $date if ($last_mod_date < $date);
1150 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1153 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1154 open(my $camelcase_file, '<', "$camelcase_cache")
1155 or warn "$P: Can't read '$camelcase_cache' $!\n";
1156 while (<$camelcase_file>) {
1160 close($camelcase_file);
1165 if (-e "$gitroot") {
1166 $files = `${git_command} ls-files "include/*.h"`;
1167 @include_files = split('\n', $files);
1170 foreach my $file (@include_files) {
1171 seed_camelcase_file($file);
1174 if ($camelcase_cache ne "") {
1175 unlink glob ".checkpatch-camelcase.*";
1176 open(my $camelcase_file, '>', "$camelcase_cache")
1177 or warn "$P: Can't write '$camelcase_cache' $!\n";
1178 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1179 print $camelcase_file ("$_\n");
1181 close($camelcase_file);
1185 sub git_is_single_file {
1186 my ($filename) = @_;
1188 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1190 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1191 my $count = $output =~ tr/\n//;
1192 return $count eq 1 && $output =~ m{^${filename}$};
1195 sub git_commit_info {
1196 my ($commit, $id, $desc) = @_;
1198 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1200 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1201 $output =~ s/^\s*//gm;
1202 my @lines = split("\n", $output);
1204 return ($id, $desc) if ($#lines < 0);
1206 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1207 # Maybe one day convert this block of bash into something that returns
1208 # all matching commit ids, but it's very slow...
1210 # echo "checking commits $1..."
1211 # git rev-list --remotes | grep -i "^$1" |
1212 # while read line ; do
1213 # git log --format='%H %s' -1 $line |
1214 # echo "commit $(cut -c 1-12,41-)"
1216 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1217 $lines[0] =~ /^fatal: bad object $commit/) {
1220 $id = substr($lines[0], 0, 12);
1221 $desc = substr($lines[0], 41);
1224 return ($id, $desc);
1227 $chk_signoff = 0 if ($file);
1232 my @fixed_inserted = ();
1233 my @fixed_deleted = ();
1236 # If input is git commits, extract all commits from the commit expressions.
1237 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1238 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1242 foreach my $commit_expr (@ARGV) {
1244 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1245 $git_range = "-$2 $1";
1246 } elsif ($commit_expr =~ m/\.\./) {
1247 $git_range = "$commit_expr";
1249 $git_range = "-1 $commit_expr";
1251 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1252 foreach my $line (split(/\n/, $lines)) {
1253 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1254 next if (!defined($1) || !defined($2));
1257 unshift(@commits, $sha1);
1258 $git_commits{$sha1} = $subject;
1261 die "$P: no git commits after extraction!\n" if (@commits == 0);
1266 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1267 for my $filename (@ARGV) {
1269 my $is_git_file = git_is_single_file($filename);
1270 my $oldfile = $file;
1271 $file = 1 if ($is_git_file);
1273 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1274 die "$P: $filename: git format-patch failed - $!\n";
1276 open($FILE, '-|', "diff -u /dev/null $filename") ||
1277 die "$P: $filename: diff failed - $!\n";
1278 } elsif ($filename eq '-') {
1279 open($FILE, '<&STDIN');
1281 open($FILE, '<', "$filename") ||
1282 die "$P: $filename: open failed - $!\n";
1284 if ($filename eq '-') {
1285 $vname = 'Your patch';
1287 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1293 push(@rawlines, $_);
1294 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1298 if ($#ARGV > 0 && $quiet == 0) {
1299 print '-' x length($vname) . "\n";
1301 print '-' x length($vname) . "\n";
1304 if (!process($filename)) {
1310 @fixed_inserted = ();
1311 @fixed_deleted = ();
1313 @modifierListFile = ();
1316 $file = $oldfile if ($is_git_file);
1320 hash_show_words(\%use_type, "Used");
1321 hash_show_words(\%ignore_type, "Ignored");
1323 if (!$perl_version_ok) {
1326 NOTE: perl $^V is not modern enough to detect all possible issues.
1327 An upgrade to at least perl $minimum_perl_version is suggested.
1333 NOTE: If any of the errors are false positives, please report
1334 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1341 sub top_of_kernel_tree {
1345 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1346 "README", "Documentation", "arch", "include", "drivers",
1347 "fs", "init", "ipc", "kernel", "lib", "scripts",
1350 foreach my $check (@tree_check) {
1351 if (! -e $root . '/' . $check) {
1359 my ($formatted_email) = @_;
1363 my $name_comment = "";
1367 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1370 $comment = $3 if defined $3;
1371 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1373 $comment = $2 if defined $2;
1374 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1376 $comment = $2 if defined $2;
1377 $formatted_email =~ s/\Q$address\E.*$//;
1378 $name = $formatted_email;
1379 $name = trim($name);
1380 $name =~ s/^\"|\"$//g;
1381 # If there's a name left after stripping spaces and
1382 # leading quotes, and the address doesn't have both
1383 # leading and trailing angle brackets, the address
1385 # "joe smith joe@smith.com" bad
1386 # "joe smith <joe@smith.com" bad
1387 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1394 # Extract comments from names excluding quoted parts
1395 # "John D. (Doe)" - Do not extract
1396 if ($name =~ s/\"(.+)\"//) {
1399 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1400 $name_comment .= trim($1);
1402 $name =~ s/^[ \"]+|[ \"]+$//g;
1403 $name = trim("$quoted $name");
1405 $address = trim($address);
1406 $address =~ s/^\<|\>$//g;
1407 $comment = trim($comment);
1409 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1410 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1411 $name = "\"$name\"";
1414 return ($name, $name_comment, $address, $comment);
1418 my ($name, $name_comment, $address, $comment) = @_;
1420 my $formatted_email;
1422 $name =~ s/^[ \"]+|[ \"]+$//g;
1423 $address = trim($address);
1424 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1426 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1427 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1428 $name = "\"$name\"";
1431 $name_comment = trim($name_comment);
1432 $name_comment = " $name_comment" if ($name_comment ne "");
1433 $comment = trim($comment);
1434 $comment = " $comment" if ($comment ne "");
1436 if ("$name" eq "") {
1437 $formatted_email = "$address";
1439 $formatted_email = "$name$name_comment <$address>";
1441 $formatted_email .= "$comment";
1442 return $formatted_email;
1445 sub reformat_email {
1448 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1449 return format_email($email_name, $name_comment, $email_address, $comment);
1452 sub same_email_addresses {
1453 my ($email1, $email2) = @_;
1455 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1456 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1458 return $email1_name eq $email2_name &&
1459 $email1_address eq $email2_address &&
1460 $name1_comment eq $name2_comment &&
1461 $comment1 eq $comment2;
1467 foreach my $path (split(/:/, $ENV{PATH})) {
1468 if (-e "$path/$bin") {
1469 return "$path/$bin";
1479 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1480 if (-e "$path/$conf") {
1481 return "$path/$conf";
1493 for my $c (split(//, $str)) {
1497 for (; ($n % $tabsize) != 0; $n++) {
1509 (my $res = shift) =~ tr/\t/ /c;
1516 # Drop the diff line leader and expand tabs
1518 $line = expand_tabs($line);
1520 # Pick the indent from the front of the line.
1521 my ($white) = ($line =~ /^(\s*)/);
1523 return (length($line), length($white));
1526 my $sanitise_quote = '';
1528 sub sanitise_line_reset {
1529 my ($in_comment) = @_;
1532 $sanitise_quote = '*/';
1534 $sanitise_quote = '';
1547 # Always copy over the diff marker.
1548 $res = substr($line, 0, 1);
1550 for ($off = 1; $off < length($line); $off++) {
1551 $c = substr($line, $off, 1);
1553 # Comments we are whacking completely including the begin
1554 # and end, all to $;.
1555 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1556 $sanitise_quote = '*/';
1558 substr($res, $off, 2, "$;$;");
1562 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1563 $sanitise_quote = '';
1564 substr($res, $off, 2, "$;$;");
1568 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1569 $sanitise_quote = '//';
1571 substr($res, $off, 2, $sanitise_quote);
1576 # A \ in a string means ignore the next character.
1577 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1579 substr($res, $off, 2, 'XX');
1584 if ($c eq "'" || $c eq '"') {
1585 if ($sanitise_quote eq '') {
1586 $sanitise_quote = $c;
1588 substr($res, $off, 1, $c);
1590 } elsif ($sanitise_quote eq $c) {
1591 $sanitise_quote = '';
1595 #print "c<$c> SQ<$sanitise_quote>\n";
1596 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1597 substr($res, $off, 1, $;);
1598 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1599 substr($res, $off, 1, $;);
1600 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1601 substr($res, $off, 1, 'X');
1603 substr($res, $off, 1, $c);
1607 if ($sanitise_quote eq '//') {
1608 $sanitise_quote = '';
1611 # The pathname on a #include may be surrounded by '<' and '>'.
1612 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1613 my $clean = 'X' x length($1);
1614 $res =~ s@\<.*\>@<$clean>@;
1616 # The whole of a #error is a string.
1617 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1618 my $clean = 'X' x length($1);
1619 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1622 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1624 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1630 sub get_quoted_string {
1631 my ($line, $rawline) = @_;
1633 return "" if (!defined($line) || !defined($rawline));
1634 return "" if ($line !~ m/($String)/g);
1635 return substr($rawline, $-[0], $+[0] - $-[0]);
1638 sub ctx_statement_block {
1639 my ($linenr, $remain, $off) = @_;
1640 my $line = $linenr - 1;
1643 my $coff = $off - 1;
1657 @stack = (['', 0]) if ($#stack == -1);
1659 #warn "CSB: blk<$blk> remain<$remain>\n";
1660 # If we are about to drop off the end, pull in more
1663 for (; $remain > 0; $line++) {
1664 last if (!defined $lines[$line]);
1665 next if ($lines[$line] =~ /^-/);
1668 $blk .= $lines[$line] . "\n";
1669 $len = length($blk);
1673 # Bail if there is no further context.
1674 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1678 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1684 $c = substr($blk, $off, 1);
1685 $remainder = substr($blk, $off);
1687 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1689 # Handle nested #if/#else.
1690 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1691 push(@stack, [ $type, $level ]);
1692 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1693 ($type, $level) = @{$stack[$#stack - 1]};
1694 } elsif ($remainder =~ /^#\s*endif\b/) {
1695 ($type, $level) = @{pop(@stack)};
1698 # Statement ends at the ';' or a close '}' at the
1700 if ($level == 0 && $c eq ';') {
1704 # An else is really a conditional as long as its not else if
1705 if ($level == 0 && $coff_set == 0 &&
1706 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1707 $remainder =~ /^(else)(?:\s|{)/ &&
1708 $remainder !~ /^else\s+if\b/) {
1709 $coff = $off + length($1) - 1;
1711 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1712 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1715 if (($type eq '' || $type eq '(') && $c eq '(') {
1719 if ($type eq '(' && $c eq ')') {
1721 $type = ($level != 0)? '(' : '';
1723 if ($level == 0 && $coff < $soff) {
1726 #warn "CSB: mark coff<$coff>\n";
1729 if (($type eq '' || $type eq '{') && $c eq '{') {
1733 if ($type eq '{' && $c eq '}') {
1735 $type = ($level != 0)? '{' : '';
1738 if (substr($blk, $off + 1, 1) eq ';') {
1744 # Preprocessor commands end at the newline unless escaped.
1745 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1753 # We are truly at the end, so shuffle to the next line.
1760 my $statement = substr($blk, $soff, $off - $soff + 1);
1761 my $condition = substr($blk, $soff, $coff - $soff + 1);
1763 #warn "STATEMENT<$statement>\n";
1764 #warn "CONDITION<$condition>\n";
1766 #print "coff<$coff> soff<$off> loff<$loff>\n";
1768 return ($statement, $condition,
1769 $line, $remain + 1, $off - $loff + 1, $level);
1772 sub statement_lines {
1775 # Strip the diff line prefixes and rip blank lines at start and end.
1776 $stmt =~ s/(^|\n)./$1/g;
1780 my @stmt_lines = ($stmt =~ /\n/g);
1782 return $#stmt_lines + 2;
1785 sub statement_rawlines {
1788 my @stmt_lines = ($stmt =~ /\n/g);
1790 return $#stmt_lines + 2;
1793 sub statement_block_size {
1796 $stmt =~ s/(^|\n)./$1/g;
1802 my @stmt_lines = ($stmt =~ /\n/g);
1803 my @stmt_statements = ($stmt =~ /;/g);
1805 my $stmt_lines = $#stmt_lines + 2;
1806 my $stmt_statements = $#stmt_statements + 1;
1808 if ($stmt_lines > $stmt_statements) {
1811 return $stmt_statements;
1815 sub ctx_statement_full {
1816 my ($linenr, $remain, $off) = @_;
1817 my ($statement, $condition, $level);
1821 # Grab the first conditional/block pair.
1822 ($statement, $condition, $linenr, $remain, $off, $level) =
1823 ctx_statement_block($linenr, $remain, $off);
1824 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1825 push(@chunks, [ $condition, $statement ]);
1826 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1827 return ($level, $linenr, @chunks);
1830 # Pull in the following conditional/block pairs and see if they
1831 # could continue the statement.
1833 ($statement, $condition, $linenr, $remain, $off, $level) =
1834 ctx_statement_block($linenr, $remain, $off);
1835 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1836 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1838 push(@chunks, [ $condition, $statement ]);
1841 return ($level, $linenr, @chunks);
1845 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1847 my $start = $linenr - 1;
1854 my @stack = ($level);
1855 for ($line = $start; $remain > 0; $line++) {
1856 next if ($rawlines[$line] =~ /^-/);
1859 $blk .= $rawlines[$line];
1861 # Handle nested #if/#else.
1862 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1863 push(@stack, $level);
1864 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1865 $level = $stack[$#stack - 1];
1866 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1867 $level = pop(@stack);
1870 foreach my $c (split(//, $lines[$line])) {
1871 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1877 if ($c eq $close && $level > 0) {
1879 last if ($level == 0);
1880 } elsif ($c eq $open) {
1885 if (!$outer || $level <= 1) {
1886 push(@res, $rawlines[$line]);
1889 last if ($level == 0);
1892 return ($level, @res);
1894 sub ctx_block_outer {
1895 my ($linenr, $remain) = @_;
1897 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1901 my ($linenr, $remain) = @_;
1903 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1907 my ($linenr, $remain, $off) = @_;
1909 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1912 sub ctx_block_level {
1913 my ($linenr, $remain) = @_;
1915 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1917 sub ctx_statement_level {
1918 my ($linenr, $remain, $off) = @_;
1920 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1923 sub ctx_locate_comment {
1924 my ($first_line, $end_line) = @_;
1926 # If c99 comment on the current line, or the line before or after
1927 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1928 return $current_comment if (defined $current_comment);
1929 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1930 return $current_comment if (defined $current_comment);
1931 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1932 return $current_comment if (defined $current_comment);
1934 # Catch a comment on the end of the line itself.
1935 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1936 return $current_comment if (defined $current_comment);
1938 # Look through the context and try and figure out if there is a
1941 $current_comment = '';
1942 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1943 my $line = $rawlines[$linenr - 1];
1945 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1948 if ($line =~ m@/\*@) {
1951 if (!$in_comment && $current_comment ne '') {
1952 $current_comment = '';
1954 $current_comment .= $line . "\n" if ($in_comment);
1955 if ($line =~ m@\*/@) {
1960 chomp($current_comment);
1961 return($current_comment);
1963 sub ctx_has_comment {
1964 my ($first_line, $end_line) = @_;
1965 my $cmt = ctx_locate_comment($first_line, $end_line);
1967 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1968 ##print "CMMT: $cmt\n";
1970 return ($cmt ne '');
1974 my ($linenr, $cnt) = @_;
1976 my $offset = $linenr - 1;
1981 $line = $rawlines[$offset++];
1982 next if (defined($line) && $line =~ /^-/);
1990 my ($linenr, $lc) = @_;
1992 my $stat_real = raw_line($linenr, 0);
1993 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1994 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2001 my ($linenr, $cnt, $here) = @_;
2003 my $herectx = $here . "\n";
2004 for (my $n = 0; $n < $cnt; $n++) {
2005 $herectx .= raw_line($linenr, $n) . "\n";
2016 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2019 $coded = sprintf("^%c", unpack('C', $2) + 64);
2028 my $av_preprocessor = 0;
2033 sub annotate_reset {
2034 $av_preprocessor = 0;
2036 @av_paren_type = ('E');
2037 $av_pend_colon = 'O';
2040 sub annotate_values {
2041 my ($stream, $type) = @_;
2044 my $var = '_' x length($stream);
2047 print "$stream\n" if ($dbg_values > 1);
2049 while (length($cur)) {
2050 @av_paren_type = ('E') if ($#av_paren_type < 0);
2051 print " <" . join('', @av_paren_type) .
2052 "> <$type> <$av_pending>" if ($dbg_values > 1);
2053 if ($cur =~ /^(\s+)/o) {
2054 print "WS($1)\n" if ($dbg_values > 1);
2055 if ($1 =~ /\n/ && $av_preprocessor) {
2056 $type = pop(@av_paren_type);
2057 $av_preprocessor = 0;
2060 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2061 print "CAST($1)\n" if ($dbg_values > 1);
2062 push(@av_paren_type, $type);
2065 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2066 print "DECLARE($1)\n" if ($dbg_values > 1);
2069 } elsif ($cur =~ /^($Modifier)\s*/) {
2070 print "MODIFIER($1)\n" if ($dbg_values > 1);
2073 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2074 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2075 $av_preprocessor = 1;
2076 push(@av_paren_type, $type);
2082 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2083 print "UNDEF($1)\n" if ($dbg_values > 1);
2084 $av_preprocessor = 1;
2085 push(@av_paren_type, $type);
2087 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2088 print "PRE_START($1)\n" if ($dbg_values > 1);
2089 $av_preprocessor = 1;
2091 push(@av_paren_type, $type);
2092 push(@av_paren_type, $type);
2095 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2096 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2097 $av_preprocessor = 1;
2099 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2103 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2104 print "PRE_END($1)\n" if ($dbg_values > 1);
2106 $av_preprocessor = 1;
2108 # Assume all arms of the conditional end as this
2109 # one does, and continue as if the #endif was not here.
2110 pop(@av_paren_type);
2111 push(@av_paren_type, $type);
2114 } elsif ($cur =~ /^(\\\n)/o) {
2115 print "PRECONT($1)\n" if ($dbg_values > 1);
2117 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2118 print "ATTR($1)\n" if ($dbg_values > 1);
2119 $av_pending = $type;
2122 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2123 print "SIZEOF($1)\n" if ($dbg_values > 1);
2129 } elsif ($cur =~ /^(if|while|for)\b/o) {
2130 print "COND($1)\n" if ($dbg_values > 1);
2134 } elsif ($cur =~/^(case)/o) {
2135 print "CASE($1)\n" if ($dbg_values > 1);
2136 $av_pend_colon = 'C';
2139 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2140 print "KEYWORD($1)\n" if ($dbg_values > 1);
2143 } elsif ($cur =~ /^(\()/o) {
2144 print "PAREN('$1')\n" if ($dbg_values > 1);
2145 push(@av_paren_type, $av_pending);
2149 } elsif ($cur =~ /^(\))/o) {
2150 my $new_type = pop(@av_paren_type);
2151 if ($new_type ne '_') {
2153 print "PAREN('$1') -> $type\n"
2154 if ($dbg_values > 1);
2156 print "PAREN('$1')\n" if ($dbg_values > 1);
2159 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2160 print "FUNC($1)\n" if ($dbg_values > 1);
2164 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2165 if (defined $2 && $type eq 'C' || $type eq 'T') {
2166 $av_pend_colon = 'B';
2167 } elsif ($type eq 'E') {
2168 $av_pend_colon = 'L';
2170 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2173 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2174 print "IDENT($1)\n" if ($dbg_values > 1);
2177 } elsif ($cur =~ /^($Assignment)/o) {
2178 print "ASSIGN($1)\n" if ($dbg_values > 1);
2181 } elsif ($cur =~/^(;|{|})/) {
2182 print "END($1)\n" if ($dbg_values > 1);
2184 $av_pend_colon = 'O';
2186 } elsif ($cur =~/^(,)/) {
2187 print "COMMA($1)\n" if ($dbg_values > 1);
2190 } elsif ($cur =~ /^(\?)/o) {
2191 print "QUESTION($1)\n" if ($dbg_values > 1);
2194 } elsif ($cur =~ /^(:)/o) {
2195 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2197 substr($var, length($res), 1, $av_pend_colon);
2198 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2203 $av_pend_colon = 'O';
2205 } elsif ($cur =~ /^(\[)/o) {
2206 print "CLOSE($1)\n" if ($dbg_values > 1);
2209 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2212 print "OPV($1)\n" if ($dbg_values > 1);
2219 substr($var, length($res), 1, $variant);
2222 } elsif ($cur =~ /^($Operators)/o) {
2223 print "OP($1)\n" if ($dbg_values > 1);
2224 if ($1 ne '++' && $1 ne '--') {
2228 } elsif ($cur =~ /(^.)/o) {
2229 print "C($1)\n" if ($dbg_values > 1);
2232 $cur = substr($cur, length($1));
2233 $res .= $type x length($1);
2237 return ($res, $var);
2241 my ($possible, $line) = @_;
2242 my $notPermitted = qr{(?:
2259 ^(?:typedef|struct|enum)\b
2261 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2262 if ($possible !~ $notPermitted) {
2263 # Check for modifiers.
2264 $possible =~ s/\s*$Storage\s*//g;
2265 $possible =~ s/\s*$Sparse\s*//g;
2266 if ($possible =~ /^\s*$/) {
2268 } elsif ($possible =~ /\s/) {
2269 $possible =~ s/\s*$Type\s*//g;
2270 for my $modifier (split(' ', $possible)) {
2271 if ($modifier !~ $notPermitted) {
2272 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2273 push(@modifierListFile, $modifier);
2278 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2279 push(@typeListFile, $possible);
2283 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2292 $type =~ tr/[a-z]/[A-Z]/;
2294 return defined $use_type{$type} if (scalar keys %use_type > 0);
2296 return !defined $ignore_type{$type};
2300 my ($level, $type, $msg) = @_;
2302 if (!show_type($type) ||
2303 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2308 if ($level eq 'ERROR') {
2310 } elsif ($level eq 'WARNING') {
2316 $output .= $prefix . $level . ':';
2318 $output .= BLUE if ($color);
2319 $output .= "$type:";
2321 $output .= RESET if ($color);
2322 $output .= ' ' . $msg . "\n";
2325 my @lines = split("\n", $output, -1);
2326 splice(@lines, 1, 1);
2327 $output = join("\n", @lines);
2331 $output = (split('\n', $output))[0] . "\n";
2334 if ($verbose && exists($verbose_messages{$type}) &&
2335 !exists($verbose_emitted{$type})) {
2336 $output .= $verbose_messages{$type} . "\n\n";
2337 $verbose_emitted{$type} = 1;
2340 push(our @report, $output);
2349 sub fixup_current_range {
2350 my ($lineRef, $offset, $length) = @_;
2352 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2355 my $no = $o + $offset;
2356 my $nl = $l + $length;
2357 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2361 sub fix_inserted_deleted_lines {
2362 my ($linesRef, $insertedRef, $deletedRef) = @_;
2364 my $range_last_linenr = 0;
2365 my $delta_offset = 0;
2370 my $next_insert = 0;
2371 my $next_delete = 0;
2375 my $inserted = @{$insertedRef}[$next_insert++];
2376 my $deleted = @{$deletedRef}[$next_delete++];
2378 foreach my $old_line (@{$linesRef}) {
2380 my $line = $old_line; #don't modify the array
2381 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2383 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2384 $range_last_linenr = $new_linenr;
2385 fixup_current_range(\$line, $delta_offset, 0);
2388 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2389 $deleted = @{$deletedRef}[$next_delete++];
2391 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2394 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2395 push(@lines, ${$inserted}{'LINE'});
2396 $inserted = @{$insertedRef}[$next_insert++];
2398 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2402 push(@lines, $line);
2412 sub fix_insert_line {
2413 my ($linenr, $line) = @_;
2419 push(@fixed_inserted, $inserted);
2422 sub fix_delete_line {
2423 my ($linenr, $line) = @_;
2430 push(@fixed_deleted, $deleted);
2434 my ($type, $msg) = @_;
2436 if (report("ERROR", $type, $msg)) {
2444 my ($type, $msg) = @_;
2446 if (report("WARNING", $type, $msg)) {
2454 my ($type, $msg) = @_;
2456 if ($check && report("CHECK", $type, $msg)) {
2464 sub check_absolute_file {
2465 my ($absolute, $herecurr) = @_;
2466 my $file = $absolute;
2468 ##print "absolute<$absolute>\n";
2470 # See if any suffix of this path is a path within the tree.
2471 while ($file =~ s@^[^/]*/@@) {
2472 if (-f "$root/$file") {
2473 ##print "file<$file>\n";
2481 # It is, so see if the prefix is acceptable.
2482 my $prefix = $absolute;
2483 substr($prefix, -length($file)) = '';
2485 ##print "prefix<$prefix>\n";
2486 if ($prefix ne ".../") {
2487 WARN("USE_RELATIVE_PATH",
2488 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2495 $string =~ s/^\s+|\s+$//g;
2503 $string =~ s/^\s+//;
2511 $string =~ s/\s+$//;
2516 sub string_find_replace {
2517 my ($string, $find, $replace) = @_;
2519 $string =~ s/$find/$replace/g;
2527 my $source_indent = $tabsize;
2528 my $max_spaces_before_tab = $source_indent - 1;
2529 my $spaces_to_tab = " " x $source_indent;
2531 #convert leading spaces to tabs
2532 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2533 #Remove spaces before a tab
2534 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2539 sub pos_last_openparen {
2544 my $opens = $line =~ tr/\(/\(/;
2545 my $closes = $line =~ tr/\)/\)/;
2547 my $last_openparen = 0;
2549 if (($opens == 0) || ($closes >= $opens)) {
2553 my $len = length($line);
2555 for ($pos = 0; $pos < $len; $pos++) {
2556 my $string = substr($line, $pos);
2557 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2558 $pos += length($1) - 1;
2559 } elsif (substr($line, $pos, 1) eq '(') {
2560 $last_openparen = $pos;
2561 } elsif (index($string, '(') == -1) {
2566 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2569 sub get_raw_comment {
2570 my ($line, $rawline) = @_;
2573 for my $i (0 .. (length($line) - 1)) {
2574 if (substr($line, $i, 1) eq "$;") {
2575 $comment .= substr($rawline, $i, 1);
2582 sub exclude_global_initialisers {
2583 my ($realfile) = @_;
2585 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2586 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2587 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2588 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2592 my $filename = shift;
2598 my $stashrawline="";
2608 my $authorsignoff = 0;
2609 my $author_sob = '';
2611 my $is_binding_patch = -1;
2612 my $in_header_lines = $file ? 0 : 1;
2613 my $in_commit_log = 0; #Scanning lines before patch
2614 my $has_patch_separator = 0; #Found a --- line
2615 my $has_commit_log = 0; #Encountered lines before patch
2616 my $commit_log_lines = 0; #Number of commit log lines
2617 my $commit_log_possible_stack_dump = 0;
2618 my $commit_log_long_line = 0;
2619 my $commit_log_has_diff = 0;
2620 my $reported_maintainer_file = 0;
2621 my $non_utf8_charset = 0;
2623 my $last_git_commit_id_linenr = -1;
2625 my $last_blank_line = 0;
2626 my $last_coalesced_string_linenr = -1;
2634 # Trace the real file/line as we go.
2639 my $context_function; #undef'd unless there's a known function
2641 my $comment_edge = 0;
2645 my $prev_values = 'E';
2648 my %suppress_ifbraces;
2649 my %suppress_whiletrailers;
2650 my %suppress_export;
2651 my $suppress_statement = 0;
2653 my %signatures = ();
2655 # Pre-scan the patch sanitizing the lines.
2656 # Pre-scan the patch looking for any __setup documentation.
2658 my @setup_docs = ();
2661 my $camelcase_file_seeded = 0;
2663 my $checklicenseline = 1;
2665 sanitise_line_reset();
2667 foreach my $rawline (@rawlines) {
2671 push(@fixed, $rawline) if ($fix);
2673 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2675 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2680 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2689 # Guestimate if this is a continuing comment. Run
2690 # the context looking for a comment "edge". If this
2691 # edge is a close comment then we must be in a comment
2695 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2696 next if (defined $rawlines[$ln - 1] &&
2697 $rawlines[$ln - 1] =~ /^-/);
2699 #print "RAW<$rawlines[$ln - 1]>\n";
2700 last if (!defined $rawlines[$ln - 1]);
2701 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2702 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2707 if (defined $edge && $edge eq '*/') {
2711 # Guestimate if this is a continuing comment. If this
2712 # is the start of a diff block and this line starts
2713 # ' *' then it is very likely a comment.
2714 if (!defined $edge &&
2715 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2720 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2721 sanitise_line_reset($in_comment);
2723 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2724 # Standardise the strings and chars within the input to
2725 # simplify matching -- only bother with positive lines.
2726 $line = sanitise_line($rawline);
2728 push(@lines, $line);
2731 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2736 #print "==>$rawline\n";
2737 #print "-->$line\n";
2739 if ($setup_docs && $line =~ /^\+/) {
2740 push(@setup_docs, $line);
2749 foreach my $line (@lines) {
2752 my $sline = $line; #copy of $line
2753 $sline =~ s/$;/ /g; #with comments as spaces
2755 my $rawline = $rawlines[$linenr - 1];
2756 my $raw_comment = get_raw_comment($line, $rawline);
2758 # check if it's a mode change, rename or start of a patch
2759 if (!$in_commit_log &&
2760 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2761 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2762 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2766 #extract the line range in the file after the patch is applied
2767 if (!$in_commit_log &&
2768 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2771 $first_line = $linenr + 1;
2781 %suppress_ifbraces = ();
2782 %suppress_whiletrailers = ();
2783 %suppress_export = ();
2784 $suppress_statement = 0;
2785 if ($context =~ /\b(\w+)\s*\(/) {
2786 $context_function = $1;
2788 undef $context_function;
2792 # track the line number as we move through the hunk, note that
2793 # new versions of GNU diff omit the leading space on completely
2794 # blank context lines so we need to count that too.
2795 } elsif ($line =~ /^( |\+|$)/) {
2797 $realcnt-- if ($realcnt != 0);
2799 # Measure the line length and indent.
2800 ($length, $indent) = line_stats($rawline);
2802 # Track the previous line.
2803 ($prevline, $stashline) = ($stashline, $line);
2804 ($previndent, $stashindent) = ($stashindent, $indent);
2805 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2807 #warn "line<$line>\n";
2809 } elsif ($realcnt == 1) {
2813 my $hunk_line = ($realcnt != 0);
2815 $here = "#$linenr: " if (!$file);
2816 $here = "#$realline: " if ($file);
2819 # extract the filename as it passes
2820 if ($line =~ /^diff --git.*?(\S+)$/) {
2822 $realfile =~ s@^([^/]*)/@@ if (!$file);
2825 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2827 $realfile =~ s@^([^/]*)/@@ if (!$file);
2831 if (!$file && $tree && $p1_prefix ne '' &&
2832 -e "$root/$p1_prefix") {
2833 WARN("PATCH_PREFIX",
2834 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2837 if ($realfile =~ m@^include/asm/@) {
2838 ERROR("MODIFIED_INCLUDE_ASM",
2839 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2844 #make up the handle for any error we report on this line
2846 $prefix = "$realfile:$realline: "
2849 $prefix = "$filename:$realline: ";
2851 $prefix = "$filename:$linenr: ";
2856 if (is_maintained_obsolete($realfile)) {
2858 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2860 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2863 $check = $check_orig;
2865 $checklicenseline = 1;
2867 if ($realfile !~ /^MAINTAINERS/) {
2868 my $last_binding_patch = $is_binding_patch;
2870 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2872 if (($last_binding_patch != -1) &&
2873 ($last_binding_patch ^ $is_binding_patch)) {
2874 WARN("DT_SPLIT_BINDING_PATCH",
2875 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2882 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2884 my $hereline = "$here\n$rawline\n";
2885 my $herecurr = "$here\n$rawline\n";
2886 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2888 $cnt_lines++ if ($realcnt != 0);
2890 # Verify the existence of a commit log if appropriate
2891 # 2 is used because a $signature is counted in $commit_log_lines
2892 if ($in_commit_log) {
2893 if ($line !~ /^\s*$/) {
2894 $commit_log_lines++; #could be a $signature
2896 } elsif ($has_commit_log && $commit_log_lines < 2) {
2897 WARN("COMMIT_MESSAGE",
2898 "Missing commit description - Add an appropriate one\n");
2899 $commit_log_lines = 2; #warn only once
2902 # Check if the commit log has what seems like a diff which can confuse patch
2903 if ($in_commit_log && !$commit_log_has_diff &&
2904 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2905 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2906 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2907 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2908 ERROR("DIFF_IN_COMMIT_MSG",
2909 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2910 $commit_log_has_diff = 1;
2913 # Check for incorrect file permissions
2914 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2915 my $permhere = $here . "FILE: $realfile\n";
2916 if ($realfile !~ m@scripts/@ &&
2917 $realfile !~ /\.(py|pl|awk|sh)$/) {
2918 ERROR("EXECUTE_PERMISSIONS",
2919 "do not set execute permissions for source files\n" . $permhere);
2923 # Check the patch for a From:
2924 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2926 my $curline = $linenr;
2927 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2930 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2932 $author = reformat_email($author);
2935 # Check the patch for a signoff:
2936 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2939 if ($author ne '' && $authorsignoff != 1) {
2940 if (same_email_addresses($1, $author)) {
2944 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2945 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2947 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2950 } elsif (lc $email_address eq lc $author_address) {
2953 } elsif ($email_name eq $author_name) {
2957 my $address1 = $email_address;
2958 my $address2 = $author_address;
2960 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2963 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2966 if ($address1 eq $address2) {
2974 # Check for patch separator
2975 if ($line =~ /^---$/) {
2976 $has_patch_separator = 1;
2980 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2981 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2982 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2983 $reported_maintainer_file = 1;
2986 # Check signature styles
2987 if (!$in_header_lines &&
2988 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2989 my $space_before = $1;
2991 my $space_after = $3;
2993 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2995 if ($sign_off !~ /$signature_tags/) {
2996 my $suggested_signature = find_standard_signature($sign_off);
2997 if ($suggested_signature eq "") {
2998 WARN("BAD_SIGN_OFF",
2999 "Non-standard signature: $sign_off\n" . $herecurr);
3001 if (WARN("BAD_SIGN_OFF",
3002 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3004 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3008 if (defined $space_before && $space_before ne "") {
3009 if (WARN("BAD_SIGN_OFF",
3010 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3012 $fixed[$fixlinenr] =
3013 "$ucfirst_sign_off $email";
3016 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3017 if (WARN("BAD_SIGN_OFF",
3018 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3020 $fixed[$fixlinenr] =
3021 "$ucfirst_sign_off $email";
3025 if (!defined $space_after || $space_after ne " ") {
3026 if (WARN("BAD_SIGN_OFF",
3027 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3029 $fixed[$fixlinenr] =
3030 "$ucfirst_sign_off $email";
3034 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3035 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3036 if ($suggested_email eq "") {
3037 ERROR("BAD_SIGN_OFF",
3038 "Unrecognized email address: '$email'\n" . $herecurr);
3040 my $dequoted = $suggested_email;
3041 $dequoted =~ s/^"//;
3042 $dequoted =~ s/" </ </;
3043 # Don't force email to have quotes
3044 # Allow just an angle bracketed address
3045 if (!same_email_addresses($email, $suggested_email)) {
3046 if (WARN("BAD_SIGN_OFF",
3047 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3049 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3053 # Address part shouldn't have comments
3054 my $stripped_address = $email_address;
3055 $stripped_address =~ s/\([^\(\)]*\)//g;
3056 if ($email_address ne $stripped_address) {
3057 if (WARN("BAD_SIGN_OFF",
3058 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3060 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3064 # Only one name comment should be allowed
3065 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3066 if ($comment_count > 1) {
3067 WARN("BAD_SIGN_OFF",
3068 "Use a single name comment in email: '$email'\n" . $herecurr);
3072 # stable@vger.kernel.org or stable@kernel.org shouldn't
3073 # have an email name. In addition comments should strictly
3075 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3076 if (($comment ne "" && $comment !~ /^#.+/) ||
3077 ($email_name ne "")) {
3078 my $cur_name = $email_name;
3079 my $new_comment = $comment;
3080 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3082 # Remove brackets enclosing comment text
3083 # and # from start of comments to get comment text
3084 $new_comment =~ s/^\((.*)\)$/$1/;
3085 $new_comment =~ s/^\[(.*)\]$/$1/;
3086 $new_comment =~ s/^[\s\#]+|\s+$//g;
3088 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3089 $new_comment = " # $new_comment" if ($new_comment ne "");
3090 my $new_email = "$email_address$new_comment";
3092 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3093 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3095 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3098 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3099 my $new_comment = $comment;
3101 # Extract comment text from within brackets or
3102 # c89 style /*...*/ comments
3103 $new_comment =~ s/^\[(.*)\]$/$1/;
3104 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3106 $new_comment = trim($new_comment);
3107 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3108 $new_comment = "($new_comment)" if ($new_comment ne "");
3109 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3111 if (WARN("BAD_SIGN_OFF",
3112 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3114 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3119 # Check for duplicate signatures
3120 my $sig_nospace = $line;
3121 $sig_nospace =~ s/\s//g;
3122 $sig_nospace = lc($sig_nospace);
3123 if (defined $signatures{$sig_nospace}) {
3124 WARN("BAD_SIGN_OFF",
3125 "Duplicate signature\n" . $herecurr);
3127 $signatures{$sig_nospace} = 1;
3130 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3131 if ($sign_off =~ /^co-developed-by:$/i) {
3132 if ($email eq $author) {
3133 WARN("BAD_SIGN_OFF",
3134 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3136 if (!defined $lines[$linenr]) {
3137 WARN("BAD_SIGN_OFF",
3138 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3139 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3140 WARN("BAD_SIGN_OFF",
3141 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3142 } elsif ($1 ne $email) {
3143 WARN("BAD_SIGN_OFF",
3144 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3149 # Check Fixes: styles is correct
3150 if (!$in_header_lines &&
3151 $line =~ /^\s*fixes:?\s*(?:commit\s*)?[0-9a-f]{5,}\b/i) {
3152 my $orig_commit = "";
3153 my $id = "0123456789ab";
3154 my $title = "commit title";
3159 my $title_has_quotes = 0;
3161 if ($line =~ /(\s*fixes:?)\s+([0-9a-f]{5,})\s+($balanced_parens)/i) {
3166 $tag_case = 0 if $tag eq "Fixes:";
3167 $tag_space = 0 if ($line =~ /^fixes:? [0-9a-f]{5,} ($balanced_parens)/i);
3169 $id_length = 0 if ($orig_commit =~ /^[0-9a-f]{12}$/i);
3170 $id_case = 0 if ($orig_commit !~ /[A-F]/);
3172 # Always strip leading/trailing parens then double quotes if existing
3173 $title = substr($title, 1, -1);
3174 if ($title =~ /^".*"$/) {
3175 $title = substr($title, 1, -1);
3176 $title_has_quotes = 1;
3180 my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3183 if ($ctitle ne $title || $tag_case || $tag_space ||
3184 $id_length || $id_case || !$title_has_quotes) {
3185 if (WARN("BAD_FIXES_TAG",
3186 "Please use correct Fixes: style 'Fixes: <12 chars of sha1> (\"<title line>\")' - ie: 'Fixes: $cid (\"$ctitle\")'\n" . $herecurr) &&
3188 $fixed[$fixlinenr] = "Fixes: $cid (\"$ctitle\")";
3193 # Check email subject for common tools that don't need to be mentioned
3194 if ($in_header_lines &&
3195 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3196 WARN("EMAIL_SUBJECT",
3197 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3200 # Check for Gerrit Change-Ids not in any patch context
3201 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3202 if (ERROR("GERRIT_CHANGE_ID",
3203 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3205 fix_delete_line($fixlinenr, $rawline);
3209 # Check if the commit log is in a possible stack dump
3210 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3211 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3212 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3214 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3215 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3216 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3217 # stack dump address styles
3218 $commit_log_possible_stack_dump = 1;
3221 # Check for line lengths > 75 in commit log, warn once
3222 if ($in_commit_log && !$commit_log_long_line &&
3223 length($line) > 75 &&
3224 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3225 # file delta changes
3226 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3228 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3229 # A Fixes: or Link: line or signature tag line
3230 $commit_log_possible_stack_dump)) {
3231 WARN("COMMIT_LOG_LONG_LINE",
3232 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3233 $commit_log_long_line = 1;
3236 # Reset possible stack dump if a blank line is found
3237 if ($in_commit_log && $commit_log_possible_stack_dump &&
3239 $commit_log_possible_stack_dump = 0;
3242 # Check for lines starting with a #
3243 if ($in_commit_log && $line =~ /^#/) {
3244 if (WARN("COMMIT_COMMENT_SYMBOL",
3245 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3247 $fixed[$fixlinenr] =~ s/^/ /;
3251 # Check for git id commit length and improperly formed commit descriptions
3252 # A correctly formed commit description is:
3253 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3254 # with the commit subject '("' prefix and '")' suffix
3255 # This is a fairly compilicated block as it tests for what appears to be
3256 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3257 # possible SHA-1 matches.
3258 # A commit match can span multiple lines so this block attempts to find a
3259 # complete typical commit on a maximum of 3 lines
3260 if ($perl_version_ok &&
3261 $in_commit_log && !$commit_log_possible_stack_dump &&
3262 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3263 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3264 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3265 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3266 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3267 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3268 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3269 my $init_char = "c";
3270 my $orig_commit = "";
3275 my $id = '0123456789ab';
3276 my $orig_desc = "commit description";
3277 my $description = "";
3278 my $herectx = $herecurr;
3283 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3284 for (my $n = 0; $n < 2; $n++) {
3285 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3288 # Always strip leading/trailing parens then double quotes if existing
3289 $orig_desc = substr($orig_desc, 1, -1);
3290 if ($orig_desc =~ /^".*"$/) {
3291 $orig_desc = substr($orig_desc, 1, -1);
3296 last if ($#lines < $linenr + $n);
3297 $input .= " " . trim($rawlines[$linenr + $n]);
3298 $herectx .= "$rawlines[$linenr + $n]\n";
3300 $herectx = $herecurr if (!$has_parens);
3303 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3305 $orig_commit = lc($2);
3306 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3307 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3308 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3309 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3310 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3311 $orig_commit = lc($1);
3314 ($id, $description) = git_commit_info($orig_commit,
3318 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3319 $last_git_commit_id_linenr != $linenr - 1) {
3320 ERROR("GIT_COMMIT_ID",
3321 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3323 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3324 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3327 # Check for added, moved or deleted files
3328 if (!$reported_maintainer_file && !$in_commit_log &&
3329 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3330 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3331 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3332 (defined($1) || defined($2))))) {
3334 $reported_maintainer_file = 1;
3335 WARN("FILE_PATH_CHANGES",
3336 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3339 # Check for adding new DT bindings not in schema format
3340 if (!$in_commit_log &&
3341 ($line =~ /^new file mode\s*\d+\s*$/) &&
3342 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3343 WARN("DT_SCHEMA_BINDING_PATCH",
3344 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3347 # Check for wrappage within a valid hunk of the file
3348 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3349 ERROR("CORRUPTED_PATCH",
3350 "patch seems to be corrupt (line wrapped?)\n" .
3351 $herecurr) if (!$emitted_corrupt++);
3354 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3355 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3356 $rawline !~ m/^$UTF8*$/) {
3357 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3359 my $blank = copy_spacing($rawline);
3360 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3361 my $hereptr = "$hereline$ptr\n";
3364 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3367 # Check if it's the start of a commit log
3368 # (not a header line and we haven't seen the patch filename)
3369 if ($in_header_lines && $realfile =~ /^$/ &&
3370 !($rawline =~ /^\s+(?:\S|$)/ ||
3371 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3372 $in_header_lines = 0;
3374 $has_commit_log = 1;
3377 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3378 # declined it, i.e defined some charset where it is missing.
3379 if ($in_header_lines &&
3380 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3382 $non_utf8_charset = 1;
3385 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3386 $rawline =~ /$NON_ASCII_UTF8/) {
3387 WARN("UTF8_BEFORE_PATCH",
3388 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3391 # Check for absolute kernel paths in commit message
3392 if ($tree && $in_commit_log) {
3393 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3396 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3397 check_absolute_file($1, $herecurr)) {
3400 check_absolute_file($file, $herecurr);
3405 # Check for various typo / spelling mistakes
3406 if (defined($misspellings) &&
3407 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3408 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3410 my $blank = copy_spacing($rawline);
3411 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3412 my $hereptr = "$hereline$ptr\n";
3413 my $typo_fix = $spelling_fix{lc($typo)};
3414 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3415 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3416 my $msg_level = \&WARN;
3417 $msg_level = \&CHK if ($file);
3418 if (&{$msg_level}("TYPO_SPELLING",
3419 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3421 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3426 # check for invalid commit id
3427 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3430 ($id, $description) = git_commit_info($2, undef, undef);
3431 if (!defined($id)) {
3432 WARN("UNKNOWN_COMMIT_ID",
3433 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3437 # check for repeated words separated by a single space
3438 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3439 if (($rawline =~ /^\+/ || $in_commit_log) &&
3440 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3441 pos($rawline) = 1 if (!$in_commit_log);
3442 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3446 my $start_pos = $-[1];
3447 my $end_pos = $+[2];
3448 if ($first =~ /(?:struct|union|enum)/) {
3449 pos($rawline) += length($first) + length($second) + 1;
3453 next if (lc($first) ne lc($second));
3454 next if ($first eq 'long');
3456 # check for character before and after the word matches
3457 my $start_char = '';
3459 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3460 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3462 next if ($start_char =~ /^\S$/);
3463 next if (index(" \t.,;?!", $end_char) == -1);
3465 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3466 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3467 next if (!exists($allow_repeated_words{lc($first)}));
3470 if (WARN("REPEATED_WORD",
3471 "Possible repeated word: '$first'\n" . $herecurr) &&
3473 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3477 # if it's a repeated word on consecutive lines in a comment block
3478 if ($prevline =~ /$;+\s*$/ &&
3479 $prevrawline =~ /($word_pattern)\s*$/) {
3481 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3482 if (WARN("REPEATED_WORD",
3483 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3485 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3491 # ignore non-hunk lines and lines being removed
3492 next if (!$hunk_line || $line =~ /^-/);
3494 #trailing whitespace
3495 if ($line =~ /^\+.*\015/) {
3496 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3497 if (ERROR("DOS_LINE_ENDINGS",
3498 "DOS line endings\n" . $herevet) &&
3500 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3502 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3503 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3504 if (ERROR("TRAILING_WHITESPACE",
3505 "trailing whitespace\n" . $herevet) &&
3507 $fixed[$fixlinenr] =~ s/\s+$//;
3513 # Check for FSF mailing addresses.
3514 if ($rawline =~ /\bwrite to the Free/i ||
3515 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3516 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3517 $rawline =~ /\b51\s+Franklin\s+St/i) {
3518 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3519 my $msg_level = \&ERROR;
3520 $msg_level = \&CHK if ($file);
3521 &{$msg_level}("FSF_MAILING_ADDRESS",
3522 "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)
3525 # check for Kconfig help text having a real description
3526 # Only applies when adding the entry originally, after that we do not have
3527 # sufficient context to determine whether it is indeed long enough.
3528 if ($realfile =~ /Kconfig/ &&
3529 # 'choice' is usually the last thing on the line (though
3530 # Kconfig supports named choices), so use a word boundary
3531 # (\b) rather than a whitespace character (\s)
3532 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3536 my $help_length = 0;
3537 while (defined $lines[$ln]) {
3538 my $f = $lines[$ln++];
3540 next if ($f =~ /^-/);
3541 last if ($f !~ /^[\+ ]/); # !patch context
3543 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3547 if ($f =~ /^\+\s*help\s*$/) {
3552 $f =~ s/^.//; # strip patch context [+ ]
3553 $f =~ s/#.*//; # strip # directives
3554 $f =~ s/^\s+//; # strip leading blanks
3555 next if ($f =~ /^$/); # skip blank lines
3557 # At the end of this Kconfig block:
3558 # This only checks context lines in the patch
3559 # and so hopefully shouldn't trigger false
3560 # positives, even though some of these are
3561 # common words in help texts
3562 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3563 if|endif|menu|endmenu|source)\b/x) {
3566 $help_length++ if ($has_help);
3569 $help_length < $min_conf_desc_length) {
3570 my $stat_real = get_stat_real($linenr, $ln - 1);
3571 WARN("CONFIG_DESCRIPTION",
3572 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3576 # check MAINTAINERS entries
3577 if ($realfile =~ /^MAINTAINERS$/) {
3578 # check MAINTAINERS entries for the right form
3579 if ($rawline =~ /^\+[A-Z]:/ &&
3580 $rawline !~ /^\+[A-Z]:\t\S/) {
3581 if (WARN("MAINTAINERS_STYLE",
3582 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3584 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3587 # check MAINTAINERS entries for the right ordering too
3588 my $preferred_order = 'MRLSWQBCPTFXNK';
3589 if ($rawline =~ /^\+[A-Z]:/ &&
3590 $prevrawline =~ /^[\+ ][A-Z]:/) {
3591 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3594 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3597 my $curindex = index($preferred_order, $cur);
3598 my $previndex = index($preferred_order, $prev);
3599 if ($curindex < 0) {
3600 WARN("MAINTAINERS_STYLE",
3601 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3603 if ($previndex >= 0 && $curindex < $previndex) {
3604 WARN("MAINTAINERS_STYLE",
3605 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3606 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3607 ($prev eq 'X' && $cur eq 'X')) &&
3608 ($prevval cmp $curval) > 0) {
3609 WARN("MAINTAINERS_STYLE",
3610 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3616 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3617 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3620 'EXTRA_AFLAGS' => 'asflags-y',
3621 'EXTRA_CFLAGS' => 'ccflags-y',
3622 'EXTRA_CPPFLAGS' => 'cppflags-y',
3623 'EXTRA_LDFLAGS' => 'ldflags-y',
3626 WARN("DEPRECATED_VARIABLE",
3627 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3630 # check for DT compatible documentation
3631 if (defined $root &&
3632 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3633 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3635 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3637 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3638 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3640 foreach my $compat (@compats) {
3641 my $compat2 = $compat;
3642 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3643 my $compat3 = $compat;
3644 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3645 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3647 WARN("UNDOCUMENTED_DT_STRING",
3648 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3651 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3653 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3655 WARN("UNDOCUMENTED_DT_STRING",
3656 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3661 # check for using SPDX license tag at beginning of files
3662 if ($realline == $checklicenseline) {
3663 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3664 $checklicenseline = 2;
3665 } elsif ($rawline =~ /^\+/) {
3667 if ($realfile =~ /\.(h|s|S)$/) {
3669 } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3671 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3673 } elsif ($realfile =~ /\.rst$/) {
3677 # check SPDX comment style for .[chsS] files
3678 if ($realfile =~ /\.[chsS]$/ &&
3679 $rawline =~ /SPDX-License-Identifier:/ &&
3680 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3681 WARN("SPDX_LICENSE_TAG",
3682 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3685 if ($comment !~ /^$/ &&
3686 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3687 WARN("SPDX_LICENSE_TAG",
3688 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3689 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3690 my $spdx_license = $1;
3691 if (!is_SPDX_License_valid($spdx_license)) {
3692 WARN("SPDX_LICENSE_TAG",
3693 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3695 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3696 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3697 my $msg_level = \&WARN;
3698 $msg_level = \&CHK if ($file);
3699 if (&{$msg_level}("SPDX_LICENSE_TAG",
3701 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3703 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3710 # check for embedded filenames
3711 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3712 WARN("EMBEDDED_FILENAME",
3713 "It's generally not useful to have the filename in the file\n" . $herecurr);
3716 # check we are in a valid source file if not then ignore this hunk
3717 next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3719 # check for using SPDX-License-Identifier on the wrong line number
3720 if ($realline != $checklicenseline &&
3721 $rawline =~ /\bSPDX-License-Identifier:/ &&
3722 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3723 WARN("SPDX_LICENSE_TAG",
3724 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3727 # line length limit (with some exclusions)
3729 # There are a few types of lines that may extend beyond $max_line_length:
3730 # logging functions like pr_info that end in a string
3731 # lines with a single string
3732 # #defines that are a single string
3733 # lines with an RFC3986 like URL
3735 # There are 3 different line length message types:
3736 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3737 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3738 # LONG_LINE all other lines longer than $max_line_length
3740 # if LONG_LINE is ignored, the other 2 types are also ignored
3743 if ($line =~ /^\+/ && $length > $max_line_length) {
3744 my $msg_type = "LONG_LINE";
3746 # Check the allowed long line types first
3748 # logging functions that end in a string that starts
3749 # before $max_line_length
3750 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3751 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3754 # lines with only strings (w/ possible termination)
3755 # #defines with only strings
3756 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3757 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3760 # More special cases
3761 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3762 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3765 # URL ($rawline is used in case the URL is in a comment)
3766 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3769 # Otherwise set the alternate message types
3771 # a comment starts before $max_line_length
3772 } elsif ($line =~ /($;[\s$;]*)$/ &&
3773 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3774 $msg_type = "LONG_LINE_COMMENT"
3776 # a quoted string starts before $max_line_length
3777 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3778 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3779 $msg_type = "LONG_LINE_STRING"
3782 if ($msg_type ne "" &&
3783 (show_type("LONG_LINE") || show_type($msg_type))) {
3784 my $msg_level = \&WARN;
3785 $msg_level = \&CHK if ($file);
3786 &{$msg_level}($msg_type,
3787 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3791 # check for adding lines without a newline.
3792 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3793 if (WARN("MISSING_EOF_NEWLINE",
3794 "adding a line without newline at end of file\n" . $herecurr) &&
3796 fix_delete_line($fixlinenr+1, "No newline at end of file");
3800 # check for .L prefix local symbols in .S files
3801 if ($realfile =~ /\.S$/ &&
3802 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3803 WARN("AVOID_L_PREFIX",
3804 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr);
3807 # check we are in a valid source file C or perl if not then ignore this hunk
3808 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3810 # at the beginning of a line any tabs must come first and anything
3811 # more than $tabsize must use tabs.
3812 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3813 $rawline =~ /^\+\s* \s*/) {
3814 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3816 if (ERROR("CODE_INDENT",
3817 "code indent should use tabs where possible\n" . $herevet) &&
3819 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3823 # check for space before tabs.
3824 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3825 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3826 if (WARN("SPACE_BEFORE_TAB",
3827 "please, no space before tabs\n" . $herevet) &&
3829 while ($fixed[$fixlinenr] =~
3830 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3831 while ($fixed[$fixlinenr] =~
3832 s/(^\+.*) +\t/$1\t/) {}
3836 # check for assignments on the start of a line
3837 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3839 if (CHK("ASSIGNMENT_CONTINUATIONS",
3840 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3841 $fix && $prevrawline =~ /^\+/) {
3842 # add assignment operator to the previous line, remove from current line
3843 $fixed[$fixlinenr - 1] .= " $operator";
3844 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3848 # check for && or || at the start of a line
3849 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3851 if (CHK("LOGICAL_CONTINUATIONS",
3852 "Logical continuations should be on the previous line\n" . $hereprev) &&
3853 $fix && $prevrawline =~ /^\+/) {
3854 # insert logical operator at last non-comment, non-whitepsace char on previous line
3855 $prevline =~ /[\s$;]*$/;
3856 my $line_end = substr($prevrawline, $-[0]);
3857 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3858 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3862 # check indentation starts on a tab stop
3863 if ($perl_version_ok &&
3864 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3865 my $indent = length($1);
3866 if ($indent % $tabsize) {
3868 "Statements should start on a tabstop\n" . $herecurr) &&
3870 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3875 # check multi-line statement indentation matches previous line
3876 if ($perl_version_ok &&
3877 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3878 $prevline =~ /^\+(\t*)(.*)$/;
3882 my $pos = pos_last_openparen($rest);
3884 $line =~ /^(\+| )([ \t]*)/;
3887 my $goodtabindent = $oldindent .
3888 "\t" x ($pos / $tabsize) .
3889 " " x ($pos % $tabsize);
3890 my $goodspaceindent = $oldindent . " " x $pos;
3892 if ($newindent ne $goodtabindent &&
3893 $newindent ne $goodspaceindent) {
3895 if (CHK("PARENTHESIS_ALIGNMENT",
3896 "Alignment should match open parenthesis\n" . $hereprev) &&
3897 $fix && $line =~ /^\+/) {
3898 $fixed[$fixlinenr] =~
3899 s/^\+[ \t]*/\+$goodtabindent/;
3905 # check for space after cast like "(int) foo" or "(struct foo) bar"
3906 # avoid checking a few false positives:
3907 # "sizeof(<type>)" or "__alignof__(<type>)"
3908 # function pointer declarations like "(*foo)(int) = bar;"
3909 # structure definitions like "(struct foo) { 0 };"
3910 # multiline macros that define functions
3911 # known attributes or the __attribute__ keyword
3912 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3913 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3915 "No space is necessary after a cast\n" . $herecurr) &&
3917 $fixed[$fixlinenr] =~
3918 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3922 # Block comment styles
3923 # Networking with an initial /*
3924 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3925 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3926 $rawline =~ /^\+[ \t]*\*/ &&
3927 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3928 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3929 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3932 # Block comments use * on subsequent lines
3933 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3934 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3935 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3936 $rawline =~ /^\+/ && #line is new
3937 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3938 WARN("BLOCK_COMMENT_STYLE",
3939 "Block comments use * on subsequent lines\n" . $hereprev);
3942 # Block comments use */ on trailing lines
3943 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3944 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3945 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3946 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3947 WARN("BLOCK_COMMENT_STYLE",
3948 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3951 # Block comment * alignment
3952 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3953 $line =~ /^\+[ \t]*$;/ && #leading comment
3954 $rawline =~ /^\+[ \t]*\*/ && #leading *
3955 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3956 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3957 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3959 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3961 $oldindent = expand_tabs($1);
3963 $prevrawline =~ m@^\+(.*/?)\*@;
3964 $oldindent = expand_tabs($1);
3966 $rawline =~ m@^\+([ \t]*)\*@;
3968 $newindent = expand_tabs($newindent);
3969 if (length($oldindent) ne length($newindent)) {
3970 WARN("BLOCK_COMMENT_STYLE",
3971 "Block comments should align the * on each line\n" . $hereprev);
3975 # check for missing blank lines after struct/union declarations
3976 # with exceptions for various attributes and macros
3977 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3979 !($line =~ /^\+\s*$/ ||
3980 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
3981 $line =~ /^\+\s*MODULE_/i ||
3982 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3983 $line =~ /^\+[a-z_]*init/ ||
3984 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3985 $line =~ /^\+\s*DECLARE/ ||
3986 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3987 $line =~ /^\+\s*__setup/)) {
3988 if (CHK("LINE_SPACING",
3989 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3991 fix_insert_line($fixlinenr, "\+");
3995 # check for multiple consecutive blank lines
3996 if ($prevline =~ /^[\+ ]\s*$/ &&
3997 $line =~ /^\+\s*$/ &&
3998 $last_blank_line != ($linenr - 1)) {
3999 if (CHK("LINE_SPACING",
4000 "Please don't use multiple blank lines\n" . $hereprev) &&
4002 fix_delete_line($fixlinenr, $rawline);
4005 $last_blank_line = $linenr;
4008 # check for missing blank lines after declarations
4009 # (declarations must have the same indentation and not be at the start of line)
4010 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4014 # remove $Attribute/$Sparse uses to simplify comparisons
4015 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4016 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4017 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4018 # function pointer declarations
4019 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4020 # foo bar; where foo is some local typedef or #define
4021 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4022 # known declaration macros
4023 $pl =~ /^\+\s+$declaration_macros/) &&
4024 # for "else if" which can look like "$Ident $Ident"
4025 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4026 # other possible extensions of declaration lines
4027 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4028 # not starting a section or a macro "\" extended line
4029 $pl =~ /(?:\{\s*|\\)$/) &&
4030 # looks like a declaration
4031 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4032 # function pointer declarations
4033 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4034 # foo bar; where foo is some local typedef or #define
4035 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4036 # known declaration macros
4037 $sl =~ /^\+\s+$declaration_macros/ ||
4038 # start of struct or union or enum
4039 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4040 # start or end of block or continuation of declaration
4041 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4042 # bitfield continuation
4043 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4044 # other possible extensions of declaration lines
4045 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4046 if (WARN("LINE_SPACING",
4047 "Missing a blank line after declarations\n" . $hereprev) &&
4049 fix_insert_line($fixlinenr, "\+");
4054 # check for spaces at the beginning of a line.
4056 # 1) within comments
4057 # 2) indented preprocessor commands
4059 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4060 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4061 if (WARN("LEADING_SPACE",
4062 "please, no spaces at the start of a line\n" . $herevet) &&
4064 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4068 # check we are in a valid C source file if not then ignore this hunk
4069 next if ($realfile !~ /\.(h|c)$/);
4071 # check for unusual line ending [ or (
4072 if ($line =~ /^\+.*([\[\(])\s*$/) {
4073 CHK("OPEN_ENDED_LINE",
4074 "Lines should not end with a '$1'\n" . $herecurr);
4077 # check if this appears to be the start function declaration, save the name
4078 if ($sline =~ /^\+\{\s*$/ &&
4079 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4080 $context_function = $1;
4083 # check if this appears to be the end of function declaration
4084 if ($sline =~ /^\+\}\s*$/) {
4085 undef $context_function;
4088 # check indentation of any line with a bare else
4089 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4090 # if the previous line is a break or return and is indented 1 tab more...
4091 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4092 my $tabs = length($1) + 1;
4093 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4094 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4095 defined $lines[$linenr] &&
4096 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4097 WARN("UNNECESSARY_ELSE",
4098 "else is not generally useful after a break or return\n" . $hereprev);
4102 # check indentation of a line with a break;
4103 # if the previous line is a goto, return or break
4104 # and is indented the same # of tabs
4105 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4107 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4108 if (WARN("UNNECESSARY_BREAK",
4109 "break is not useful after a $1\n" . $hereprev) &&
4111 fix_delete_line($fixlinenr, $rawline);
4116 # check for RCS/CVS revision markers
4117 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4119 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4122 # check for old HOTPLUG __dev<foo> section markings
4123 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4124 WARN("HOTPLUG_SECTION",
4125 "Using $1 is unnecessary\n" . $herecurr);
4128 # Check for potential 'bare' types
4129 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4131 #print "LINE<$line>\n";
4132 if ($linenr > $suppress_statement &&
4133 $realcnt && $sline =~ /.\s*\S/) {
4134 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4135 ctx_statement_block($linenr, $realcnt, 0);
4136 $stat =~ s/\n./\n /g;
4137 $cond =~ s/\n./\n /g;
4139 #print "linenr<$linenr> <$stat>\n";
4140 # If this statement has no statement boundaries within
4141 # it there is no point in retrying a statement scan
4142 # until we hit end of it.
4143 my $frag = $stat; $frag =~ s/;+\s*$//;
4144 if ($frag !~ /(?:{|;)/) {
4145 #print "skip<$line_nr_next>\n";
4146 $suppress_statement = $line_nr_next;
4149 # Find the real next line.
4150 $realline_next = $line_nr_next;
4151 if (defined $realline_next &&
4152 (!defined $lines[$realline_next - 1] ||
4153 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4160 # Ignore goto labels.
4161 if ($s =~ /$Ident:\*$/s) {
4163 # Ignore functions being called
4164 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4166 } elsif ($s =~ /^.\s*else\b/s) {
4168 # declarations always start with types
4169 } 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) {
4172 possible($type, "A:" . $s);
4174 # definitions in global scope can only start with types
4175 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4176 possible($1, "B:" . $s);
4179 # any (foo ... *) is a pointer cast, and foo is a type
4180 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4181 possible($1, "C:" . $s);
4184 # Check for any sort of function declaration.
4185 # int foo(something bar, other baz);
4186 # void (*store_gdt)(x86_descr_ptr *);
4187 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4188 my ($name_len) = length($1);
4191 substr($ctx, 0, $name_len + 1, '');
4192 $ctx =~ s/\)[^\)]*$//;
4194 for my $arg (split(/\s*,\s*/, $ctx)) {
4195 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4197 possible($1, "D:" . $s);
4205 # Checks which may be anchored in the context.
4208 # Check for switch () and associated case and default
4209 # statements should be at the same indent.
4210 if ($line=~/\bswitch\s*\(.*\)/) {
4213 my @ctx = ctx_block_outer($linenr, $realcnt);
4215 for my $ctx (@ctx) {
4216 my ($clen, $cindent) = line_stats($ctx);
4217 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4218 $indent != $cindent) {
4219 $err .= "$sep$ctx\n";
4226 ERROR("SWITCH_CASE_INDENT_LEVEL",
4227 "switch and case should be at the same indent\n$hereline$err");
4231 # if/while/etc brace do not go on next line, unless defining a do while loop,
4232 # or if that brace on the next line is for something else
4233 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4234 my $pre_ctx = "$1$2";
4236 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4238 if ($line =~ /^\+\t{6,}/) {
4239 WARN("DEEP_INDENTATION",
4240 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4243 my $ctx_cnt = $realcnt - $#ctx - 1;
4244 my $ctx = join("\n", @ctx);
4246 my $ctx_ln = $linenr;
4247 my $ctx_skip = $realcnt;
4249 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4250 defined $lines[$ctx_ln - 1] &&
4251 $lines[$ctx_ln - 1] =~ /^-/)) {
4252 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4253 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4257 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4258 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4260 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4262 "that open brace { should be on the previous line\n" .
4263 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4265 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4266 $ctx =~ /\)\s*\;\s*$/ &&
4267 defined $lines[$ctx_ln - 1])
4269 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4270 if ($nindent > $indent) {
4271 WARN("TRAILING_SEMICOLON",
4272 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4273 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4278 # Check relative indent for conditionals and blocks.
4279 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4280 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4281 ctx_statement_block($linenr, $realcnt, 0)
4282 if (!defined $stat);
4283 my ($s, $c) = ($stat, $cond);
4285 substr($s, 0, length($c), '');
4287 # remove inline comments
4291 # Find out how long the conditional actually is.
4292 my @newlines = ($c =~ /\n/gs);
4293 my $cond_lines = 1 + $#newlines;
4295 # Make sure we remove the line prefixes as we have
4296 # none on the first line, and are going to readd them
4299 while ($s =~ /\n\s+\\\n/) {
4300 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4303 # We want to check the first line inside the block
4304 # starting at the end of the conditional, so remove:
4305 # 1) any blank line termination
4306 # 2) any opening brace { on end of the line
4308 my $continuation = 0;
4310 $s =~ s/^.*\bdo\b//;
4312 if ($s =~ s/^\s*\\//) {
4315 if ($s =~ s/^\s*?\n//) {
4320 # Also ignore a loop construct at the end of a
4321 # preprocessor statement.
4322 if (($prevline =~ /^.\s*#\s*define\s/ ||
4323 $prevline =~ /\\\s*$/) && $continuation == 0) {
4329 while ($cond_ptr != $cond_lines) {
4330 $cond_ptr = $cond_lines;
4332 # If we see an #else/#elif then the code
4334 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4339 # 1) blank lines, they should be at 0,
4340 # 2) preprocessor lines, and
4342 if ($continuation ||
4344 $s =~ /^\s*#\s*?/ ||
4345 $s =~ /^\s*$Ident\s*:/) {
4346 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4347 if ($s =~ s/^.*?\n//) {
4353 my (undef, $sindent) = line_stats("+" . $s);
4354 my $stat_real = raw_line($linenr, $cond_lines);
4356 # Check if either of these lines are modified, else
4357 # this is not this patch's fault.
4358 if (!defined($stat_real) ||
4359 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4362 if (defined($stat_real) && $cond_lines > 1) {
4363 $stat_real = "[...]\n$stat_real";
4366 #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";
4368 if ($check && $s ne '' &&
4369 (($sindent % $tabsize) != 0 ||
4370 ($sindent < $indent) ||
4371 ($sindent == $indent &&
4372 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4373 ($sindent > $indent + $tabsize))) {
4374 WARN("SUSPECT_CODE_INDENT",
4375 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4379 # Track the 'values' across context and added lines.
4380 my $opline = $line; $opline =~ s/^./ /;
4381 my ($curr_values, $curr_vars) =
4382 annotate_values($opline . "\n", $prev_values);
4383 $curr_values = $prev_values . $curr_values;
4385 my $outline = $opline; $outline =~ s/\t/ /g;
4386 print "$linenr > .$outline\n";
4387 print "$linenr > $curr_values\n";
4388 print "$linenr > $curr_vars\n";
4390 $prev_values = substr($curr_values, -1);
4392 #ignore lines not being added
4393 next if ($line =~ /^[^\+]/);
4395 # check for self assignments used to avoid compiler warnings
4396 # e.g.: int foo = foo, *bar = NULL;
4397 # struct foo bar = *(&(bar));
4398 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4400 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4401 WARN("SELF_ASSIGNMENT",
4402 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4406 # check for dereferences that span multiple lines
4407 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4408 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4409 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4411 $line =~ /^.\s*($Lval)/;
4414 WARN("MULTILINE_DEREFERENCE",
4415 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4418 # check for declarations of signed or unsigned without int
4419 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4422 $var = "" if (!defined $var);
4423 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4427 $pointer = "" if (!defined $pointer);
4429 if (WARN("UNSPECIFIED_INT",
4430 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4432 my $decl = trim($sign) . " int ";
4433 my $comp_pointer = $pointer;
4434 $comp_pointer =~ s/\s//g;
4435 $decl .= $comp_pointer;
4436 $decl = rtrim($decl) if ($var eq "");
4437 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4442 # TEST: allow direct testing of the type matcher.
4444 if ($line =~ /^.\s*$Declare\s*$/) {
4446 "TEST: is type\n" . $herecurr);
4447 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4448 ERROR("TEST_NOT_TYPE",
4449 "TEST: is not type ($1 is)\n". $herecurr);
4453 # TEST: allow direct testing of the attribute matcher.
4455 if ($line =~ /^.\s*$Modifier\s*$/) {
4457 "TEST: is attr\n" . $herecurr);
4458 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4459 ERROR("TEST_NOT_ATTR",
4460 "TEST: is not attr ($1 is)\n". $herecurr);
4465 # check for initialisation to aggregates open brace on the next line
4466 if ($line =~ /^.\s*{/ &&
4467 $prevline =~ /(?:^|[^=])=\s*$/) {
4468 if (ERROR("OPEN_BRACE",
4469 "that open brace { should be on the previous line\n" . $hereprev) &&
4470 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4471 fix_delete_line($fixlinenr - 1, $prevrawline);
4472 fix_delete_line($fixlinenr, $rawline);
4473 my $fixedline = $prevrawline;
4474 $fixedline =~ s/\s*=\s*$/ = {/;
4475 fix_insert_line($fixlinenr, $fixedline);
4477 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4478 fix_insert_line($fixlinenr, $fixedline);
4483 # Checks which are anchored on the added line.
4486 # check for malformed paths in #include statements (uses RAW line)
4487 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4489 if ($path =~ m{//}) {
4490 ERROR("MALFORMED_INCLUDE",
4491 "malformed #include filename\n" . $herecurr);
4493 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4494 ERROR("UAPI_INCLUDE",
4495 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4499 # no C99 // comments
4500 if ($line =~ m{//}) {
4501 if (ERROR("C99_COMMENTS",
4502 "do not use C99 // comments\n" . $herecurr) &&
4504 my $line = $fixed[$fixlinenr];
4505 if ($line =~ /\/\/(.*)$/) {
4506 my $comment = trim($1);
4507 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4511 # Remove C99 comments.
4513 $opline =~ s@//.*@@;
4515 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4516 # the whole statement.
4517 #print "APW <$lines[$realline_next - 1]>\n";
4518 if (defined $realline_next &&
4519 exists $lines[$realline_next - 1] &&
4520 !defined $suppress_export{$realline_next} &&
4521 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4522 # Handle definitions which produce identifiers with
4525 # EXPORT_SYMBOL(something_foo);
4527 $name =~ s/^\s*($Ident).*/$1/;
4528 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4529 $name =~ /^${Ident}_$2/) {
4530 #print "FOO C name<$name>\n";
4531 $suppress_export{$realline_next} = 1;
4533 } elsif ($stat !~ /(?:
4535 ^.DEFINE_$Ident\(\Q$name\E\)|
4536 ^.DECLARE_$Ident\(\Q$name\E\)|
4537 ^.LIST_HEAD\(\Q$name\E\)|
4538 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4539 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4541 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4542 $suppress_export{$realline_next} = 2;
4544 $suppress_export{$realline_next} = 1;
4547 if (!defined $suppress_export{$linenr} &&
4548 $prevline =~ /^.\s*$/ &&
4549 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4550 #print "FOO B <$lines[$linenr - 1]>\n";
4551 $suppress_export{$linenr} = 2;
4553 if (defined $suppress_export{$linenr} &&
4554 $suppress_export{$linenr} == 2) {
4555 WARN("EXPORT_SYMBOL",
4556 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4559 # check for global initialisers.
4560 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4561 !exclude_global_initialisers($realfile)) {
4562 if (ERROR("GLOBAL_INITIALISERS",
4563 "do not initialise globals to $1\n" . $herecurr) &&
4565 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4568 # check for static initialisers.
4569 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4570 if (ERROR("INITIALISED_STATIC",
4571 "do not initialise statics to $1\n" .
4574 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4578 # check for misordered declarations of char/short/int/long with signed/unsigned
4579 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4581 WARN("MISORDERED_TYPE",
4582 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4585 # check for unnecessary <signed> int declarations of short/long/long long
4586 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4587 my $type = trim($1);
4588 next if ($type !~ /\bint\b/);
4589 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4590 my $new_type = $type;
4591 $new_type =~ s/\b\s*int\s*\b/ /;
4592 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4593 $new_type =~ s/^const\s+//;
4594 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4595 $new_type = "const $new_type" if ($type =~ /^const\b/);
4596 $new_type =~ s/\s+/ /g;
4597 $new_type = trim($new_type);
4598 if (WARN("UNNECESSARY_INT",
4599 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4601 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4605 # check for static const char * arrays.
4606 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4607 WARN("STATIC_CONST_CHAR_ARRAY",
4608 "static const char * array should probably be static const char * const\n" .
4612 # check for initialized const char arrays that should be static const
4613 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4614 if (WARN("STATIC_CONST_CHAR_ARRAY",
4615 "const array should probably be static const\n" . $herecurr) &&
4617 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4621 # check for static char foo[] = "bar" declarations.
4622 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4623 WARN("STATIC_CONST_CHAR_ARRAY",
4624 "static char array declaration should probably be static const char\n" .
4628 # check for const <foo> const where <foo> is not a pointer or array type
4629 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4631 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4633 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4634 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4636 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4640 # check for const static or static <non ptr type> const declarations
4641 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4642 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4643 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4644 if (WARN("STATIC_CONST",
4645 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4647 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4648 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4652 # check for non-global char *foo[] = {"bar", ...} declarations.
4653 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4654 WARN("STATIC_CONST_CHAR_ARRAY",
4655 "char * array declaration might be better as static const\n" .
4659 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4660 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4662 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4664 if (WARN("ARRAY_SIZE",
4665 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4667 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4672 # check for function declarations without arguments like "int foo()"
4673 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4674 if (ERROR("FUNCTION_WITHOUT_ARGS",
4675 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4677 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4681 # check for new typedefs, only function parameters and sparse annotations
4683 if ($line =~ /\btypedef\s/ &&
4684 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4685 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4686 $line !~ /\b$typeTypedefs\b/ &&
4687 $line !~ /\b__bitwise\b/) {
4688 WARN("NEW_TYPEDEFS",
4689 "do not add new typedefs\n" . $herecurr);
4692 # * goes on variable not on type
4694 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4696 my ($ident, $from, $to) = ($1, $2, $2);
4698 # Should start with a space.
4699 $to =~ s/^(\S)/ $1/;
4700 # Should not end with a space.
4702 # '*'s should not have spaces between.
4703 while ($to =~ s/\*\s+\*/\*\*/) {
4706 ## print "1: from<$from> to<$to> ident<$ident>\n";
4708 if (ERROR("POINTER_LOCATION",
4709 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4711 my $sub_from = $ident;
4712 my $sub_to = $ident;
4713 $sub_to =~ s/\Q$from\E/$to/;
4714 $fixed[$fixlinenr] =~
4715 s@\Q$sub_from\E@$sub_to@;
4719 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4721 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4723 # Should start with a space.
4724 $to =~ s/^(\S)/ $1/;
4725 # Should not end with a space.
4727 # '*'s should not have spaces between.
4728 while ($to =~ s/\*\s+\*/\*\*/) {
4730 # Modifiers should have spaces.
4731 $to =~ s/(\b$Modifier$)/$1 /;
4733 ## print "2: from<$from> to<$to> ident<$ident>\n";
4734 if ($from ne $to && $ident !~ /^$Modifier$/) {
4735 if (ERROR("POINTER_LOCATION",
4736 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4739 my $sub_from = $match;
4740 my $sub_to = $match;
4741 $sub_to =~ s/\Q$from\E/$to/;
4742 $fixed[$fixlinenr] =~
4743 s@\Q$sub_from\E@$sub_to@;
4748 # do not use BUG() or variants
4749 if ($line =~ /\b(?!AA_|BUILD_|DCCP_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4750 my $msg_level = \&WARN;
4751 $msg_level = \&CHK if ($file);
4752 &{$msg_level}("AVOID_BUG",
4753 "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr);
4756 # avoid LINUX_VERSION_CODE
4757 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4758 WARN("LINUX_VERSION_CODE",
4759 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4762 # check for uses of printk_ratelimit
4763 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4764 WARN("PRINTK_RATELIMITED",
4765 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4768 # printk should use KERN_* levels
4769 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4770 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4771 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4774 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4775 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4779 $modifier = "" if (!defined($modifier));
4780 my $level = lc($orig);
4781 $level = "warn" if ($level eq "warning");
4782 my $level2 = $level;
4783 $level2 = "dbg" if ($level eq "debug");
4784 $level .= $modifier;
4785 $level2 .= $modifier;
4786 WARN("PREFER_PR_LEVEL",
4787 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4790 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4791 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4793 my $level = lc($orig);
4794 $level = "warn" if ($level eq "warning");
4795 $level = "dbg" if ($level eq "debug");
4796 WARN("PREFER_DEV_LEVEL",
4797 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4800 # trace_printk should not be used in production code.
4801 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4802 WARN("TRACE_PRINTK",
4803 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4806 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4807 # number of false positives, but assembly files are not checked, so at
4808 # least the arch entry code will not trigger this warning.
4809 if ($line =~ /\bENOSYS\b/) {
4811 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4814 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4815 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4816 # Similarly to ENOSYS warning a small number of false positives is expected.
4817 if (!$file && $line =~ /\bENOTSUPP\b/) {
4818 if (WARN("ENOTSUPP",
4819 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4821 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4825 # function brace can't be on same line, except for #defines of do while,
4826 # or if closed on same line
4827 if ($perl_version_ok &&
4828 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4829 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4831 if (ERROR("OPEN_BRACE",
4832 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4834 fix_delete_line($fixlinenr, $rawline);
4835 my $fixed_line = $rawline;
4836 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4839 fix_insert_line($fixlinenr, ltrim($line1));
4840 fix_insert_line($fixlinenr, "\+{");
4841 if ($line2 !~ /^\s*$/) {
4842 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4847 # open braces for enum, union and struct go on the same line.
4848 if ($line =~ /^.\s*{/ &&
4849 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4850 if (ERROR("OPEN_BRACE",
4851 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4852 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4853 fix_delete_line($fixlinenr - 1, $prevrawline);
4854 fix_delete_line($fixlinenr, $rawline);
4855 my $fixedline = rtrim($prevrawline) . " {";
4856 fix_insert_line($fixlinenr, $fixedline);
4857 $fixedline = $rawline;
4858 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4859 if ($fixedline !~ /^\+\s*$/) {
4860 fix_insert_line($fixlinenr, $fixedline);
4865 # missing space after union, struct or enum definition
4866 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4868 "missing space after $1 definition\n" . $herecurr) &&
4870 $fixed[$fixlinenr] =~
4871 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4875 # Function pointer declarations
4876 # check spacing between type, funcptr, and args
4877 # canonical declaration is "type (*funcptr)(args...)"
4878 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4880 my $pre_pointer_space = $2;
4881 my $post_pointer_space = $3;
4883 my $post_funcname_space = $5;
4884 my $pre_args_space = $6;
4886 # the $Declare variable will capture all spaces after the type
4887 # so check it for a missing trailing missing space but pointer return types
4888 # don't need a space so don't warn for those.
4889 my $post_declare_space = "";
4890 if ($declare =~ /(\s+)$/) {
4891 $post_declare_space = $1;
4892 $declare = rtrim($declare);
4894 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4896 "missing space after return type\n" . $herecurr);
4897 $post_declare_space = " ";
4900 # unnecessary space "type (*funcptr)(args...)"
4901 # This test is not currently implemented because these declarations are
4903 # int foo(int bar, ...)
4904 # and this is form shouldn't/doesn't generate a checkpatch warning.
4906 # elsif ($declare =~ /\s{2,}$/) {
4908 # "Multiple spaces after return type\n" . $herecurr);
4911 # unnecessary space "type ( *funcptr)(args...)"
4912 if (defined $pre_pointer_space &&
4913 $pre_pointer_space =~ /^\s/) {
4915 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4918 # unnecessary space "type (* funcptr)(args...)"
4919 if (defined $post_pointer_space &&
4920 $post_pointer_space =~ /^\s/) {
4922 "Unnecessary space before function pointer name\n" . $herecurr);
4925 # unnecessary space "type (*funcptr )(args...)"
4926 if (defined $post_funcname_space &&
4927 $post_funcname_space =~ /^\s/) {
4929 "Unnecessary space after function pointer name\n" . $herecurr);
4932 # unnecessary space "type (*funcptr) (args...)"
4933 if (defined $pre_args_space &&
4934 $pre_args_space =~ /^\s/) {
4936 "Unnecessary space before function pointer arguments\n" . $herecurr);
4939 if (show_type("SPACING") && $fix) {
4940 $fixed[$fixlinenr] =~
4941 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4945 # check for spacing round square brackets; allowed:
4946 # 1. with a type on the left -- int [] a;
4947 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4948 # 3. inside a curly brace -- = { [0...10] = 5 }
4949 while ($line =~ /(.*?\s)\[/g) {
4950 my ($where, $prefix) = ($-[1], $1);
4951 if ($prefix !~ /$Type\s+$/ &&
4952 ($where != 0 || $prefix !~ /^.\s+$/) &&
4953 $prefix !~ /[{,:]\s+$/) {
4954 if (ERROR("BRACKET_SPACE",
4955 "space prohibited before open square bracket '['\n" . $herecurr) &&
4957 $fixed[$fixlinenr] =~
4958 s/^(\+.*?)\s+\[/$1\[/;
4963 # check for spaces between functions and their parentheses.
4964 while ($line =~ /($Ident)\s+\(/g) {
4966 my $ctx_before = substr($line, 0, $-[1]);
4967 my $ctx = "$ctx_before$name";
4969 # Ignore those directives where spaces _are_ permitted.
4971 if|for|while|switch|return|case|
4972 volatile|__volatile__|
4973 __attribute__|format|__extension__|
4976 # cpp #define statements have non-optional spaces, ie
4977 # if there is a space between the name and the open
4978 # parenthesis it is simply not a parameter group.
4979 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4981 # cpp #elif statement condition may start with a (
4982 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4984 # If this whole things ends with a type its most
4985 # likely a typedef for a function.
4986 } elsif ($ctx =~ /$Type$/) {
4990 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4992 $fixed[$fixlinenr] =~
4993 s/\b$name\s+\(/$name\(/;
4998 # Check operator spacing.
4999 if (!($line=~/\#\s*include/)) {
5000 my $fixed_line = "";
5004 <<=|>>=|<=|>=|==|!=|
5005 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5006 =>|->|<<|>>|<|>|=|!|~|
5007 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5010 my @elements = split(/($ops|;)/, $opline);
5012 ## print("element count: <" . $#elements . ">\n");
5013 ## foreach my $el (@elements) {
5014 ## print("el: <$el>\n");
5017 my @fix_elements = ();
5020 foreach my $el (@elements) {
5021 push(@fix_elements, substr($rawline, $off, length($el)));
5022 $off += length($el);
5027 my $blank = copy_spacing($opline);
5028 my $last_after = -1;
5030 for (my $n = 0; $n < $#elements; $n += 2) {
5032 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5034 ## print("n: <$n> good: <$good>\n");
5036 $off += length($elements[$n]);
5038 # Pick up the preceding and succeeding characters.
5039 my $ca = substr($opline, 0, $off);
5041 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5042 $cc = substr($opline, $off + length($elements[$n + 1]));
5044 my $cb = "$ca$;$cc";
5047 $a = 'V' if ($elements[$n] ne '');
5048 $a = 'W' if ($elements[$n] =~ /\s$/);
5049 $a = 'C' if ($elements[$n] =~ /$;$/);
5050 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5051 $a = 'O' if ($elements[$n] eq '');
5052 $a = 'E' if ($ca =~ /^\s*$/);
5054 my $op = $elements[$n + 1];
5057 if (defined $elements[$n + 2]) {
5058 $c = 'V' if ($elements[$n + 2] ne '');
5059 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5060 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5061 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5062 $c = 'O' if ($elements[$n + 2] eq '');
5063 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5068 my $ctx = "${a}x${c}";
5070 my $at = "(ctx:$ctx)";
5072 my $ptr = substr($blank, 0, $off) . "^";
5073 my $hereptr = "$hereline$ptr\n";
5075 # Pull out the value of this operator.
5076 my $op_type = substr($curr_values, $off + 1, 1);
5078 # Get the full operator variant.
5079 my $opv = $op . substr($curr_vars, $off, 1);
5081 # Ignore operators passed as parameters.
5082 if ($op_type ne 'V' &&
5083 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5086 # } elsif ($op =~ /^$;+$/) {
5088 # ; should have either the end of line or a space or \ after it
5089 } elsif ($op eq ';') {
5090 if ($ctx !~ /.x[WEBC]/ &&
5091 $cc !~ /^\\/ && $cc !~ /^;/) {
5092 if (ERROR("SPACING",
5093 "space required after that '$op' $at\n" . $hereptr)) {
5094 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5100 } elsif ($op eq '//') {
5102 # : when part of a bitfield
5103 } elsif ($opv eq ':B') {
5104 # skip the bitfield test for now
5108 } elsif ($op eq '->') {
5109 if ($ctx =~ /Wx.|.xW/) {
5110 if (ERROR("SPACING",
5111 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5112 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5113 if (defined $fix_elements[$n + 2]) {
5114 $fix_elements[$n + 2] =~ s/^\s+//;
5120 # , must not have a space before and must have a space on the right.
5121 } elsif ($op eq ',') {
5122 my $rtrim_before = 0;
5123 my $space_after = 0;
5124 if ($ctx =~ /Wx./) {
5125 if (ERROR("SPACING",
5126 "space prohibited before that '$op' $at\n" . $hereptr)) {
5131 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5132 if (ERROR("SPACING",
5133 "space required after that '$op' $at\n" . $hereptr)) {
5139 if ($rtrim_before || $space_after) {
5140 if ($rtrim_before) {
5141 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5143 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5150 # '*' as part of a type definition -- reported already.
5151 } elsif ($opv eq '*_') {
5152 #warn "'*' is part of type\n";
5154 # unary operators should have a space before and
5155 # none after. May be left adjacent to another
5156 # unary operator, or a cast
5157 } elsif ($op eq '!' || $op eq '~' ||
5158 $opv eq '*U' || $opv eq '-U' ||
5159 $opv eq '&U' || $opv eq '&&U') {
5160 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5161 if (ERROR("SPACING",
5162 "space required before that '$op' $at\n" . $hereptr)) {
5163 if ($n != $last_after + 2) {
5164 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5169 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5170 # A unary '*' may be const
5172 } elsif ($ctx =~ /.xW/) {
5173 if (ERROR("SPACING",
5174 "space prohibited after that '$op' $at\n" . $hereptr)) {
5175 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5176 if (defined $fix_elements[$n + 2]) {
5177 $fix_elements[$n + 2] =~ s/^\s+//;
5183 # unary ++ and unary -- are allowed no space on one side.
5184 } elsif ($op eq '++' or $op eq '--') {
5185 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5186 if (ERROR("SPACING",
5187 "space required one side of that '$op' $at\n" . $hereptr)) {
5188 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5192 if ($ctx =~ /Wx[BE]/ ||
5193 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5194 if (ERROR("SPACING",
5195 "space prohibited before that '$op' $at\n" . $hereptr)) {
5196 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5200 if ($ctx =~ /ExW/) {
5201 if (ERROR("SPACING",
5202 "space prohibited after that '$op' $at\n" . $hereptr)) {
5203 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5204 if (defined $fix_elements[$n + 2]) {
5205 $fix_elements[$n + 2] =~ s/^\s+//;
5211 # << and >> may either have or not have spaces both sides
5212 } elsif ($op eq '<<' or $op eq '>>' or
5213 $op eq '&' or $op eq '^' or $op eq '|' or
5214 $op eq '+' or $op eq '-' or
5215 $op eq '*' or $op eq '/' or
5219 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5221 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5222 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5223 $fix_elements[$n + 2] =~ s/^\s+//;
5226 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5228 "space preferred before that '$op' $at\n" . $hereptr)) {
5229 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5233 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5234 if (ERROR("SPACING",
5235 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5236 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5237 if (defined $fix_elements[$n + 2]) {
5238 $fix_elements[$n + 2] =~ s/^\s+//;
5244 # A colon needs no spaces before when it is
5245 # terminating a case value or a label.
5246 } elsif ($opv eq ':C' || $opv eq ':L') {
5247 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5248 if (ERROR("SPACING",
5249 "space prohibited before that '$op' $at\n" . $hereptr)) {
5250 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5255 # All the others need spaces both sides.
5256 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5259 # Ignore email addresses <foo@bar>
5261 $cc =~ /^\S+\@\S+>/) ||
5263 $ca =~ /<\S+\@\S+$/))
5268 # for asm volatile statements
5269 # ignore a colon with another
5270 # colon immediately before or after
5272 ($ca =~ /:$/ || $cc =~ /^:/)) {
5276 # messages are ERROR, but ?: are CHK
5278 my $msg_level = \&ERROR;
5279 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5281 if (&{$msg_level}("SPACING",
5282 "spaces required around that '$op' $at\n" . $hereptr)) {
5283 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5284 if (defined $fix_elements[$n + 2]) {
5285 $fix_elements[$n + 2] =~ s/^\s+//;
5291 $off += length($elements[$n + 1]);
5293 ## print("n: <$n> GOOD: <$good>\n");
5295 $fixed_line = $fixed_line . $good;
5298 if (($#elements % 2) == 0) {
5299 $fixed_line = $fixed_line . $fix_elements[$#elements];
5302 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5303 $fixed[$fixlinenr] = $fixed_line;
5309 # check for whitespace before a non-naked semicolon
5310 if ($line =~ /^\+.*\S\s+;\s*$/) {
5312 "space prohibited before semicolon\n" . $herecurr) &&
5314 1 while $fixed[$fixlinenr] =~
5315 s/^(\+.*\S)\s+;/$1;/;
5319 # check for multiple assignments
5320 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5321 CHK("MULTIPLE_ASSIGNMENTS",
5322 "multiple assignments should be avoided\n" . $herecurr);
5325 ## # check for multiple declarations, allowing for a function declaration
5327 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5328 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5330 ## # Remove any bracketed sections to ensure we do not
5331 ## # falsely report the parameters of functions.
5333 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5335 ## if ($ln =~ /,/) {
5336 ## WARN("MULTIPLE_DECLARATION",
5337 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5341 #need space before brace following if, while, etc
5342 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5343 $line =~ /\b(?:else|do)\{/) {
5344 if (ERROR("SPACING",
5345 "space required before the open brace '{'\n" . $herecurr) &&
5347 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5351 ## # check for blank lines before declarations
5352 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5353 ## $prevrawline =~ /^.\s*$/) {
5355 ## "No blank lines before declarations\n" . $hereprev);
5359 # closing brace should have a space following it when it has anything
5361 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5362 if (ERROR("SPACING",
5363 "space required after that close brace '}'\n" . $herecurr) &&
5365 $fixed[$fixlinenr] =~
5366 s/}((?!(?:,|;|\)))\S)/} $1/;
5370 # check spacing on square brackets
5371 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5372 if (ERROR("SPACING",
5373 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5375 $fixed[$fixlinenr] =~
5379 if ($line =~ /\s\]/) {
5380 if (ERROR("SPACING",
5381 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5383 $fixed[$fixlinenr] =~
5388 # check spacing on parentheses
5389 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5390 $line !~ /for\s*\(\s+;/) {
5391 if (ERROR("SPACING",
5392 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5394 $fixed[$fixlinenr] =~
5398 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5399 $line !~ /for\s*\(.*;\s+\)/ &&
5400 $line !~ /:\s+\)/) {
5401 if (ERROR("SPACING",
5402 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5404 $fixed[$fixlinenr] =~
5409 # check unnecessary parentheses around addressof/dereference single $Lvals
5410 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5412 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5414 if (CHK("UNNECESSARY_PARENTHESES",
5415 "Unnecessary parentheses around $var\n" . $herecurr) &&
5417 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5421 # check for unnecessary parentheses around function pointer uses
5422 # ie: (foo->bar)(); should be foo->bar();
5423 # but not "if (foo->bar) (" to avoid some false positives
5424 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5426 if (CHK("UNNECESSARY_PARENTHESES",
5427 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5429 my $var2 = deparenthesize($var);
5431 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5435 # check for unnecessary parentheses around comparisons in if uses
5436 # when !drivers/staging or command-line uses --strict
5437 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5438 $perl_version_ok && defined($stat) &&
5439 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5441 my $test = substr($2, 1, -1);
5443 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5445 # avoid parentheses around potential macro args
5446 next if ($match =~ /^\s*\w+\s*$/);
5447 if (!defined($herectx)) {
5448 $herectx = $here . "\n";
5449 my $cnt = statement_rawlines($if_stat);
5450 for (my $n = 0; $n < $cnt; $n++) {
5451 my $rl = raw_line($linenr, $n);
5452 $herectx .= $rl . "\n";
5453 last if $rl =~ /^[ \+].*\{/;
5456 CHK("UNNECESSARY_PARENTHESES",
5457 "Unnecessary parentheses around '$match'\n" . $herectx);
5461 # check that goto labels aren't indented (allow a single space indentation)
5462 # and ignore bitfield definitions like foo:1
5463 # Strictly, labels can have whitespace after the identifier and before the :
5464 # but this is not allowed here as many ?: uses would appear to be labels
5465 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5466 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5467 $sline !~ /^.\s+default:/) {
5468 if (WARN("INDENTED_LABEL",
5469 "labels should not be indented\n" . $herecurr) &&
5471 $fixed[$fixlinenr] =~
5476 # check if a statement with a comma should be two statements like:
5477 # foo = bar(), /* comma should be semicolon */
5479 if (defined($stat) &&
5480 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5481 my $cnt = statement_rawlines($stat);
5482 my $herectx = get_stat_here($linenr, $cnt, $here);
5483 WARN("SUSPECT_COMMA_SEMICOLON",
5484 "Possible comma where semicolon could be used\n" . $herectx);
5487 # return is not a function
5488 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5490 if ($perl_version_ok &&
5491 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5493 $value = deparenthesize($value);
5494 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5495 ERROR("RETURN_PARENTHESES",
5496 "return is not a function, parentheses are not required\n" . $herecurr);
5498 } elsif ($spacing !~ /\s+/) {
5500 "space required before the open parenthesis '('\n" . $herecurr);
5504 # unnecessary return in a void function
5505 # at end-of-function, with the previous line a single leading tab, then return;
5506 # and the line before that not a goto label target like "out:"
5507 if ($sline =~ /^[ \+]}\s*$/ &&
5508 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5510 $lines[$linenr - 3] =~ /^[ +]/ &&
5511 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5513 "void function return statements are not generally useful\n" . $hereprev);
5516 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5517 if ($perl_version_ok &&
5518 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5519 my $openparens = $1;
5520 my $count = $openparens =~ tr@\(@\(@;
5522 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5523 my $comp = $4; #Not $1 because of $LvalOrFunc
5524 $msg = " - maybe == should be = ?" if ($comp eq "==");
5525 WARN("UNNECESSARY_PARENTHESES",
5526 "Unnecessary parentheses$msg\n" . $herecurr);
5530 # comparisons with a constant or upper case identifier on the left
5531 # avoid cases like "foo + BAR < baz"
5532 # only fix matches surrounded by parentheses to avoid incorrect
5533 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5534 if ($perl_version_ok &&
5535 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5540 my $newcomp = $comp;
5541 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5542 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5543 WARN("CONSTANT_COMPARISON",
5544 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5548 } elsif ($comp eq "<=") {
5550 } elsif ($comp eq ">") {
5552 } elsif ($comp eq ">=") {
5555 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5559 # Return of what appears to be an errno should normally be negative
5560 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5562 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5563 WARN("USE_NEGATIVE_ERRNO",
5564 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5568 # Need a space before open parenthesis after if, while etc
5569 if ($line =~ /\b(if|while|for|switch)\(/) {
5570 if (ERROR("SPACING",
5571 "space required before the open parenthesis '('\n" . $herecurr) &&
5573 $fixed[$fixlinenr] =~
5574 s/\b(if|while|for|switch)\(/$1 \(/;
5578 # Check for illegal assignment in if conditional -- and check for trailing
5579 # statements after the conditional.
5580 if ($line =~ /do\s*(?!{)/) {
5581 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5582 ctx_statement_block($linenr, $realcnt, 0)
5583 if (!defined $stat);
5584 my ($stat_next) = ctx_statement_block($line_nr_next,
5585 $remain_next, $off_next);
5586 $stat_next =~ s/\n./\n /g;
5587 ##print "stat<$stat> stat_next<$stat_next>\n";
5589 if ($stat_next =~ /^\s*while\b/) {
5590 # If the statement carries leading newlines,
5591 # then count those as offsets.
5593 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5595 statement_rawlines($whitespace) - 1;
5597 $suppress_whiletrailers{$line_nr_next +
5601 if (!defined $suppress_whiletrailers{$linenr} &&
5602 defined($stat) && defined($cond) &&
5603 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5604 my ($s, $c) = ($stat, $cond);
5605 my $fixed_assign_in_if = 0;
5607 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5608 if (ERROR("ASSIGN_IN_IF",
5609 "do not use assignment in if condition\n" . $herecurr) &&
5610 $fix && $perl_version_ok) {
5611 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5619 fix_delete_line($fixlinenr, $rawline);
5620 fix_insert_line($fixlinenr, "$space$statement;");
5621 my $newline = "${space}if (";
5622 $newline .= '!' if defined($not);
5623 $newline .= '(' if (defined $not && defined($test) && defined($against));
5624 $newline .= "$assigned";
5625 $newline .= " $test $against" if (defined($test) && defined($against));
5626 $newline .= ')' if (defined $not && defined($test) && defined($against));
5628 $newline .= " {" if (defined($brace));
5629 fix_insert_line($fixlinenr + 1, $newline);
5630 $fixed_assign_in_if = 1;
5635 # Find out what is on the end of the line after the
5637 substr($s, 0, length($c), '');
5639 $s =~ s/$;//g; # Remove any comments
5640 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5641 $c !~ /}\s*while\s*/)
5643 # Find out how long the conditional actually is.
5644 my @newlines = ($c =~ /\n/gs);
5645 my $cond_lines = 1 + $#newlines;
5648 $stat_real = raw_line($linenr, $cond_lines)
5649 . "\n" if ($cond_lines);
5650 if (defined($stat_real) && $cond_lines > 1) {
5651 $stat_real = "[...]\n$stat_real";
5654 if (ERROR("TRAILING_STATEMENTS",
5655 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5656 !$fixed_assign_in_if &&
5658 $fix && $perl_version_ok &&
5659 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5662 my $rest = rtrim($4);
5663 if ($rest =~ /;$/) {
5664 $fixed[$fixlinenr] = "\+$indent$test";
5665 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5671 # Check for bitwise tests written as boolean
5683 WARN("HEXADECIMAL_BOOLEAN_TEST",
5684 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5687 # if and else should not have general statements after it
5688 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5690 $s =~ s/$;//g; # Remove any comments
5691 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5692 ERROR("TRAILING_STATEMENTS",
5693 "trailing statements should be on next line\n" . $herecurr);
5696 # if should not continue a brace
5697 if ($line =~ /}\s*if\b/) {
5698 ERROR("TRAILING_STATEMENTS",
5699 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5702 # case and default should not have general statements after them
5703 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5705 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5709 ERROR("TRAILING_STATEMENTS",
5710 "trailing statements should be on next line\n" . $herecurr);
5713 # Check for }<nl>else {, these must be at the same
5714 # indent level to be relevant to each other.
5715 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5716 $previndent == $indent) {
5717 if (ERROR("ELSE_AFTER_BRACE",
5718 "else should follow close brace '}'\n" . $hereprev) &&
5719 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5720 fix_delete_line($fixlinenr - 1, $prevrawline);
5721 fix_delete_line($fixlinenr, $rawline);
5722 my $fixedline = $prevrawline;
5723 $fixedline =~ s/}\s*$//;
5724 if ($fixedline !~ /^\+\s*$/) {
5725 fix_insert_line($fixlinenr, $fixedline);
5727 $fixedline = $rawline;
5728 $fixedline =~ s/^(.\s*)else/$1} else/;
5729 fix_insert_line($fixlinenr, $fixedline);
5733 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5734 $previndent == $indent) {
5735 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5737 # Find out what is on the end of the line after the
5739 substr($s, 0, length($c), '');
5742 if ($s =~ /^\s*;/) {
5743 if (ERROR("WHILE_AFTER_BRACE",
5744 "while should follow close brace '}'\n" . $hereprev) &&
5745 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5746 fix_delete_line($fixlinenr - 1, $prevrawline);
5747 fix_delete_line($fixlinenr, $rawline);
5748 my $fixedline = $prevrawline;
5749 my $trailing = $rawline;
5750 $trailing =~ s/^\+//;
5751 $trailing = trim($trailing);
5752 $fixedline =~ s/}\s*$/} $trailing/;
5753 fix_insert_line($fixlinenr, $fixedline);
5758 #Specific variable tests
5759 while ($line =~ m{($Constant|$Lval)}g) {
5763 if ($var !~ /^$Constant$/ &&
5764 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5765 #Ignore some autogenerated defines and enum values
5766 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5767 #Ignore Page<foo> variants
5768 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5769 #Ignore SI style variants like nS, mV and dB
5770 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5771 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5772 #Ignore some three character SI units explicitly, like MiB and KHz
5773 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5774 while ($var =~ m{\b($Ident)}g) {
5776 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5778 seed_camelcase_includes();
5779 if (!$file && !$camelcase_file_seeded) {
5780 seed_camelcase_file($realfile);
5781 $camelcase_file_seeded = 1;
5784 if (!defined $camelcase{$word}) {
5785 $camelcase{$word} = 1;
5787 "Avoid CamelCase: <$word>\n" . $herecurr);
5793 #no spaces allowed after \ in define
5794 if ($line =~ /\#\s*define.*\\\s+$/) {
5795 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5796 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5798 $fixed[$fixlinenr] =~ s/\s+$//;
5802 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5803 # itself <asm/foo.h> (uses RAW line)
5804 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5806 my $checkfile = "include/linux/$file";
5807 if (-f "$root/$checkfile" &&
5808 $realfile ne $checkfile &&
5809 $1 !~ /$allowed_asm_includes/)
5811 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5812 if ($asminclude > 0) {
5813 if ($realfile =~ m{^arch/}) {
5814 CHK("ARCH_INCLUDE_LINUX",
5815 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5817 WARN("INCLUDE_LINUX",
5818 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5824 # multi-statement macros should be enclosed in a do while loop, grab the
5825 # first statement and ensure its the whole macro if its not enclosed
5826 # in a known good container
5827 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5828 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5831 my ($off, $dstat, $dcond, $rest);
5833 my $has_flow_statement = 0;
5834 my $has_arg_concat = 0;
5835 ($dstat, $dcond, $ln, $cnt, $off) =
5836 ctx_statement_block($linenr, $realcnt, 0);
5838 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5839 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5841 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5842 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5844 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5845 my $define_args = $1;
5846 my $define_stmt = $dstat;
5849 if (defined $define_args && $define_args ne "") {
5850 $define_args = substr($define_args, 1, length($define_args) - 2);
5851 $define_args =~ s/\s*//g;
5852 $define_args =~ s/\\\+?//g;
5853 @def_args = split(",", $define_args);
5857 $dstat =~ s/\\\n.//g;
5858 $dstat =~ s/^\s*//s;
5859 $dstat =~ s/\s*$//s;
5861 # Flatten any parentheses and braces
5862 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5863 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5864 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5868 # Flatten any obvious string concatenation.
5869 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5870 $dstat =~ s/$Ident\s*($String)/$1/)
5874 # Make asm volatile uses seem like a generic function
5875 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5877 my $exceptions = qr{
5890 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5893 my $stmt_cnt = statement_rawlines($ctx);
5894 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5897 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5898 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5899 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5900 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5901 $dstat !~ /$exceptions/ &&
5902 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5903 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5904 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5905 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5906 $dstat !~ /^for\s*$Constant$/ && # for (...)
5907 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5908 $dstat !~ /^do\s*{/ && # do {...
5909 $dstat !~ /^\(\{/ && # ({...
5910 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5912 if ($dstat =~ /^\s*if\b/) {
5913 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5914 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5915 } elsif ($dstat =~ /;/) {
5916 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5917 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5919 ERROR("COMPLEX_MACRO",
5920 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5925 # Make $define_stmt single line, comment-free, etc
5926 my @stmt_array = split('\n', $define_stmt);
5929 foreach my $l (@stmt_array) {
5934 } elsif ($l =~ /^[\+ ]/) {
5935 $define_stmt .= substr($l, 1);
5938 $define_stmt =~ s/$;//g;
5939 $define_stmt =~ s/\s+/ /g;
5940 $define_stmt = trim($define_stmt);
5942 # check if any macro arguments are reused (ignore '...' and 'type')
5943 foreach my $arg (@def_args) {
5944 next if ($arg =~ /\.\.\./);
5945 next if ($arg =~ /^type$/i);
5946 my $tmp_stmt = $define_stmt;
5947 $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;
5948 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5949 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5950 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5952 CHK("MACRO_ARG_REUSE",
5953 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5955 # check if any macro arguments may have other precedence issues
5956 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5957 ((defined($1) && $1 ne ',') ||
5958 (defined($2) && $2 ne ','))) {
5959 CHK("MACRO_ARG_PRECEDENCE",
5960 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5964 # check for macros with flow control, but without ## concatenation
5965 # ## concatenation is commonly a macro that defines a function so ignore those
5966 if ($has_flow_statement && !$has_arg_concat) {
5967 my $cnt = statement_rawlines($ctx);
5968 my $herectx = get_stat_here($linenr, $cnt, $here);
5970 WARN("MACRO_WITH_FLOW_CONTROL",
5971 "Macros with flow control statements should be avoided\n" . "$herectx");
5974 # check for line continuations outside of #defines, preprocessor #, and asm
5977 if ($prevline !~ /^..*\\$/ &&
5978 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5979 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5980 $line =~ /^\+.*\\$/) {
5981 WARN("LINE_CONTINUATIONS",
5982 "Avoid unnecessary line continuations\n" . $herecurr);
5986 # do {} while (0) macro tests:
5987 # single-statement macros do not need to be enclosed in do while (0) loop,
5988 # macro should not end with a semicolon
5989 if ($perl_version_ok &&
5990 $realfile !~ m@/vmlinux.lds.h$@ &&
5991 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5994 my ($off, $dstat, $dcond, $rest);
5996 ($dstat, $dcond, $ln, $cnt, $off) =
5997 ctx_statement_block($linenr, $realcnt, 0);
6000 $dstat =~ s/\\\n.//g;
6003 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6008 my $cnt = statement_rawlines($ctx);
6009 my $herectx = get_stat_here($linenr, $cnt, $here);
6011 if (($stmts =~ tr/;/;/) == 1 &&
6012 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6013 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6014 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6016 if (defined $semis && $semis ne "") {
6017 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6018 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6020 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6022 my $cnt = statement_rawlines($ctx);
6023 my $herectx = get_stat_here($linenr, $cnt, $here);
6025 WARN("TRAILING_SEMICOLON",
6026 "macros should not use a trailing semicolon\n" . "$herectx");
6030 # check for redundant bracing round if etc
6031 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6032 my ($level, $endln, @chunks) =
6033 ctx_statement_full($linenr, $realcnt, 1);
6034 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6035 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6036 if ($#chunks > 0 && $level == 0) {
6040 my $herectx = $here . "\n";
6041 my $ln = $linenr - 1;
6042 for my $chunk (@chunks) {
6043 my ($cond, $block) = @{$chunk};
6045 # If the condition carries leading newlines, then count those as offsets.
6046 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6047 my $offset = statement_rawlines($whitespace) - 1;
6049 $allowed[$allow] = 0;
6050 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6052 # We have looked at and allowed this specific line.
6053 $suppress_ifbraces{$ln + $offset} = 1;
6055 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6056 $ln += statement_rawlines($block) - 1;
6058 substr($block, 0, length($cond), '');
6060 $seen++ if ($block =~ /^\s*{/);
6062 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6063 if (statement_lines($cond) > 1) {
6064 #print "APW: ALLOWED: cond<$cond>\n";
6065 $allowed[$allow] = 1;
6067 if ($block =~/\b(?:if|for|while)\b/) {
6068 #print "APW: ALLOWED: block<$block>\n";
6069 $allowed[$allow] = 1;
6071 if (statement_block_size($block) > 1) {
6072 #print "APW: ALLOWED: lines block<$block>\n";
6073 $allowed[$allow] = 1;
6078 my $sum_allowed = 0;
6079 foreach (@allowed) {
6082 if ($sum_allowed == 0) {
6084 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6085 } elsif ($sum_allowed != $allow &&
6088 "braces {} should be used on all arms of this statement\n" . $herectx);
6093 if (!defined $suppress_ifbraces{$linenr - 1} &&
6094 $line =~ /\b(if|while|for|else)\b/) {
6097 # Check the pre-context.
6098 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6099 #print "APW: ALLOWED: pre<$1>\n";
6103 my ($level, $endln, @chunks) =
6104 ctx_statement_full($linenr, $realcnt, $-[0]);
6106 # Check the condition.
6107 my ($cond, $block) = @{$chunks[0]};
6108 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6109 if (defined $cond) {
6110 substr($block, 0, length($cond), '');
6112 if (statement_lines($cond) > 1) {
6113 #print "APW: ALLOWED: cond<$cond>\n";
6116 if ($block =~/\b(?:if|for|while)\b/) {
6117 #print "APW: ALLOWED: block<$block>\n";
6120 if (statement_block_size($block) > 1) {
6121 #print "APW: ALLOWED: lines block<$block>\n";
6124 # Check the post-context.
6125 if (defined $chunks[1]) {
6126 my ($cond, $block) = @{$chunks[1]};
6127 if (defined $cond) {
6128 substr($block, 0, length($cond), '');
6130 if ($block =~ /^\s*\{/) {
6131 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6135 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6136 my $cnt = statement_rawlines($block);
6137 my $herectx = get_stat_here($linenr, $cnt, $here);
6140 "braces {} are not necessary for single statement blocks\n" . $herectx);
6144 # check for single line unbalanced braces
6145 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6146 $sline =~ /^.\s*else\s*\{\s*$/) {
6147 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6150 # check for unnecessary blank lines around braces
6151 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6153 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6154 $fix && $prevrawline =~ /^\+/) {
6155 fix_delete_line($fixlinenr - 1, $prevrawline);
6158 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6160 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6162 fix_delete_line($fixlinenr, $rawline);
6166 # no volatiles please
6167 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6168 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6170 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6173 # Check for user-visible strings broken across lines, which breaks the ability
6174 # to grep for the string. Make exceptions when the previous string ends in a
6175 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6176 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6177 if ($line =~ /^\+\s*$String/ &&
6178 $prevline =~ /"\s*$/ &&
6179 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6180 if (WARN("SPLIT_STRING",
6181 "quoted string split across lines\n" . $hereprev) &&
6183 $prevrawline =~ /^\+.*"\s*$/ &&
6184 $last_coalesced_string_linenr != $linenr - 1) {
6185 my $extracted_string = get_quoted_string($line, $rawline);
6186 my $comma_close = "";
6187 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6191 fix_delete_line($fixlinenr - 1, $prevrawline);
6192 fix_delete_line($fixlinenr, $rawline);
6193 my $fixedline = $prevrawline;
6194 $fixedline =~ s/"\s*$//;
6195 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6196 fix_insert_line($fixlinenr - 1, $fixedline);
6197 $fixedline = $rawline;
6198 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6199 if ($fixedline !~ /\+\s*$/) {
6200 fix_insert_line($fixlinenr, $fixedline);
6202 $last_coalesced_string_linenr = $linenr;
6206 # check for missing a space in a string concatenation
6207 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6208 WARN('MISSING_SPACE',
6209 "break quoted strings at a space character\n" . $hereprev);
6212 # check for an embedded function name in a string when the function is known
6213 # This does not work very well for -f --file checking as it depends on patch
6214 # context providing the function name or a single line form for in-file
6215 # function declarations
6216 if ($line =~ /^\+.*$String/ &&
6217 defined($context_function) &&
6218 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6219 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6220 WARN("EMBEDDED_FUNCTION_NAME",
6221 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6224 # check for unnecessary function tracing like uses
6225 # This does not use $logFunctions because there are many instances like
6226 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6227 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6228 if (WARN("TRACING_LOGGING",
6229 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6231 fix_delete_line($fixlinenr, $rawline);
6235 # check for spaces before a quoted newline
6236 if ($rawline =~ /^.*\".*\s\\n/) {
6237 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6238 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6240 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6245 # concatenated string without spaces between elements
6246 if ($line =~ /$String[A-Z_]/ ||
6247 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6248 if (CHK("CONCATENATED_STRING",
6249 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6251 while ($line =~ /($String)/g) {
6252 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6253 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6254 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6259 # uncoalesced string fragments
6260 if ($line =~ /$String\s*[Lu]?"/) {
6261 if (WARN("STRING_FRAGMENTS",
6262 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6264 while ($line =~ /($String)(?=\s*")/g) {
6265 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6266 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6271 # check for non-standard and hex prefixed decimal printf formats
6272 my $show_L = 1; #don't show the same defect twice
6274 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6275 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6276 $string =~ s/%%/__/g;
6278 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6280 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6284 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6286 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6289 # check for 0x<decimal>
6290 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6291 ERROR("PRINTF_0XDECIMAL",
6292 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6296 # check for line continuations in quoted strings with odd counts of "
6297 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6298 WARN("LINE_CONTINUATIONS",
6299 "Avoid line continuations in quoted strings\n" . $herecurr);
6303 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6305 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6309 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6311 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6314 # check for needless "if (<foo>) fn(<foo>)" uses
6315 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6316 my $tested = quotemeta($1);
6317 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6318 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6320 if (WARN('NEEDLESS_IF',
6321 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6324 my $leading_tabs = "";
6325 my $new_leading_tabs = "";
6326 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6331 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6332 $new_leading_tabs = $1;
6333 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6340 fix_delete_line($fixlinenr - 1, $prevrawline);
6341 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6347 # check for unnecessary "Out of Memory" messages
6348 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6349 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6350 (defined $1 || defined $3) &&
6353 my $testline = $lines[$linenr - 3];
6355 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6356 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6358 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6359 $s !~ /\b__GFP_NOWARN\b/ ) {
6361 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6365 # check for logging functions with KERN_<LEVEL>
6366 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6367 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6369 if (WARN("UNNECESSARY_KERN_LEVEL",
6370 "Possible unnecessary $level\n" . $herecurr) &&
6372 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6376 # check for logging continuations
6377 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6378 WARN("LOGGING_CONTINUATION",
6379 "Avoid logging continuation uses where feasible\n" . $herecurr);
6382 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6383 if (defined $stat &&
6384 $line =~ /\b$logFunctions\s*\(/ &&
6385 index($stat, '"') >= 0) {
6386 my $lc = $stat =~ tr@\n@@;
6387 $lc = $lc + $linenr;
6388 my $stat_real = get_stat_real($linenr, $lc);
6389 pos($stat_real) = index($stat_real, '"');
6390 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6393 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6394 if (WARN("UNNECESSARY_MODIFIER",
6395 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6396 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6399 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6404 # check for mask then right shift without a parentheses
6405 if ($perl_version_ok &&
6406 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6407 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6408 WARN("MASK_THEN_SHIFT",
6409 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6412 # check for pointer comparisons to NULL
6413 if ($perl_version_ok) {
6414 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6417 $equal = "" if ($4 eq "!=");
6418 if (CHK("COMPARISON_TO_NULL",
6419 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6421 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6426 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6427 if ($line =~ /(\b$InitAttribute\b)/) {
6429 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6432 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6433 ERROR("MISPLACED_INIT",
6434 "$attr should be placed after $var\n" . $herecurr)) ||
6435 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6436 WARN("MISPLACED_INIT",
6437 "$attr should be placed after $var\n" . $herecurr))) &&
6439 $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;
6444 # check for $InitAttributeData (ie: __initdata) with const
6445 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6447 $attr =~ /($InitAttributePrefix)(.*)/;
6448 my $attr_prefix = $1;
6450 if (ERROR("INIT_ATTRIBUTE",
6451 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6453 $fixed[$fixlinenr] =~
6454 s/$InitAttributeData/${attr_prefix}initconst/;
6458 # check for $InitAttributeConst (ie: __initconst) without const
6459 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6461 if (ERROR("INIT_ATTRIBUTE",
6462 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6464 my $lead = $fixed[$fixlinenr] =~
6465 /(^\+\s*(?:static\s+))/;
6467 $lead = "$lead " if ($lead !~ /^\+$/);
6468 $lead = "${lead}const ";
6469 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6473 # check for __read_mostly with const non-pointer (should just be const)
6474 if ($line =~ /\b__read_mostly\b/ &&
6475 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6476 if (ERROR("CONST_READ_MOSTLY",
6477 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6479 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6483 # don't use __constant_<foo> functions outside of include/uapi/
6484 if ($realfile !~ m@^include/uapi/@ &&
6485 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6486 my $constant_func = $1;
6487 my $func = $constant_func;
6488 $func =~ s/^__constant_//;
6489 if (WARN("CONSTANT_CONVERSION",
6490 "$constant_func should be $func\n" . $herecurr) &&
6492 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6496 # prefer usleep_range over udelay
6497 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6499 # ignore udelay's < 10, however
6500 if (! ($delay < 10) ) {
6502 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6504 if ($delay > 2000) {
6506 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6510 # warn about unexpectedly long msleep's
6511 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6514 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6518 # check for comparisons of jiffies
6519 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6520 WARN("JIFFIES_COMPARISON",
6521 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6524 # check for comparisons of get_jiffies_64()
6525 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6526 WARN("JIFFIES_COMPARISON",
6527 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6530 # warn about #ifdefs in C files
6531 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6532 # print "#ifdef in C files should be avoided\n";
6533 # print "$herecurr";
6537 # warn about spacing in #ifdefs
6538 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6539 if (ERROR("SPACING",
6540 "exactly one space required after that #$1\n" . $herecurr) &&
6542 $fixed[$fixlinenr] =~
6543 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6548 # check for spinlock_t definitions without a comment.
6549 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6550 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6552 if (!ctx_has_comment($first_line, $linenr)) {
6553 CHK("UNCOMMENTED_DEFINITION",
6554 "$1 definition without comment\n" . $herecurr);
6557 # check for memory barriers without a comment.
6564 my $barrier_stems = qr{
6572 my $all_barriers = qr{
6574 smp_(?:$barrier_stems)|
6575 virt_(?:$barrier_stems)
6578 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6579 if (!ctx_has_comment($first_line, $linenr)) {
6580 WARN("MEMORY_BARRIER",
6581 "memory barrier without comment\n" . $herecurr);
6585 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6587 if ($realfile !~ m@^include/asm-generic/@ &&
6588 $realfile !~ m@/barrier\.h$@ &&
6589 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6590 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6591 WARN("MEMORY_BARRIER",
6592 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6595 # check for waitqueue_active without a comment.
6596 if ($line =~ /\bwaitqueue_active\s*\(/) {
6597 if (!ctx_has_comment($first_line, $linenr)) {
6598 WARN("WAITQUEUE_ACTIVE",
6599 "waitqueue_active without comment\n" . $herecurr);
6603 # check for data_race without a comment.
6604 if ($line =~ /\bdata_race\s*\(/) {
6605 if (!ctx_has_comment($first_line, $linenr)) {
6607 "data_race without comment\n" . $herecurr);
6611 # check of hardware specific defines
6612 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6614 "architecture specific defines should be avoided\n" . $herecurr);
6617 # check that the storage class is not after a type
6618 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6619 WARN("STORAGE_CLASS",
6620 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6622 # Check that the storage class is at the beginning of a declaration
6623 if ($line =~ /\b$Storage\b/ &&
6624 $line !~ /^.\s*$Storage/ &&
6625 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6626 $1 !~ /[\,\)]\s*$/) {
6627 WARN("STORAGE_CLASS",
6628 "storage class should be at the beginning of the declaration\n" . $herecurr);
6631 # check the location of the inline attribute, that it is between
6632 # storage class and type.
6633 if ($line =~ /\b$Type\s+$Inline\b/ ||
6634 $line =~ /\b$Inline\s+$Storage\b/) {
6635 ERROR("INLINE_LOCATION",
6636 "inline keyword should sit between storage class and type\n" . $herecurr);
6639 # Check for __inline__ and __inline, prefer inline
6640 if ($realfile !~ m@\binclude/uapi/@ &&
6641 $line =~ /\b(__inline__|__inline)\b/) {
6643 "plain inline is preferred over $1\n" . $herecurr) &&
6645 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6650 # Check for compiler attributes
6651 if ($realfile !~ m@\binclude/uapi/@ &&
6652 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6654 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6657 "alias" => "__alias",
6658 "aligned" => "__aligned",
6659 "always_inline" => "__always_inline",
6660 "assume_aligned" => "__assume_aligned",
6662 "const" => "__attribute_const__",
6664 "designated_init" => "__designated_init",
6665 "externally_visible" => "__visible",
6666 "format" => "printf|scanf",
6667 "gnu_inline" => "__gnu_inline",
6668 "malloc" => "__malloc",
6670 "no_caller_saved_registers" => "__no_caller_saved_registers",
6671 "noclone" => "__noclone",
6672 "noinline" => "noinline",
6673 "nonstring" => "__nonstring",
6674 "noreturn" => "__noreturn",
6675 "packed" => "__packed",
6677 "section" => "__section",
6682 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6685 $params = $2 if defined($2);
6686 my $curr_attr = $orig_attr;
6687 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6688 if (exists($attr_list{$curr_attr})) {
6689 my $new = $attr_list{$curr_attr};
6690 if ($curr_attr eq "format" && $params) {
6691 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6694 $new = "$new$params";
6696 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6697 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6699 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6700 $fixed[$fixlinenr] =~ s/$remove//;
6701 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6702 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6703 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6708 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6709 if ($attr =~ /^_*unused/) {
6710 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6711 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6715 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6716 if ($perl_version_ok &&
6717 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6718 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6719 $line =~ /\b__weak\b/)) {
6720 ERROR("WEAK_DECLARATION",
6721 "Using weak declarations can have unintended link defects\n" . $herecurr);
6724 # check for c99 types like uint8_t used outside of uapi/ and tools/
6725 if ($realfile !~ m@\binclude/uapi/@ &&
6726 $realfile !~ m@\btools/@ &&
6727 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6729 if ($type =~ /\b($typeC99Typedefs)\b/) {
6731 my $kernel_type = 'u';
6732 $kernel_type = 's' if ($type =~ /^_*[si]/);
6735 if (CHK("PREFER_KERNEL_TYPES",
6736 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6738 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6743 # check for cast of C90 native int or longer types constants
6744 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6748 my $newconst = $const;
6749 $newconst =~ s/${Int_type}$//;
6750 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6751 if ($cast =~ /\blong\s+long\b/) {
6753 } elsif ($cast =~ /\blong\b/) {
6756 if (WARN("TYPECAST_INT_CONSTANT",
6757 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6759 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6763 # check for sizeof(&)
6764 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6765 WARN("SIZEOF_ADDRESS",
6766 "sizeof(& should be avoided\n" . $herecurr);
6769 # check for sizeof without parenthesis
6770 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6771 if (WARN("SIZEOF_PARENTHESIS",
6772 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6774 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6778 # check for struct spinlock declarations
6779 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6780 WARN("USE_SPINLOCK_T",
6781 "struct spinlock should be spinlock_t\n" . $herecurr);
6784 # check for seq_printf uses that could be seq_puts
6785 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6786 my $fmt = get_quoted_string($line, $rawline);
6789 if (WARN("PREFER_SEQ_PUTS",
6790 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6792 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6797 # check for vsprintf extension %p<foo> misuses
6798 if ($perl_version_ok &&
6800 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6801 $1 !~ /^_*volatile_*$/) {
6804 my $lc = $stat =~ tr@\n@@;
6805 $lc = $lc + $linenr;
6806 for (my $count = $linenr; $count <= $lc; $count++) {
6810 my $bad_specifier = "";
6811 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6814 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6818 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6819 ($extension eq "f" &&
6820 defined $qualifier && $qualifier !~ /^w/) ||
6821 ($extension eq "4" &&
6822 defined $qualifier && $qualifier !~ /^cc/)) {
6823 $bad_specifier = $specifier;
6826 if ($extension eq "x" && !defined($stat_real)) {
6827 if (!defined($stat_real)) {
6828 $stat_real = get_stat_real($linenr, $lc);
6830 WARN("VSPRINTF_SPECIFIER_PX",
6831 "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");
6834 if ($bad_specifier ne "") {
6835 my $stat_real = get_stat_real($linenr, $lc);
6836 my $msg_level = \&WARN;
6837 my $ext_type = "Invalid";
6839 if ($bad_specifier =~ /p[Ff]/) {
6840 $use = " - use %pS instead";
6841 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6842 } elsif ($bad_specifier =~ /pA/) {
6843 $use = " - '%pA' is only intended to be used from Rust code";
6844 $msg_level = \&ERROR;
6847 &{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6848 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6853 # Check for misused memsets
6854 if ($perl_version_ok &&
6856 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6862 if ($ms_size =~ /^(0x|)0$/i) {
6864 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6865 } elsif ($ms_size =~ /^(0x|)1$/i) {
6867 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6871 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6872 # if ($perl_version_ok &&
6874 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6875 # if (WARN("PREFER_ETHER_ADDR_COPY",
6876 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6878 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6882 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6883 # if ($perl_version_ok &&
6885 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6886 # WARN("PREFER_ETHER_ADDR_EQUAL",
6887 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6890 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6891 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6892 # if ($perl_version_ok &&
6894 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6898 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6899 # if (WARN("PREFER_ETH_ZERO_ADDR",
6900 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6902 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6904 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6905 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6906 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6908 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6913 # strlcpy uses that should likely be strscpy
6914 if ($line =~ /\bstrlcpy\s*\(/) {
6916 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6919 # typecasts on min/max could be min_t/max_t
6920 if ($perl_version_ok &&
6922 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6923 if (defined $2 || defined $7) {
6925 my $cast1 = deparenthesize($2);
6927 my $cast2 = deparenthesize($7);
6931 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6932 $cast = "$cast1 or $cast2";
6933 } elsif ($cast1 ne "") {
6939 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6943 # check usleep_range arguments
6944 if ($perl_version_ok &&
6946 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6950 WARN("USLEEP_RANGE",
6951 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6952 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6954 WARN("USLEEP_RANGE",
6955 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6959 # check for naked sscanf
6960 if ($perl_version_ok &&
6962 $line =~ /\bsscanf\b/ &&
6963 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6964 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6965 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6966 my $lc = $stat =~ tr@\n@@;
6967 $lc = $lc + $linenr;
6968 my $stat_real = get_stat_real($linenr, $lc);
6969 WARN("NAKED_SSCANF",
6970 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6973 # check for simple sscanf that should be kstrto<foo>
6974 if ($perl_version_ok &&
6976 $line =~ /\bsscanf\b/) {
6977 my $lc = $stat =~ tr@\n@@;
6978 $lc = $lc + $linenr;
6979 my $stat_real = get_stat_real($linenr, $lc);
6980 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6982 my $count = $format =~ tr@%@%@;
6984 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6985 WARN("SSCANF_TO_KSTRTO",
6986 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6991 # check for new externs in .h files.
6992 if ($realfile =~ /\.h$/ &&
6993 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6994 if (CHK("AVOID_EXTERNS",
6995 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6997 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7001 # check for new externs in .c files.
7002 if ($realfile =~ /\.c$/ && defined $stat &&
7003 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7005 my $function_name = $1;
7006 my $paren_space = $2;
7009 if (defined $cond) {
7010 substr($s, 0, length($cond), '');
7014 WARN("AVOID_EXTERNS",
7015 "externs should be avoided in .c files\n" . $herecurr);
7018 if ($paren_space =~ /\n/) {
7019 WARN("FUNCTION_ARGUMENTS",
7020 "arguments for function declarations should follow identifier\n" . $herecurr);
7023 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7024 $stat =~ /^.\s*extern\s+/)
7026 WARN("AVOID_EXTERNS",
7027 "externs should be avoided in .c files\n" . $herecurr);
7030 # check for function declarations that have arguments without identifier names
7031 if (defined $stat &&
7032 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7034 my $args = trim($1);
7035 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7037 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7038 WARN("FUNCTION_ARGUMENTS",
7039 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7044 # check for function definitions
7045 if ($perl_version_ok &&
7047 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7048 $context_function = $1;
7050 # check for multiline function definition with misplaced open brace
7052 my $cnt = statement_rawlines($stat);
7053 my $herectx = $here . "\n";
7054 for (my $n = 0; $n < $cnt; $n++) {
7055 my $rl = raw_line($linenr, $n);
7056 $herectx .= $rl . "\n";
7057 $ok = 1 if ($rl =~ /^[ \+]\{/);
7058 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7059 last if $rl =~ /^[ \+].*\{/;
7063 "open brace '{' following function definitions go on the next line\n" . $herectx);
7067 # checks for new __setup's
7068 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7071 if (!grep(/$name/, @setup_docs)) {
7072 CHK("UNDOCUMENTED_SETUP",
7073 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7077 # check for pointless casting of alloc functions
7078 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7079 WARN("UNNECESSARY_CASTS",
7080 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7084 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7085 if ($perl_version_ok &&
7086 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7087 CHK("ALLOC_SIZEOF_STRUCT",
7088 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7091 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7092 if ($perl_version_ok &&
7094 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7098 my $newfunc = "kmalloc_array";
7099 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7100 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7101 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7104 if ($a1 =~ /^sizeof\s*\S/) {
7108 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7109 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7110 my $cnt = statement_rawlines($stat);
7111 my $herectx = get_stat_here($linenr, $cnt, $here);
7113 if (WARN("ALLOC_WITH_MULTIPLY",
7114 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7117 $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;
7122 # check for krealloc arg reuse
7123 if ($perl_version_ok &&
7124 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7126 WARN("KREALLOC_ARG_REUSE",
7127 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7130 # check for alloc argument mismatch
7131 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7132 WARN("ALLOC_ARRAY_ARGS",
7133 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7136 # check for multiple semicolons
7137 if ($line =~ /;\s*;\s*$/) {
7138 if (WARN("ONE_SEMICOLON",
7139 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7141 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7145 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7146 if ($realfile !~ m@^include/uapi/@ &&
7147 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7149 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7150 if (CHK("BIT_MACRO",
7151 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7153 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7157 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7158 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7159 WARN("IS_ENABLED_CONFIG",
7160 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7163 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7164 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7166 if (WARN("PREFER_IS_ENABLED",
7167 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7169 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7173 # check for /* fallthrough */ like comment, prefer fallthrough;
7174 my @fallthroughs = (
7177 'lint -fallthrough[ \t]*',
7178 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7179 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7180 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7181 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7183 if ($raw_comment ne '') {
7184 foreach my $ft (@fallthroughs) {
7185 if ($raw_comment =~ /$ft/) {
7186 my $msg_level = \&WARN;
7187 $msg_level = \&CHK if ($file);
7188 &{$msg_level}("PREFER_FALLTHROUGH",
7189 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7195 # check for switch/default statements without a break;
7196 if ($perl_version_ok &&
7198 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7199 my $cnt = statement_rawlines($stat);
7200 my $herectx = get_stat_here($linenr, $cnt, $here);
7202 WARN("DEFAULT_NO_BREAK",
7203 "switch default: should use break\n" . $herectx);
7206 # check for gcc specific __FUNCTION__
7207 if ($line =~ /\b__FUNCTION__\b/) {
7208 if (WARN("USE_FUNC",
7209 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7211 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7215 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7216 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7218 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7221 # check for use of yield()
7222 if ($line =~ /\byield\s*\(\s*\)/) {
7224 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7227 # check for comparisons against true and false
7228 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7236 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7238 my $type = lc($otype);
7239 if ($type =~ /^(?:true|false)$/) {
7240 if (("$test" eq "==" && "$type" eq "true") ||
7241 ("$test" eq "!=" && "$type" eq "false")) {
7245 CHK("BOOL_COMPARISON",
7246 "Using comparison to $otype is error prone\n" . $herecurr);
7248 ## maybe suggesting a correct construct would better
7249 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7254 # check for semaphores initialized locked
7255 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7256 WARN("CONSIDER_COMPLETION",
7257 "consider using a completion\n" . $herecurr);
7260 # recommend kstrto* over simple_strto* and strict_strto*
7261 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7262 WARN("CONSIDER_KSTRTO",
7263 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7266 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7267 if ($line =~ /^.\s*__initcall\s*\(/) {
7268 WARN("USE_DEVICE_INITCALL",
7269 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7272 # check for spin_is_locked(), suggest lockdep instead
7273 if ($line =~ /\bspin_is_locked\(/) {
7275 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7278 # check for deprecated apis
7279 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7280 my $deprecated_api = $1;
7281 my $new_api = $deprecated_apis{$deprecated_api};
7282 WARN("DEPRECATED_API",
7283 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7286 # check for various structs that are normally const (ops, kgdb, device_tree)
7287 # and avoid what seem like struct definitions 'struct foo {'
7288 if (defined($const_structs) &&
7289 $line !~ /\bconst\b/ &&
7290 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7291 WARN("CONST_STRUCT",
7292 "struct $1 should normally be const\n" . $herecurr);
7295 # use of NR_CPUS is usually wrong
7296 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7297 # ignore designated initializers using NR_CPUS
7298 if ($line =~ /\bNR_CPUS\b/ &&
7299 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7300 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7301 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7302 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7303 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7304 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7307 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7310 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7311 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7312 ERROR("DEFINE_ARCH_HAS",
7313 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7316 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7317 if ($perl_version_ok &&
7318 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7319 WARN("LIKELY_MISUSE",
7320 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7323 # return sysfs_emit(foo, fmt, ...) fmt without newline
7324 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7325 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7326 my $offset = $+[6] - 1;
7327 if (WARN("SYSFS_EMIT",
7328 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7330 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7334 # nested likely/unlikely calls
7335 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7336 WARN("LIKELY_MISUSE",
7337 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7340 # whine mightly about in_atomic
7341 if ($line =~ /\bin_atomic\s*\(/) {
7342 if ($realfile =~ m@^drivers/@) {
7344 "do not use in_atomic in drivers\n" . $herecurr);
7345 } elsif ($realfile !~ m@^kernel/@) {
7347 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7351 # check for lockdep_set_novalidate_class
7352 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7353 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7354 if ($realfile !~ m@^kernel/lockdep@ &&
7355 $realfile !~ m@^include/linux/lockdep@ &&
7356 $realfile !~ m@^drivers/base/core@) {
7358 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7362 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7363 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7364 WARN("EXPORTED_WORLD_WRITABLE",
7365 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7368 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7369 # and whether or not function naming is typical and if
7370 # DEVICE_ATTR permissions uses are unusual too
7371 if ($perl_version_ok &&
7373 $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*\)/) {
7378 my $octal_perms = perms_to_octal($perms);
7379 if ($show =~ /^${var}_show$/ &&
7380 $store =~ /^${var}_store$/ &&
7381 $octal_perms eq "0644") {
7382 if (WARN("DEVICE_ATTR_RW",
7383 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7385 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7387 } elsif ($show =~ /^${var}_show$/ &&
7388 $store =~ /^NULL$/ &&
7389 $octal_perms eq "0444") {
7390 if (WARN("DEVICE_ATTR_RO",
7391 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7393 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7395 } elsif ($show =~ /^NULL$/ &&
7396 $store =~ /^${var}_store$/ &&
7397 $octal_perms eq "0200") {
7398 if (WARN("DEVICE_ATTR_WO",
7399 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7401 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7403 } elsif ($octal_perms eq "0644" ||
7404 $octal_perms eq "0444" ||
7405 $octal_perms eq "0200") {
7406 my $newshow = "$show";
7407 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7408 my $newstore = $store;
7409 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7411 if ($show ne $newshow) {
7412 $rename .= " '$show' to '$newshow'";
7414 if ($store ne $newstore) {
7415 $rename .= " '$store' to '$newstore'";
7417 WARN("DEVICE_ATTR_FUNCTIONS",
7418 "Consider renaming function(s)$rename\n" . $herecurr);
7420 WARN("DEVICE_ATTR_PERMS",
7421 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7425 # Mode permission misuses where it seems decimal should be octal
7426 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7427 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7428 # specific definition of not visible in sysfs.
7429 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7430 # use the default permissions
7431 if ($perl_version_ok &&
7433 $line =~ /$mode_perms_search/) {
7434 foreach my $entry (@mode_permission_funcs) {
7435 my $func = $entry->[0];
7436 my $arg_pos = $entry->[1];
7438 my $lc = $stat =~ tr@\n@@;
7439 $lc = $lc + $linenr;
7440 my $stat_real = get_stat_real($linenr, $lc);
7445 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7447 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7448 if ($stat =~ /$test/) {
7450 $val = $6 if ($skip_args ne "");
7451 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7452 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7453 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7454 ERROR("NON_OCTAL_PERMISSIONS",
7455 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7457 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7458 ERROR("EXPORTED_WORLD_WRITABLE",
7459 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7465 # check for uses of S_<PERMS> that could be octal for readability
7466 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7468 my $octal = perms_to_octal($oval);
7469 if (WARN("SYMBOLIC_PERMS",
7470 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7472 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7476 # validate content of MODULE_LICENSE against list from include/linux/module.h
7477 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7478 my $extracted_string = get_quoted_string($line, $rawline);
7479 my $valid_licenses = qr{
7482 GPL\ and\ additional\ rights|
7488 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7489 WARN("MODULE_LICENSE",
7490 "unknown module license " . $extracted_string . "\n" . $herecurr);
7492 if (!$file && $extracted_string eq '"GPL v2"') {
7493 if (WARN("MODULE_LICENSE",
7494 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7496 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7501 # check for sysctl duplicate constants
7502 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7503 WARN("DUPLICATED_SYSCTL_CONST",
7504 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7508 # If we have no input at all, then there is nothing to report on
7509 # so just keep quiet.
7510 if ($#rawlines == -1) {
7514 # In mailback mode only produce a report in the negative, for
7515 # things that appear to be patches.
7516 if ($mailback && ($clean == 1 || !$is_patch)) {
7520 # This is not a patch, and we are in 'no-patch' mode so
7522 if (!$chk_patch && !$is_patch) {
7526 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7527 ERROR("NOT_UNIFIED_DIFF",
7528 "Does not appear to be a unified-diff format patch\n");
7530 if ($is_patch && $has_commit_log && $chk_signoff) {
7531 if ($signoff == 0) {
7532 ERROR("MISSING_SIGN_OFF",
7533 "Missing Signed-off-by: line(s)\n");
7534 } elsif ($authorsignoff != 1) {
7535 # authorsignoff values:
7536 # 0 -> missing sign off
7537 # 1 -> sign off identical
7538 # 2 -> names and addresses match, comments mismatch
7539 # 3 -> addresses match, names different
7540 # 4 -> names match, addresses different
7541 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7543 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7545 if ($authorsignoff == 0) {
7546 ERROR("NO_AUTHOR_SIGN_OFF",
7547 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7548 } elsif ($authorsignoff == 2) {
7549 CHK("FROM_SIGN_OFF_MISMATCH",
7550 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7551 } elsif ($authorsignoff == 3) {
7552 WARN("FROM_SIGN_OFF_MISMATCH",
7553 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7554 } elsif ($authorsignoff == 4) {
7555 WARN("FROM_SIGN_OFF_MISMATCH",
7556 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7557 } elsif ($authorsignoff == 5) {
7558 WARN("FROM_SIGN_OFF_MISMATCH",
7559 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7564 print report_dump();
7565 if ($summary && !($clean == 1 && $quiet == 1)) {
7566 print "$filename " if ($summary_file);
7567 print "total: $cnt_error errors, $cnt_warn warnings, " .
7568 (($check)? "$cnt_chk checks, " : "") .
7569 "$cnt_lines lines checked\n";
7573 # If there were any defects found and not already fixing them
7574 if (!$clean and !$fix) {
7577 NOTE: For some of the reported defects, checkpatch may be able to
7578 mechanically convert to the typical style using --fix or --fix-inplace.
7581 # If there were whitespace errors which cleanpatch can fix
7582 # then suggest that.
7583 if ($rpt_cleaners) {
7587 NOTE: Whitespace errors detected.
7588 You may wish to use scripts/cleanpatch or scripts/cleanfile
7593 if ($clean == 0 && $fix &&
7594 ("@rawlines" ne "@fixed" ||
7595 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7596 my $newfile = $filename;
7597 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7601 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7603 open($f, '>', $newfile)
7604 or die "$P: Can't open $newfile for write\n";
7605 foreach my $fixed_line (@fixed) {
7608 if ($linecount > 3) {
7609 $fixed_line =~ s/^\+//;
7610 print $f $fixed_line . "\n";
7613 print $f $fixed_line . "\n";
7621 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7623 Do _NOT_ trust the results written to this file.
7624 Do _NOT_ submit these changes without inspecting them for correctness.
7626 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7627 No warranties, expressed or implied...
7635 print "$vname has no obvious style problems and is ready for submission.\n";
7637 print "$vname has style problems, please review.\n";