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 $typeTypedefs = qr{(?x:
581 $typeOtherOSTypedefs\b|
582 $typeKernelTypedefs\b
585 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
587 our $logFunctions = qr{(?x:
588 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
589 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
591 WARN(?:_RATELIMIT|_ONCE|)|
594 seq_vprintf|seq_printf|seq_puts
597 our $allocFunctions = qr{(?x:
599 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
602 (?:\w+)?alloc_skb(?:_ip_align)? |
603 # dev_alloc_skb/netdev_alloc_skb, et al
607 our $signature_tags = qr{(?xi:
619 our $tracing_logging_tags = qr{(?xi:
643 sub edit_distance_min {
645 my $len = scalar @arr;
646 if ((scalar @arr) < 1) {
647 # if underflow, return
651 for my $i (0 .. ($len-1)) {
652 if ($arr[$i] < $min) {
659 sub get_edit_distance {
660 my ($str1, $str2) = @_;
665 my $len1 = length($str1);
666 my $len2 = length($str2);
667 # two dimensional array storing minimum edit distance
669 for my $i (0 .. $len1) {
670 for my $j (0 .. $len2) {
672 $distance[$i][$j] = $j;
674 $distance[$i][$j] = $i;
675 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
676 $distance[$i][$j] = $distance[$i - 1][$j - 1];
678 my $dist1 = $distance[$i][$j - 1]; #insert distance
679 my $dist2 = $distance[$i - 1][$j]; # remove
680 my $dist3 = $distance[$i - 1][$j - 1]; #replace
681 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
685 return $distance[$len1][$len2];
688 sub find_standard_signature {
690 my @standard_signature_tags = (
691 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
692 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
694 foreach my $signature (@standard_signature_tags) {
695 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
701 our @typeListMisordered = (
702 qr{char\s+(?:un)?signed},
703 qr{int\s+(?:(?:un)?signed\s+)?short\s},
704 qr{int\s+short(?:\s+(?:un)?signed)},
705 qr{short\s+int(?:\s+(?:un)?signed)},
706 qr{(?:un)?signed\s+int\s+short},
707 qr{short\s+(?:un)?signed},
708 qr{long\s+int\s+(?:un)?signed},
709 qr{int\s+long\s+(?:un)?signed},
710 qr{long\s+(?:un)?signed\s+int},
711 qr{int\s+(?:un)?signed\s+long},
712 qr{int\s+(?:un)?signed},
713 qr{int\s+long\s+long\s+(?:un)?signed},
714 qr{long\s+long\s+int\s+(?:un)?signed},
715 qr{long\s+long\s+(?:un)?signed\s+int},
716 qr{long\s+long\s+(?:un)?signed},
717 qr{long\s+(?:un)?signed},
722 qr{(?:(?:un)?signed\s+)?char},
723 qr{(?:(?:un)?signed\s+)?short\s+int},
724 qr{(?:(?:un)?signed\s+)?short},
725 qr{(?:(?:un)?signed\s+)?int},
726 qr{(?:(?:un)?signed\s+)?long\s+int},
727 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
728 qr{(?:(?:un)?signed\s+)?long\s+long},
729 qr{(?:(?:un)?signed\s+)?long},
738 qr{${Ident}_handler},
739 qr{${Ident}_handler_fn},
743 our $C90_int_types = qr{(?x:
744 long\s+long\s+int\s+(?:un)?signed|
745 long\s+long\s+(?:un)?signed\s+int|
746 long\s+long\s+(?:un)?signed|
747 (?:(?:un)?signed\s+)?long\s+long\s+int|
748 (?:(?:un)?signed\s+)?long\s+long|
749 int\s+long\s+long\s+(?:un)?signed|
750 int\s+(?:(?:un)?signed\s+)?long\s+long|
752 long\s+int\s+(?:un)?signed|
753 long\s+(?:un)?signed\s+int|
754 long\s+(?:un)?signed|
755 (?:(?:un)?signed\s+)?long\s+int|
756 (?:(?:un)?signed\s+)?long|
757 int\s+long\s+(?:un)?signed|
758 int\s+(?:(?:un)?signed\s+)?long|
761 (?:(?:un)?signed\s+)?int
764 our @typeListFile = ();
765 our @typeListWithAttr = (
767 qr{struct\s+$InitAttribute\s+$Ident},
768 qr{union\s+$InitAttribute\s+$Ident},
771 our @modifierList = (
774 our @modifierListFile = ();
776 our @mode_permission_funcs = (
778 ["module_param_(?:array|named|string)", 4],
779 ["module_param_array_named", 5],
780 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
781 ["proc_create(?:_data|)", 2],
782 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
783 ["IIO_DEV_ATTR_[A-Z_]+", 1],
784 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
785 ["SENSOR_TEMPLATE(?:_2|)", 3],
789 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
791 #Create a search pattern for all these functions to speed up a loop below
792 our $mode_perms_search = "";
793 foreach my $entry (@mode_permission_funcs) {
794 $mode_perms_search .= '|' if ($mode_perms_search ne "");
795 $mode_perms_search .= $entry->[0];
797 $mode_perms_search = "(?:${mode_perms_search})";
799 our %deprecated_apis = (
800 "synchronize_rcu_bh" => "synchronize_rcu",
801 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
802 "call_rcu_bh" => "call_rcu",
803 "rcu_barrier_bh" => "rcu_barrier",
804 "synchronize_sched" => "synchronize_rcu",
805 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
806 "call_rcu_sched" => "call_rcu",
807 "rcu_barrier_sched" => "rcu_barrier",
808 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
809 "cond_synchronize_sched" => "cond_synchronize_rcu",
812 #Create a search pattern for all these strings to speed up a loop below
813 our $deprecated_apis_search = "";
814 foreach my $entry (keys %deprecated_apis) {
815 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
816 $deprecated_apis_search .= $entry;
818 $deprecated_apis_search = "(?:${deprecated_apis_search})";
820 our $mode_perms_world_writable = qr{
828 our %mode_permission_string_types = (
847 #Create a search pattern for all these strings to speed up a loop below
848 our $mode_perms_string_search = "";
849 foreach my $entry (keys %mode_permission_string_types) {
850 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
851 $mode_perms_string_search .= $entry;
853 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
854 our $multi_mode_perms_string_search = qr{
855 ${single_mode_perms_string_search}
856 (?:\s*\|\s*${single_mode_perms_string_search})*
862 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
869 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
870 $curpos = pos($string);
873 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
875 $to |= $mode_permission_string_types{$match};
876 $val .= '\s*\|\s*' if ($val ne "");
880 $oval =~ s/^\s*\|\s*//;
881 $oval =~ s/\s*\|\s*$//;
882 return sprintf("%04o", $to);
885 our $allowed_asm_includes = qr{(?x:
891 # memory.h: ARM has a custom one
893 # Load common spelling mistakes and build regular expression list.
897 if (open(my $spelling, '<', $spelling_file)) {
898 while (<$spelling>) {
901 $line =~ s/\s*\n?$//g;
904 next if ($line =~ m/^\s*#/);
905 next if ($line =~ m/^\s*$/);
907 my ($suspect, $fix) = split(/\|\|/, $line);
909 $spelling_fix{$suspect} = $fix;
913 warn "No typos will be found - file '$spelling_file': $!\n";
917 if (open(my $spelling, '<', $codespellfile)) {
918 while (<$spelling>) {
921 $line =~ s/\s*\n?$//g;
924 next if ($line =~ m/^\s*#/);
925 next if ($line =~ m/^\s*$/);
926 next if ($line =~ m/, disabled/i);
930 my ($suspect, $fix) = split(/->/, $line);
932 $spelling_fix{$suspect} = $fix;
936 warn "No codespell typos will be found - file '$codespellfile': $!\n";
940 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
943 my ($wordsRef, $file) = @_;
945 if (open(my $words, '<', $file)) {
949 $line =~ s/\s*\n?$//g;
952 next if ($line =~ m/^\s*#/);
953 next if ($line =~ m/^\s*$/);
955 print("$file: '$line' invalid - ignored\n");
959 $$wordsRef .= '|' if (defined $$wordsRef);
970 if (show_type("CONST_STRUCT")) {
971 read_words(\$const_structs, $conststructsfile)
972 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
975 if (defined($typedefsfile)) {
976 my $typeOtherTypedefs;
977 read_words(\$typeOtherTypedefs, $typedefsfile)
978 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
979 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
983 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
984 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
985 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
986 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
987 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
993 (?:$Modifier\s+|const\s+)*
995 (?:typeof|__typeof__)\s*\([^\)]*\)|
999 (?:\s+$Modifier|\s+const)*
1001 $NonptrTypeMisordered = qr{
1002 (?:$Modifier\s+|const\s+)*
1006 (?:\s+$Modifier|\s+const)*
1008 $NonptrTypeWithAttr = qr{
1009 (?:$Modifier\s+|const\s+)*
1011 (?:typeof|__typeof__)\s*\([^\)]*\)|
1012 (?:$typeTypedefs\b)|
1013 (?:${allWithAttr}\b)
1015 (?:\s+$Modifier|\s+const)*
1019 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1020 (?:\s+$Inline|\s+$Modifier)*
1022 $TypeMisordered = qr{
1023 $NonptrTypeMisordered
1024 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1025 (?:\s+$Inline|\s+$Modifier)*
1027 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1028 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1032 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1034 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1035 # requires at least perl version v5.10.0
1036 # Any use must be runtime checked with $^V
1038 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1039 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1040 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1042 our $declaration_macros = qr{(?x:
1043 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1044 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1045 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1046 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1049 our %allow_repeated_words = (
1056 sub deparenthesize {
1058 return "" if (!defined($string));
1060 while ($string =~ /^\s*\(.*\)\s*$/) {
1061 $string =~ s@^\s*\(\s*@@;
1062 $string =~ s@\s*\)\s*$@@;
1065 $string =~ s@\s+@ @g;
1070 sub seed_camelcase_file {
1073 return if (!(-f $file));
1077 open(my $include_file, '<', "$file")
1078 or warn "$P: Can't read '$file' $!\n";
1079 my $text = <$include_file>;
1080 close($include_file);
1082 my @lines = split('\n', $text);
1084 foreach my $line (@lines) {
1085 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1086 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1088 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1090 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1096 our %maintained_status = ();
1098 sub is_maintained_obsolete {
1099 my ($filename) = @_;
1101 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1103 if (!exists($maintained_status{$filename})) {
1104 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1107 return $maintained_status{$filename} =~ /obsolete/i;
1110 sub is_SPDX_License_valid {
1113 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1115 my $root_path = abs_path($root);
1116 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1117 return 0 if ($status ne "");
1121 my $camelcase_seeded = 0;
1122 sub seed_camelcase_includes {
1123 return if ($camelcase_seeded);
1126 my $camelcase_cache = "";
1127 my @include_files = ();
1129 $camelcase_seeded = 1;
1131 if (-e "$gitroot") {
1132 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1133 chomp $git_last_include_commit;
1134 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1136 my $last_mod_date = 0;
1137 $files = `find $root/include -name "*.h"`;
1138 @include_files = split('\n', $files);
1139 foreach my $file (@include_files) {
1140 my $date = POSIX::strftime("%Y%m%d%H%M",
1141 localtime((stat $file)[9]));
1142 $last_mod_date = $date if ($last_mod_date < $date);
1144 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1147 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1148 open(my $camelcase_file, '<', "$camelcase_cache")
1149 or warn "$P: Can't read '$camelcase_cache' $!\n";
1150 while (<$camelcase_file>) {
1154 close($camelcase_file);
1159 if (-e "$gitroot") {
1160 $files = `${git_command} ls-files "include/*.h"`;
1161 @include_files = split('\n', $files);
1164 foreach my $file (@include_files) {
1165 seed_camelcase_file($file);
1168 if ($camelcase_cache ne "") {
1169 unlink glob ".checkpatch-camelcase.*";
1170 open(my $camelcase_file, '>', "$camelcase_cache")
1171 or warn "$P: Can't write '$camelcase_cache' $!\n";
1172 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1173 print $camelcase_file ("$_\n");
1175 close($camelcase_file);
1179 sub git_is_single_file {
1180 my ($filename) = @_;
1182 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1184 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1185 my $count = $output =~ tr/\n//;
1186 return $count eq 1 && $output =~ m{^${filename}$};
1189 sub git_commit_info {
1190 my ($commit, $id, $desc) = @_;
1192 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1194 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1195 $output =~ s/^\s*//gm;
1196 my @lines = split("\n", $output);
1198 return ($id, $desc) if ($#lines < 0);
1200 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1201 # Maybe one day convert this block of bash into something that returns
1202 # all matching commit ids, but it's very slow...
1204 # echo "checking commits $1..."
1205 # git rev-list --remotes | grep -i "^$1" |
1206 # while read line ; do
1207 # git log --format='%H %s' -1 $line |
1208 # echo "commit $(cut -c 1-12,41-)"
1210 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1211 $lines[0] =~ /^fatal: bad object $commit/) {
1214 $id = substr($lines[0], 0, 12);
1215 $desc = substr($lines[0], 41);
1218 return ($id, $desc);
1221 $chk_signoff = 0 if ($file);
1226 my @fixed_inserted = ();
1227 my @fixed_deleted = ();
1230 # If input is git commits, extract all commits from the commit expressions.
1231 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1232 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1236 foreach my $commit_expr (@ARGV) {
1238 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1239 $git_range = "-$2 $1";
1240 } elsif ($commit_expr =~ m/\.\./) {
1241 $git_range = "$commit_expr";
1243 $git_range = "-1 $commit_expr";
1245 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1246 foreach my $line (split(/\n/, $lines)) {
1247 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1248 next if (!defined($1) || !defined($2));
1251 unshift(@commits, $sha1);
1252 $git_commits{$sha1} = $subject;
1255 die "$P: no git commits after extraction!\n" if (@commits == 0);
1260 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1261 for my $filename (@ARGV) {
1263 my $is_git_file = git_is_single_file($filename);
1264 my $oldfile = $file;
1265 $file = 1 if ($is_git_file);
1267 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1268 die "$P: $filename: git format-patch failed - $!\n";
1270 open($FILE, '-|', "diff -u /dev/null $filename") ||
1271 die "$P: $filename: diff failed - $!\n";
1272 } elsif ($filename eq '-') {
1273 open($FILE, '<&STDIN');
1275 open($FILE, '<', "$filename") ||
1276 die "$P: $filename: open failed - $!\n";
1278 if ($filename eq '-') {
1279 $vname = 'Your patch';
1281 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1287 push(@rawlines, $_);
1288 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1292 if ($#ARGV > 0 && $quiet == 0) {
1293 print '-' x length($vname) . "\n";
1295 print '-' x length($vname) . "\n";
1298 if (!process($filename)) {
1304 @fixed_inserted = ();
1305 @fixed_deleted = ();
1307 @modifierListFile = ();
1310 $file = $oldfile if ($is_git_file);
1314 hash_show_words(\%use_type, "Used");
1315 hash_show_words(\%ignore_type, "Ignored");
1317 if (!$perl_version_ok) {
1320 NOTE: perl $^V is not modern enough to detect all possible issues.
1321 An upgrade to at least perl $minimum_perl_version is suggested.
1327 NOTE: If any of the errors are false positives, please report
1328 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1335 sub top_of_kernel_tree {
1339 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1340 "README", "Documentation", "arch", "include", "drivers",
1341 "fs", "init", "ipc", "kernel", "lib", "scripts",
1344 foreach my $check (@tree_check) {
1345 if (! -e $root . '/' . $check) {
1353 my ($formatted_email) = @_;
1357 my $name_comment = "";
1361 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1364 $comment = $3 if defined $3;
1365 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1367 $comment = $2 if defined $2;
1368 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1370 $comment = $2 if defined $2;
1371 $formatted_email =~ s/\Q$address\E.*$//;
1372 $name = $formatted_email;
1373 $name = trim($name);
1374 $name =~ s/^\"|\"$//g;
1375 # If there's a name left after stripping spaces and
1376 # leading quotes, and the address doesn't have both
1377 # leading and trailing angle brackets, the address
1379 # "joe smith joe@smith.com" bad
1380 # "joe smith <joe@smith.com" bad
1381 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1388 # Extract comments from names excluding quoted parts
1389 # "John D. (Doe)" - Do not extract
1390 if ($name =~ s/\"(.+)\"//) {
1393 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1394 $name_comment .= trim($1);
1396 $name =~ s/^[ \"]+|[ \"]+$//g;
1397 $name = trim("$quoted $name");
1399 $address = trim($address);
1400 $address =~ s/^\<|\>$//g;
1401 $comment = trim($comment);
1403 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1404 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1405 $name = "\"$name\"";
1408 return ($name, $name_comment, $address, $comment);
1412 my ($name, $name_comment, $address, $comment) = @_;
1414 my $formatted_email;
1416 $name =~ s/^[ \"]+|[ \"]+$//g;
1417 $address = trim($address);
1418 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1420 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1421 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1422 $name = "\"$name\"";
1425 $name_comment = trim($name_comment);
1426 $name_comment = " $name_comment" if ($name_comment ne "");
1427 $comment = trim($comment);
1428 $comment = " $comment" if ($comment ne "");
1430 if ("$name" eq "") {
1431 $formatted_email = "$address";
1433 $formatted_email = "$name$name_comment <$address>";
1435 $formatted_email .= "$comment";
1436 return $formatted_email;
1439 sub reformat_email {
1442 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1443 return format_email($email_name, $name_comment, $email_address, $comment);
1446 sub same_email_addresses {
1447 my ($email1, $email2) = @_;
1449 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1450 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1452 return $email1_name eq $email2_name &&
1453 $email1_address eq $email2_address &&
1454 $name1_comment eq $name2_comment &&
1455 $comment1 eq $comment2;
1461 foreach my $path (split(/:/, $ENV{PATH})) {
1462 if (-e "$path/$bin") {
1463 return "$path/$bin";
1473 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1474 if (-e "$path/$conf") {
1475 return "$path/$conf";
1487 for my $c (split(//, $str)) {
1491 for (; ($n % $tabsize) != 0; $n++) {
1503 (my $res = shift) =~ tr/\t/ /c;
1510 # Drop the diff line leader and expand tabs
1512 $line = expand_tabs($line);
1514 # Pick the indent from the front of the line.
1515 my ($white) = ($line =~ /^(\s*)/);
1517 return (length($line), length($white));
1520 my $sanitise_quote = '';
1522 sub sanitise_line_reset {
1523 my ($in_comment) = @_;
1526 $sanitise_quote = '*/';
1528 $sanitise_quote = '';
1541 # Always copy over the diff marker.
1542 $res = substr($line, 0, 1);
1544 for ($off = 1; $off < length($line); $off++) {
1545 $c = substr($line, $off, 1);
1547 # Comments we are whacking completely including the begin
1548 # and end, all to $;.
1549 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1550 $sanitise_quote = '*/';
1552 substr($res, $off, 2, "$;$;");
1556 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1557 $sanitise_quote = '';
1558 substr($res, $off, 2, "$;$;");
1562 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1563 $sanitise_quote = '//';
1565 substr($res, $off, 2, $sanitise_quote);
1570 # A \ in a string means ignore the next character.
1571 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1573 substr($res, $off, 2, 'XX');
1578 if ($c eq "'" || $c eq '"') {
1579 if ($sanitise_quote eq '') {
1580 $sanitise_quote = $c;
1582 substr($res, $off, 1, $c);
1584 } elsif ($sanitise_quote eq $c) {
1585 $sanitise_quote = '';
1589 #print "c<$c> SQ<$sanitise_quote>\n";
1590 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1591 substr($res, $off, 1, $;);
1592 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1593 substr($res, $off, 1, $;);
1594 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1595 substr($res, $off, 1, 'X');
1597 substr($res, $off, 1, $c);
1601 if ($sanitise_quote eq '//') {
1602 $sanitise_quote = '';
1605 # The pathname on a #include may be surrounded by '<' and '>'.
1606 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1607 my $clean = 'X' x length($1);
1608 $res =~ s@\<.*\>@<$clean>@;
1610 # The whole of a #error is a string.
1611 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1612 my $clean = 'X' x length($1);
1613 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1616 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1618 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1624 sub get_quoted_string {
1625 my ($line, $rawline) = @_;
1627 return "" if (!defined($line) || !defined($rawline));
1628 return "" if ($line !~ m/($String)/g);
1629 return substr($rawline, $-[0], $+[0] - $-[0]);
1632 sub ctx_statement_block {
1633 my ($linenr, $remain, $off) = @_;
1634 my $line = $linenr - 1;
1637 my $coff = $off - 1;
1651 @stack = (['', 0]) if ($#stack == -1);
1653 #warn "CSB: blk<$blk> remain<$remain>\n";
1654 # If we are about to drop off the end, pull in more
1657 for (; $remain > 0; $line++) {
1658 last if (!defined $lines[$line]);
1659 next if ($lines[$line] =~ /^-/);
1662 $blk .= $lines[$line] . "\n";
1663 $len = length($blk);
1667 # Bail if there is no further context.
1668 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1672 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1678 $c = substr($blk, $off, 1);
1679 $remainder = substr($blk, $off);
1681 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1683 # Handle nested #if/#else.
1684 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1685 push(@stack, [ $type, $level ]);
1686 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1687 ($type, $level) = @{$stack[$#stack - 1]};
1688 } elsif ($remainder =~ /^#\s*endif\b/) {
1689 ($type, $level) = @{pop(@stack)};
1692 # Statement ends at the ';' or a close '}' at the
1694 if ($level == 0 && $c eq ';') {
1698 # An else is really a conditional as long as its not else if
1699 if ($level == 0 && $coff_set == 0 &&
1700 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1701 $remainder =~ /^(else)(?:\s|{)/ &&
1702 $remainder !~ /^else\s+if\b/) {
1703 $coff = $off + length($1) - 1;
1705 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1706 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1709 if (($type eq '' || $type eq '(') && $c eq '(') {
1713 if ($type eq '(' && $c eq ')') {
1715 $type = ($level != 0)? '(' : '';
1717 if ($level == 0 && $coff < $soff) {
1720 #warn "CSB: mark coff<$coff>\n";
1723 if (($type eq '' || $type eq '{') && $c eq '{') {
1727 if ($type eq '{' && $c eq '}') {
1729 $type = ($level != 0)? '{' : '';
1732 if (substr($blk, $off + 1, 1) eq ';') {
1738 # Preprocessor commands end at the newline unless escaped.
1739 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1747 # We are truly at the end, so shuffle to the next line.
1754 my $statement = substr($blk, $soff, $off - $soff + 1);
1755 my $condition = substr($blk, $soff, $coff - $soff + 1);
1757 #warn "STATEMENT<$statement>\n";
1758 #warn "CONDITION<$condition>\n";
1760 #print "coff<$coff> soff<$off> loff<$loff>\n";
1762 return ($statement, $condition,
1763 $line, $remain + 1, $off - $loff + 1, $level);
1766 sub statement_lines {
1769 # Strip the diff line prefixes and rip blank lines at start and end.
1770 $stmt =~ s/(^|\n)./$1/g;
1774 my @stmt_lines = ($stmt =~ /\n/g);
1776 return $#stmt_lines + 2;
1779 sub statement_rawlines {
1782 my @stmt_lines = ($stmt =~ /\n/g);
1784 return $#stmt_lines + 2;
1787 sub statement_block_size {
1790 $stmt =~ s/(^|\n)./$1/g;
1796 my @stmt_lines = ($stmt =~ /\n/g);
1797 my @stmt_statements = ($stmt =~ /;/g);
1799 my $stmt_lines = $#stmt_lines + 2;
1800 my $stmt_statements = $#stmt_statements + 1;
1802 if ($stmt_lines > $stmt_statements) {
1805 return $stmt_statements;
1809 sub ctx_statement_full {
1810 my ($linenr, $remain, $off) = @_;
1811 my ($statement, $condition, $level);
1815 # Grab the first conditional/block pair.
1816 ($statement, $condition, $linenr, $remain, $off, $level) =
1817 ctx_statement_block($linenr, $remain, $off);
1818 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1819 push(@chunks, [ $condition, $statement ]);
1820 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1821 return ($level, $linenr, @chunks);
1824 # Pull in the following conditional/block pairs and see if they
1825 # could continue the statement.
1827 ($statement, $condition, $linenr, $remain, $off, $level) =
1828 ctx_statement_block($linenr, $remain, $off);
1829 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1830 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1832 push(@chunks, [ $condition, $statement ]);
1835 return ($level, $linenr, @chunks);
1839 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1841 my $start = $linenr - 1;
1848 my @stack = ($level);
1849 for ($line = $start; $remain > 0; $line++) {
1850 next if ($rawlines[$line] =~ /^-/);
1853 $blk .= $rawlines[$line];
1855 # Handle nested #if/#else.
1856 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1857 push(@stack, $level);
1858 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1859 $level = $stack[$#stack - 1];
1860 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1861 $level = pop(@stack);
1864 foreach my $c (split(//, $lines[$line])) {
1865 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1871 if ($c eq $close && $level > 0) {
1873 last if ($level == 0);
1874 } elsif ($c eq $open) {
1879 if (!$outer || $level <= 1) {
1880 push(@res, $rawlines[$line]);
1883 last if ($level == 0);
1886 return ($level, @res);
1888 sub ctx_block_outer {
1889 my ($linenr, $remain) = @_;
1891 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1895 my ($linenr, $remain) = @_;
1897 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1901 my ($linenr, $remain, $off) = @_;
1903 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1906 sub ctx_block_level {
1907 my ($linenr, $remain) = @_;
1909 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1911 sub ctx_statement_level {
1912 my ($linenr, $remain, $off) = @_;
1914 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1917 sub ctx_locate_comment {
1918 my ($first_line, $end_line) = @_;
1920 # If c99 comment on the current line, or the line before or after
1921 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1922 return $current_comment if (defined $current_comment);
1923 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1924 return $current_comment if (defined $current_comment);
1925 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1926 return $current_comment if (defined $current_comment);
1928 # Catch a comment on the end of the line itself.
1929 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1930 return $current_comment if (defined $current_comment);
1932 # Look through the context and try and figure out if there is a
1935 $current_comment = '';
1936 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1937 my $line = $rawlines[$linenr - 1];
1939 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1942 if ($line =~ m@/\*@) {
1945 if (!$in_comment && $current_comment ne '') {
1946 $current_comment = '';
1948 $current_comment .= $line . "\n" if ($in_comment);
1949 if ($line =~ m@\*/@) {
1954 chomp($current_comment);
1955 return($current_comment);
1957 sub ctx_has_comment {
1958 my ($first_line, $end_line) = @_;
1959 my $cmt = ctx_locate_comment($first_line, $end_line);
1961 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1962 ##print "CMMT: $cmt\n";
1964 return ($cmt ne '');
1968 my ($linenr, $cnt) = @_;
1970 my $offset = $linenr - 1;
1975 $line = $rawlines[$offset++];
1976 next if (defined($line) && $line =~ /^-/);
1984 my ($linenr, $lc) = @_;
1986 my $stat_real = raw_line($linenr, 0);
1987 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1988 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1995 my ($linenr, $cnt, $here) = @_;
1997 my $herectx = $here . "\n";
1998 for (my $n = 0; $n < $cnt; $n++) {
1999 $herectx .= raw_line($linenr, $n) . "\n";
2010 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2013 $coded = sprintf("^%c", unpack('C', $2) + 64);
2022 my $av_preprocessor = 0;
2027 sub annotate_reset {
2028 $av_preprocessor = 0;
2030 @av_paren_type = ('E');
2031 $av_pend_colon = 'O';
2034 sub annotate_values {
2035 my ($stream, $type) = @_;
2038 my $var = '_' x length($stream);
2041 print "$stream\n" if ($dbg_values > 1);
2043 while (length($cur)) {
2044 @av_paren_type = ('E') if ($#av_paren_type < 0);
2045 print " <" . join('', @av_paren_type) .
2046 "> <$type> <$av_pending>" if ($dbg_values > 1);
2047 if ($cur =~ /^(\s+)/o) {
2048 print "WS($1)\n" if ($dbg_values > 1);
2049 if ($1 =~ /\n/ && $av_preprocessor) {
2050 $type = pop(@av_paren_type);
2051 $av_preprocessor = 0;
2054 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2055 print "CAST($1)\n" if ($dbg_values > 1);
2056 push(@av_paren_type, $type);
2059 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2060 print "DECLARE($1)\n" if ($dbg_values > 1);
2063 } elsif ($cur =~ /^($Modifier)\s*/) {
2064 print "MODIFIER($1)\n" if ($dbg_values > 1);
2067 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2068 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2069 $av_preprocessor = 1;
2070 push(@av_paren_type, $type);
2076 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2077 print "UNDEF($1)\n" if ($dbg_values > 1);
2078 $av_preprocessor = 1;
2079 push(@av_paren_type, $type);
2081 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2082 print "PRE_START($1)\n" if ($dbg_values > 1);
2083 $av_preprocessor = 1;
2085 push(@av_paren_type, $type);
2086 push(@av_paren_type, $type);
2089 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2090 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2091 $av_preprocessor = 1;
2093 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2097 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2098 print "PRE_END($1)\n" if ($dbg_values > 1);
2100 $av_preprocessor = 1;
2102 # Assume all arms of the conditional end as this
2103 # one does, and continue as if the #endif was not here.
2104 pop(@av_paren_type);
2105 push(@av_paren_type, $type);
2108 } elsif ($cur =~ /^(\\\n)/o) {
2109 print "PRECONT($1)\n" if ($dbg_values > 1);
2111 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2112 print "ATTR($1)\n" if ($dbg_values > 1);
2113 $av_pending = $type;
2116 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2117 print "SIZEOF($1)\n" if ($dbg_values > 1);
2123 } elsif ($cur =~ /^(if|while|for)\b/o) {
2124 print "COND($1)\n" if ($dbg_values > 1);
2128 } elsif ($cur =~/^(case)/o) {
2129 print "CASE($1)\n" if ($dbg_values > 1);
2130 $av_pend_colon = 'C';
2133 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2134 print "KEYWORD($1)\n" if ($dbg_values > 1);
2137 } elsif ($cur =~ /^(\()/o) {
2138 print "PAREN('$1')\n" if ($dbg_values > 1);
2139 push(@av_paren_type, $av_pending);
2143 } elsif ($cur =~ /^(\))/o) {
2144 my $new_type = pop(@av_paren_type);
2145 if ($new_type ne '_') {
2147 print "PAREN('$1') -> $type\n"
2148 if ($dbg_values > 1);
2150 print "PAREN('$1')\n" if ($dbg_values > 1);
2153 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2154 print "FUNC($1)\n" if ($dbg_values > 1);
2158 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2159 if (defined $2 && $type eq 'C' || $type eq 'T') {
2160 $av_pend_colon = 'B';
2161 } elsif ($type eq 'E') {
2162 $av_pend_colon = 'L';
2164 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2167 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2168 print "IDENT($1)\n" if ($dbg_values > 1);
2171 } elsif ($cur =~ /^($Assignment)/o) {
2172 print "ASSIGN($1)\n" if ($dbg_values > 1);
2175 } elsif ($cur =~/^(;|{|})/) {
2176 print "END($1)\n" if ($dbg_values > 1);
2178 $av_pend_colon = 'O';
2180 } elsif ($cur =~/^(,)/) {
2181 print "COMMA($1)\n" if ($dbg_values > 1);
2184 } elsif ($cur =~ /^(\?)/o) {
2185 print "QUESTION($1)\n" if ($dbg_values > 1);
2188 } elsif ($cur =~ /^(:)/o) {
2189 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2191 substr($var, length($res), 1, $av_pend_colon);
2192 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2197 $av_pend_colon = 'O';
2199 } elsif ($cur =~ /^(\[)/o) {
2200 print "CLOSE($1)\n" if ($dbg_values > 1);
2203 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2206 print "OPV($1)\n" if ($dbg_values > 1);
2213 substr($var, length($res), 1, $variant);
2216 } elsif ($cur =~ /^($Operators)/o) {
2217 print "OP($1)\n" if ($dbg_values > 1);
2218 if ($1 ne '++' && $1 ne '--') {
2222 } elsif ($cur =~ /(^.)/o) {
2223 print "C($1)\n" if ($dbg_values > 1);
2226 $cur = substr($cur, length($1));
2227 $res .= $type x length($1);
2231 return ($res, $var);
2235 my ($possible, $line) = @_;
2236 my $notPermitted = qr{(?:
2253 ^(?:typedef|struct|enum)\b
2255 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2256 if ($possible !~ $notPermitted) {
2257 # Check for modifiers.
2258 $possible =~ s/\s*$Storage\s*//g;
2259 $possible =~ s/\s*$Sparse\s*//g;
2260 if ($possible =~ /^\s*$/) {
2262 } elsif ($possible =~ /\s/) {
2263 $possible =~ s/\s*$Type\s*//g;
2264 for my $modifier (split(' ', $possible)) {
2265 if ($modifier !~ $notPermitted) {
2266 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2267 push(@modifierListFile, $modifier);
2272 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2273 push(@typeListFile, $possible);
2277 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2286 $type =~ tr/[a-z]/[A-Z]/;
2288 return defined $use_type{$type} if (scalar keys %use_type > 0);
2290 return !defined $ignore_type{$type};
2294 my ($level, $type, $msg) = @_;
2296 if (!show_type($type) ||
2297 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2302 if ($level eq 'ERROR') {
2304 } elsif ($level eq 'WARNING') {
2310 $output .= $prefix . $level . ':';
2312 $output .= BLUE if ($color);
2313 $output .= "$type:";
2315 $output .= RESET if ($color);
2316 $output .= ' ' . $msg . "\n";
2319 my @lines = split("\n", $output, -1);
2320 splice(@lines, 1, 1);
2321 $output = join("\n", @lines);
2325 $output = (split('\n', $output))[0] . "\n";
2328 if ($verbose && exists($verbose_messages{$type}) &&
2329 !exists($verbose_emitted{$type})) {
2330 $output .= $verbose_messages{$type} . "\n\n";
2331 $verbose_emitted{$type} = 1;
2334 push(our @report, $output);
2343 sub fixup_current_range {
2344 my ($lineRef, $offset, $length) = @_;
2346 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2349 my $no = $o + $offset;
2350 my $nl = $l + $length;
2351 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2355 sub fix_inserted_deleted_lines {
2356 my ($linesRef, $insertedRef, $deletedRef) = @_;
2358 my $range_last_linenr = 0;
2359 my $delta_offset = 0;
2364 my $next_insert = 0;
2365 my $next_delete = 0;
2369 my $inserted = @{$insertedRef}[$next_insert++];
2370 my $deleted = @{$deletedRef}[$next_delete++];
2372 foreach my $old_line (@{$linesRef}) {
2374 my $line = $old_line; #don't modify the array
2375 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2377 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2378 $range_last_linenr = $new_linenr;
2379 fixup_current_range(\$line, $delta_offset, 0);
2382 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2383 $deleted = @{$deletedRef}[$next_delete++];
2385 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2388 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2389 push(@lines, ${$inserted}{'LINE'});
2390 $inserted = @{$insertedRef}[$next_insert++];
2392 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2396 push(@lines, $line);
2406 sub fix_insert_line {
2407 my ($linenr, $line) = @_;
2413 push(@fixed_inserted, $inserted);
2416 sub fix_delete_line {
2417 my ($linenr, $line) = @_;
2424 push(@fixed_deleted, $deleted);
2428 my ($type, $msg) = @_;
2430 if (report("ERROR", $type, $msg)) {
2438 my ($type, $msg) = @_;
2440 if (report("WARNING", $type, $msg)) {
2448 my ($type, $msg) = @_;
2450 if ($check && report("CHECK", $type, $msg)) {
2458 sub check_absolute_file {
2459 my ($absolute, $herecurr) = @_;
2460 my $file = $absolute;
2462 ##print "absolute<$absolute>\n";
2464 # See if any suffix of this path is a path within the tree.
2465 while ($file =~ s@^[^/]*/@@) {
2466 if (-f "$root/$file") {
2467 ##print "file<$file>\n";
2475 # It is, so see if the prefix is acceptable.
2476 my $prefix = $absolute;
2477 substr($prefix, -length($file)) = '';
2479 ##print "prefix<$prefix>\n";
2480 if ($prefix ne ".../") {
2481 WARN("USE_RELATIVE_PATH",
2482 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2489 $string =~ s/^\s+|\s+$//g;
2497 $string =~ s/^\s+//;
2505 $string =~ s/\s+$//;
2510 sub string_find_replace {
2511 my ($string, $find, $replace) = @_;
2513 $string =~ s/$find/$replace/g;
2521 my $source_indent = $tabsize;
2522 my $max_spaces_before_tab = $source_indent - 1;
2523 my $spaces_to_tab = " " x $source_indent;
2525 #convert leading spaces to tabs
2526 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2527 #Remove spaces before a tab
2528 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2533 sub pos_last_openparen {
2538 my $opens = $line =~ tr/\(/\(/;
2539 my $closes = $line =~ tr/\)/\)/;
2541 my $last_openparen = 0;
2543 if (($opens == 0) || ($closes >= $opens)) {
2547 my $len = length($line);
2549 for ($pos = 0; $pos < $len; $pos++) {
2550 my $string = substr($line, $pos);
2551 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2552 $pos += length($1) - 1;
2553 } elsif (substr($line, $pos, 1) eq '(') {
2554 $last_openparen = $pos;
2555 } elsif (index($string, '(') == -1) {
2560 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2563 sub get_raw_comment {
2564 my ($line, $rawline) = @_;
2567 for my $i (0 .. (length($line) - 1)) {
2568 if (substr($line, $i, 1) eq "$;") {
2569 $comment .= substr($rawline, $i, 1);
2576 sub exclude_global_initialisers {
2577 my ($realfile) = @_;
2579 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2580 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2581 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2582 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2586 my $filename = shift;
2592 my $stashrawline="";
2602 my $authorsignoff = 0;
2603 my $author_sob = '';
2605 my $is_binding_patch = -1;
2606 my $in_header_lines = $file ? 0 : 1;
2607 my $in_commit_log = 0; #Scanning lines before patch
2608 my $has_patch_separator = 0; #Found a --- line
2609 my $has_commit_log = 0; #Encountered lines before patch
2610 my $commit_log_lines = 0; #Number of commit log lines
2611 my $commit_log_possible_stack_dump = 0;
2612 my $commit_log_long_line = 0;
2613 my $commit_log_has_diff = 0;
2614 my $reported_maintainer_file = 0;
2615 my $non_utf8_charset = 0;
2617 my $last_git_commit_id_linenr = -1;
2619 my $last_blank_line = 0;
2620 my $last_coalesced_string_linenr = -1;
2628 # Trace the real file/line as we go.
2633 my $context_function; #undef'd unless there's a known function
2635 my $comment_edge = 0;
2639 my $prev_values = 'E';
2642 my %suppress_ifbraces;
2643 my %suppress_whiletrailers;
2644 my %suppress_export;
2645 my $suppress_statement = 0;
2647 my %signatures = ();
2649 # Pre-scan the patch sanitizing the lines.
2650 # Pre-scan the patch looking for any __setup documentation.
2652 my @setup_docs = ();
2655 my $camelcase_file_seeded = 0;
2657 my $checklicenseline = 1;
2659 sanitise_line_reset();
2661 foreach my $rawline (@rawlines) {
2665 push(@fixed, $rawline) if ($fix);
2667 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2669 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2674 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2683 # Guestimate if this is a continuing comment. Run
2684 # the context looking for a comment "edge". If this
2685 # edge is a close comment then we must be in a comment
2689 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2690 next if (defined $rawlines[$ln - 1] &&
2691 $rawlines[$ln - 1] =~ /^-/);
2693 #print "RAW<$rawlines[$ln - 1]>\n";
2694 last if (!defined $rawlines[$ln - 1]);
2695 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2696 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2701 if (defined $edge && $edge eq '*/') {
2705 # Guestimate if this is a continuing comment. If this
2706 # is the start of a diff block and this line starts
2707 # ' *' then it is very likely a comment.
2708 if (!defined $edge &&
2709 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2714 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2715 sanitise_line_reset($in_comment);
2717 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2718 # Standardise the strings and chars within the input to
2719 # simplify matching -- only bother with positive lines.
2720 $line = sanitise_line($rawline);
2722 push(@lines, $line);
2725 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2730 #print "==>$rawline\n";
2731 #print "-->$line\n";
2733 if ($setup_docs && $line =~ /^\+/) {
2734 push(@setup_docs, $line);
2743 foreach my $line (@lines) {
2746 my $sline = $line; #copy of $line
2747 $sline =~ s/$;/ /g; #with comments as spaces
2749 my $rawline = $rawlines[$linenr - 1];
2750 my $raw_comment = get_raw_comment($line, $rawline);
2752 # check if it's a mode change, rename or start of a patch
2753 if (!$in_commit_log &&
2754 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2755 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2756 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2760 #extract the line range in the file after the patch is applied
2761 if (!$in_commit_log &&
2762 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2765 $first_line = $linenr + 1;
2775 %suppress_ifbraces = ();
2776 %suppress_whiletrailers = ();
2777 %suppress_export = ();
2778 $suppress_statement = 0;
2779 if ($context =~ /\b(\w+)\s*\(/) {
2780 $context_function = $1;
2782 undef $context_function;
2786 # track the line number as we move through the hunk, note that
2787 # new versions of GNU diff omit the leading space on completely
2788 # blank context lines so we need to count that too.
2789 } elsif ($line =~ /^( |\+|$)/) {
2791 $realcnt-- if ($realcnt != 0);
2793 # Measure the line length and indent.
2794 ($length, $indent) = line_stats($rawline);
2796 # Track the previous line.
2797 ($prevline, $stashline) = ($stashline, $line);
2798 ($previndent, $stashindent) = ($stashindent, $indent);
2799 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2801 #warn "line<$line>\n";
2803 } elsif ($realcnt == 1) {
2807 my $hunk_line = ($realcnt != 0);
2809 $here = "#$linenr: " if (!$file);
2810 $here = "#$realline: " if ($file);
2813 # extract the filename as it passes
2814 if ($line =~ /^diff --git.*?(\S+)$/) {
2816 $realfile =~ s@^([^/]*)/@@ if (!$file);
2819 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2821 $realfile =~ s@^([^/]*)/@@ if (!$file);
2825 if (!$file && $tree && $p1_prefix ne '' &&
2826 -e "$root/$p1_prefix") {
2827 WARN("PATCH_PREFIX",
2828 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2831 if ($realfile =~ m@^include/asm/@) {
2832 ERROR("MODIFIED_INCLUDE_ASM",
2833 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2838 #make up the handle for any error we report on this line
2840 $prefix = "$realfile:$realline: "
2843 $prefix = "$filename:$realline: ";
2845 $prefix = "$filename:$linenr: ";
2850 if (is_maintained_obsolete($realfile)) {
2852 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2854 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2857 $check = $check_orig;
2859 $checklicenseline = 1;
2861 if ($realfile !~ /^MAINTAINERS/) {
2862 my $last_binding_patch = $is_binding_patch;
2864 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2866 if (($last_binding_patch != -1) &&
2867 ($last_binding_patch ^ $is_binding_patch)) {
2868 WARN("DT_SPLIT_BINDING_PATCH",
2869 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2876 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2878 my $hereline = "$here\n$rawline\n";
2879 my $herecurr = "$here\n$rawline\n";
2880 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2882 $cnt_lines++ if ($realcnt != 0);
2884 # Verify the existence of a commit log if appropriate
2885 # 2 is used because a $signature is counted in $commit_log_lines
2886 if ($in_commit_log) {
2887 if ($line !~ /^\s*$/) {
2888 $commit_log_lines++; #could be a $signature
2890 } elsif ($has_commit_log && $commit_log_lines < 2) {
2891 WARN("COMMIT_MESSAGE",
2892 "Missing commit description - Add an appropriate one\n");
2893 $commit_log_lines = 2; #warn only once
2896 # Check if the commit log has what seems like a diff which can confuse patch
2897 if ($in_commit_log && !$commit_log_has_diff &&
2898 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2899 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2900 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2901 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2902 ERROR("DIFF_IN_COMMIT_MSG",
2903 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2904 $commit_log_has_diff = 1;
2907 # Check for incorrect file permissions
2908 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2909 my $permhere = $here . "FILE: $realfile\n";
2910 if ($realfile !~ m@scripts/@ &&
2911 $realfile !~ /\.(py|pl|awk|sh)$/) {
2912 ERROR("EXECUTE_PERMISSIONS",
2913 "do not set execute permissions for source files\n" . $permhere);
2917 # Check the patch for a From:
2918 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2920 my $curline = $linenr;
2921 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2924 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2926 $author = reformat_email($author);
2929 # Check the patch for a signoff:
2930 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2933 if ($author ne '' && $authorsignoff != 1) {
2934 if (same_email_addresses($1, $author)) {
2938 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2939 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2941 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2944 } elsif (lc $email_address eq lc $author_address) {
2947 } elsif ($email_name eq $author_name) {
2951 my $address1 = $email_address;
2952 my $address2 = $author_address;
2954 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2957 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2960 if ($address1 eq $address2) {
2968 # Check for patch separator
2969 if ($line =~ /^---$/) {
2970 $has_patch_separator = 1;
2974 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2975 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2976 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2977 $reported_maintainer_file = 1;
2980 # Check signature styles
2981 if (!$in_header_lines &&
2982 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2983 my $space_before = $1;
2985 my $space_after = $3;
2987 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2989 if ($sign_off !~ /$signature_tags/) {
2990 my $suggested_signature = find_standard_signature($sign_off);
2991 if ($suggested_signature eq "") {
2992 WARN("BAD_SIGN_OFF",
2993 "Non-standard signature: $sign_off\n" . $herecurr);
2995 if (WARN("BAD_SIGN_OFF",
2996 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
2998 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3002 if (defined $space_before && $space_before ne "") {
3003 if (WARN("BAD_SIGN_OFF",
3004 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3006 $fixed[$fixlinenr] =
3007 "$ucfirst_sign_off $email";
3010 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3011 if (WARN("BAD_SIGN_OFF",
3012 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3014 $fixed[$fixlinenr] =
3015 "$ucfirst_sign_off $email";
3019 if (!defined $space_after || $space_after ne " ") {
3020 if (WARN("BAD_SIGN_OFF",
3021 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3023 $fixed[$fixlinenr] =
3024 "$ucfirst_sign_off $email";
3028 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3029 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3030 if ($suggested_email eq "") {
3031 ERROR("BAD_SIGN_OFF",
3032 "Unrecognized email address: '$email'\n" . $herecurr);
3034 my $dequoted = $suggested_email;
3035 $dequoted =~ s/^"//;
3036 $dequoted =~ s/" </ </;
3037 # Don't force email to have quotes
3038 # Allow just an angle bracketed address
3039 if (!same_email_addresses($email, $suggested_email)) {
3040 if (WARN("BAD_SIGN_OFF",
3041 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3043 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3047 # Address part shouldn't have comments
3048 my $stripped_address = $email_address;
3049 $stripped_address =~ s/\([^\(\)]*\)//g;
3050 if ($email_address ne $stripped_address) {
3051 if (WARN("BAD_SIGN_OFF",
3052 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3054 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3058 # Only one name comment should be allowed
3059 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3060 if ($comment_count > 1) {
3061 WARN("BAD_SIGN_OFF",
3062 "Use a single name comment in email: '$email'\n" . $herecurr);
3066 # stable@vger.kernel.org or stable@kernel.org shouldn't
3067 # have an email name. In addition comments should strictly
3069 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3070 if (($comment ne "" && $comment !~ /^#.+/) ||
3071 ($email_name ne "")) {
3072 my $cur_name = $email_name;
3073 my $new_comment = $comment;
3074 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3076 # Remove brackets enclosing comment text
3077 # and # from start of comments to get comment text
3078 $new_comment =~ s/^\((.*)\)$/$1/;
3079 $new_comment =~ s/^\[(.*)\]$/$1/;
3080 $new_comment =~ s/^[\s\#]+|\s+$//g;
3082 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3083 $new_comment = " # $new_comment" if ($new_comment ne "");
3084 my $new_email = "$email_address$new_comment";
3086 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3087 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3089 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3092 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3093 my $new_comment = $comment;
3095 # Extract comment text from within brackets or
3096 # c89 style /*...*/ comments
3097 $new_comment =~ s/^\[(.*)\]$/$1/;
3098 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3100 $new_comment = trim($new_comment);
3101 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3102 $new_comment = "($new_comment)" if ($new_comment ne "");
3103 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3105 if (WARN("BAD_SIGN_OFF",
3106 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3108 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3113 # Check for duplicate signatures
3114 my $sig_nospace = $line;
3115 $sig_nospace =~ s/\s//g;
3116 $sig_nospace = lc($sig_nospace);
3117 if (defined $signatures{$sig_nospace}) {
3118 WARN("BAD_SIGN_OFF",
3119 "Duplicate signature\n" . $herecurr);
3121 $signatures{$sig_nospace} = 1;
3124 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3125 if ($sign_off =~ /^co-developed-by:$/i) {
3126 if ($email eq $author) {
3127 WARN("BAD_SIGN_OFF",
3128 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3130 if (!defined $lines[$linenr]) {
3131 WARN("BAD_SIGN_OFF",
3132 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3133 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3134 WARN("BAD_SIGN_OFF",
3135 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3136 } elsif ($1 ne $email) {
3137 WARN("BAD_SIGN_OFF",
3138 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3143 # Check email subject for common tools that don't need to be mentioned
3144 if ($in_header_lines &&
3145 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3146 WARN("EMAIL_SUBJECT",
3147 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3150 # Check for Gerrit Change-Ids not in any patch context
3151 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3152 if (ERROR("GERRIT_CHANGE_ID",
3153 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3155 fix_delete_line($fixlinenr, $rawline);
3159 # Check if the commit log is in a possible stack dump
3160 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3161 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3162 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3164 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3165 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3166 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3167 # stack dump address styles
3168 $commit_log_possible_stack_dump = 1;
3171 # Check for line lengths > 75 in commit log, warn once
3172 if ($in_commit_log && !$commit_log_long_line &&
3173 length($line) > 75 &&
3174 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3175 # file delta changes
3176 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3178 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3179 # A Fixes: or Link: line or signature tag line
3180 $commit_log_possible_stack_dump)) {
3181 WARN("COMMIT_LOG_LONG_LINE",
3182 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3183 $commit_log_long_line = 1;
3186 # Reset possible stack dump if a blank line is found
3187 if ($in_commit_log && $commit_log_possible_stack_dump &&
3189 $commit_log_possible_stack_dump = 0;
3192 # Check for lines starting with a #
3193 if ($in_commit_log && $line =~ /^#/) {
3194 if (WARN("COMMIT_COMMENT_SYMBOL",
3195 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3197 $fixed[$fixlinenr] =~ s/^/ /;
3201 # Check for git id commit length and improperly formed commit descriptions
3202 # A correctly formed commit description is:
3203 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3204 # with the commit subject '("' prefix and '")' suffix
3205 # This is a fairly compilicated block as it tests for what appears to be
3206 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3207 # possible SHA-1 matches.
3208 # A commit match can span multiple lines so this block attempts to find a
3209 # complete typical commit on a maximum of 3 lines
3210 if ($perl_version_ok &&
3211 $in_commit_log && !$commit_log_possible_stack_dump &&
3212 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3213 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3214 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3215 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3216 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3217 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3218 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3219 my $init_char = "c";
3220 my $orig_commit = "";
3225 my $id = '0123456789ab';
3226 my $orig_desc = "commit description";
3227 my $description = "";
3228 my $herectx = $herecurr;
3233 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3234 for (my $n = 0; $n < 2; $n++) {
3235 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3238 # Always strip leading/trailing parens then double quotes if existing
3239 $orig_desc = substr($orig_desc, 1, -1);
3240 if ($orig_desc =~ /^".*"$/) {
3241 $orig_desc = substr($orig_desc, 1, -1);
3246 last if ($#lines < $linenr + $n);
3247 $input .= " " . trim($rawlines[$linenr + $n]);
3248 $herectx .= "$rawlines[$linenr + $n]\n";
3250 $herectx = $herecurr if (!$has_parens);
3253 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3255 $orig_commit = lc($2);
3256 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3257 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3258 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3259 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3260 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3261 $orig_commit = lc($1);
3264 ($id, $description) = git_commit_info($orig_commit,
3268 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3269 $last_git_commit_id_linenr != $linenr - 1) {
3270 ERROR("GIT_COMMIT_ID",
3271 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3273 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3274 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3277 # Check for added, moved or deleted files
3278 if (!$reported_maintainer_file && !$in_commit_log &&
3279 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3280 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3281 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3282 (defined($1) || defined($2))))) {
3284 $reported_maintainer_file = 1;
3285 WARN("FILE_PATH_CHANGES",
3286 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3289 # Check for adding new DT bindings not in schema format
3290 if (!$in_commit_log &&
3291 ($line =~ /^new file mode\s*\d+\s*$/) &&
3292 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3293 WARN("DT_SCHEMA_BINDING_PATCH",
3294 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3297 # Check for wrappage within a valid hunk of the file
3298 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3299 ERROR("CORRUPTED_PATCH",
3300 "patch seems to be corrupt (line wrapped?)\n" .
3301 $herecurr) if (!$emitted_corrupt++);
3304 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3305 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3306 $rawline !~ m/^$UTF8*$/) {
3307 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3309 my $blank = copy_spacing($rawline);
3310 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3311 my $hereptr = "$hereline$ptr\n";
3314 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3317 # Check if it's the start of a commit log
3318 # (not a header line and we haven't seen the patch filename)
3319 if ($in_header_lines && $realfile =~ /^$/ &&
3320 !($rawline =~ /^\s+(?:\S|$)/ ||
3321 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3322 $in_header_lines = 0;
3324 $has_commit_log = 1;
3327 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3328 # declined it, i.e defined some charset where it is missing.
3329 if ($in_header_lines &&
3330 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3332 $non_utf8_charset = 1;
3335 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3336 $rawline =~ /$NON_ASCII_UTF8/) {
3337 WARN("UTF8_BEFORE_PATCH",
3338 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3341 # Check for absolute kernel paths in commit message
3342 if ($tree && $in_commit_log) {
3343 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3346 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3347 check_absolute_file($1, $herecurr)) {
3350 check_absolute_file($file, $herecurr);
3355 # Check for various typo / spelling mistakes
3356 if (defined($misspellings) &&
3357 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3358 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3360 my $blank = copy_spacing($rawline);
3361 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3362 my $hereptr = "$hereline$ptr\n";
3363 my $typo_fix = $spelling_fix{lc($typo)};
3364 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3365 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3366 my $msg_level = \&WARN;
3367 $msg_level = \&CHK if ($file);
3368 if (&{$msg_level}("TYPO_SPELLING",
3369 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3371 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3376 # check for invalid commit id
3377 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3380 ($id, $description) = git_commit_info($2, undef, undef);
3381 if (!defined($id)) {
3382 WARN("UNKNOWN_COMMIT_ID",
3383 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3387 # check for repeated words separated by a single space
3388 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3389 if (($rawline =~ /^\+/ || $in_commit_log) &&
3390 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3391 pos($rawline) = 1 if (!$in_commit_log);
3392 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3396 my $start_pos = $-[1];
3397 my $end_pos = $+[2];
3398 if ($first =~ /(?:struct|union|enum)/) {
3399 pos($rawline) += length($first) + length($second) + 1;
3403 next if (lc($first) ne lc($second));
3404 next if ($first eq 'long');
3406 # check for character before and after the word matches
3407 my $start_char = '';
3409 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3410 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3412 next if ($start_char =~ /^\S$/);
3413 next if (index(" \t.,;?!", $end_char) == -1);
3415 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3416 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3417 next if (!exists($allow_repeated_words{lc($first)}));
3420 if (WARN("REPEATED_WORD",
3421 "Possible repeated word: '$first'\n" . $herecurr) &&
3423 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3427 # if it's a repeated word on consecutive lines in a comment block
3428 if ($prevline =~ /$;+\s*$/ &&
3429 $prevrawline =~ /($word_pattern)\s*$/) {
3431 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3432 if (WARN("REPEATED_WORD",
3433 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3435 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3441 # ignore non-hunk lines and lines being removed
3442 next if (!$hunk_line || $line =~ /^-/);
3444 #trailing whitespace
3445 if ($line =~ /^\+.*\015/) {
3446 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3447 if (ERROR("DOS_LINE_ENDINGS",
3448 "DOS line endings\n" . $herevet) &&
3450 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3452 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3453 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3454 if (ERROR("TRAILING_WHITESPACE",
3455 "trailing whitespace\n" . $herevet) &&
3457 $fixed[$fixlinenr] =~ s/\s+$//;
3463 # Check for FSF mailing addresses.
3464 if ($rawline =~ /\bwrite to the Free/i ||
3465 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3466 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3467 $rawline =~ /\b51\s+Franklin\s+St/i) {
3468 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3469 my $msg_level = \&ERROR;
3470 $msg_level = \&CHK if ($file);
3471 &{$msg_level}("FSF_MAILING_ADDRESS",
3472 "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)
3475 # check for Kconfig help text having a real description
3476 # Only applies when adding the entry originally, after that we do not have
3477 # sufficient context to determine whether it is indeed long enough.
3478 if ($realfile =~ /Kconfig/ &&
3479 # 'choice' is usually the last thing on the line (though
3480 # Kconfig supports named choices), so use a word boundary
3481 # (\b) rather than a whitespace character (\s)
3482 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3486 my $help_length = 0;
3487 while (defined $lines[$ln]) {
3488 my $f = $lines[$ln++];
3490 next if ($f =~ /^-/);
3491 last if ($f !~ /^[\+ ]/); # !patch context
3493 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3497 if ($f =~ /^\+\s*help\s*$/) {
3502 $f =~ s/^.//; # strip patch context [+ ]
3503 $f =~ s/#.*//; # strip # directives
3504 $f =~ s/^\s+//; # strip leading blanks
3505 next if ($f =~ /^$/); # skip blank lines
3507 # At the end of this Kconfig block:
3508 # This only checks context lines in the patch
3509 # and so hopefully shouldn't trigger false
3510 # positives, even though some of these are
3511 # common words in help texts
3512 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3513 if|endif|menu|endmenu|source)\b/x) {
3516 $help_length++ if ($has_help);
3519 $help_length < $min_conf_desc_length) {
3520 my $stat_real = get_stat_real($linenr, $ln - 1);
3521 WARN("CONFIG_DESCRIPTION",
3522 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3526 # check MAINTAINERS entries
3527 if ($realfile =~ /^MAINTAINERS$/) {
3528 # check MAINTAINERS entries for the right form
3529 if ($rawline =~ /^\+[A-Z]:/ &&
3530 $rawline !~ /^\+[A-Z]:\t\S/) {
3531 if (WARN("MAINTAINERS_STYLE",
3532 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3534 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3537 # check MAINTAINERS entries for the right ordering too
3538 my $preferred_order = 'MRLSWQBCPTFXNK';
3539 if ($rawline =~ /^\+[A-Z]:/ &&
3540 $prevrawline =~ /^[\+ ][A-Z]:/) {
3541 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3544 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3547 my $curindex = index($preferred_order, $cur);
3548 my $previndex = index($preferred_order, $prev);
3549 if ($curindex < 0) {
3550 WARN("MAINTAINERS_STYLE",
3551 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3553 if ($previndex >= 0 && $curindex < $previndex) {
3554 WARN("MAINTAINERS_STYLE",
3555 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3556 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3557 ($prev eq 'X' && $cur eq 'X')) &&
3558 ($prevval cmp $curval) > 0) {
3559 WARN("MAINTAINERS_STYLE",
3560 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3566 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3567 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3570 'EXTRA_AFLAGS' => 'asflags-y',
3571 'EXTRA_CFLAGS' => 'ccflags-y',
3572 'EXTRA_CPPFLAGS' => 'cppflags-y',
3573 'EXTRA_LDFLAGS' => 'ldflags-y',
3576 WARN("DEPRECATED_VARIABLE",
3577 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3580 # check for DT compatible documentation
3581 if (defined $root &&
3582 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3583 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3585 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3587 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3588 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3590 foreach my $compat (@compats) {
3591 my $compat2 = $compat;
3592 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3593 my $compat3 = $compat;
3594 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3595 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3597 WARN("UNDOCUMENTED_DT_STRING",
3598 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3601 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3603 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3605 WARN("UNDOCUMENTED_DT_STRING",
3606 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3611 # check for using SPDX license tag at beginning of files
3612 if ($realline == $checklicenseline) {
3613 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3614 $checklicenseline = 2;
3615 } elsif ($rawline =~ /^\+/) {
3617 if ($realfile =~ /\.(h|s|S)$/) {
3619 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3621 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3623 } elsif ($realfile =~ /\.rst$/) {
3627 # check SPDX comment style for .[chsS] files
3628 if ($realfile =~ /\.[chsS]$/ &&
3629 $rawline =~ /SPDX-License-Identifier:/ &&
3630 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3631 WARN("SPDX_LICENSE_TAG",
3632 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3635 if ($comment !~ /^$/ &&
3636 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3637 WARN("SPDX_LICENSE_TAG",
3638 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3639 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3640 my $spdx_license = $1;
3641 if (!is_SPDX_License_valid($spdx_license)) {
3642 WARN("SPDX_LICENSE_TAG",
3643 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3645 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3646 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3647 my $msg_level = \&WARN;
3648 $msg_level = \&CHK if ($file);
3649 if (&{$msg_level}("SPDX_LICENSE_TAG",
3651 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3653 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3660 # check for embedded filenames
3661 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3662 WARN("EMBEDDED_FILENAME",
3663 "It's generally not useful to have the filename in the file\n" . $herecurr);
3666 # check we are in a valid source file if not then ignore this hunk
3667 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3669 # check for using SPDX-License-Identifier on the wrong line number
3670 if ($realline != $checklicenseline &&
3671 $rawline =~ /\bSPDX-License-Identifier:/ &&
3672 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3673 WARN("SPDX_LICENSE_TAG",
3674 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3677 # line length limit (with some exclusions)
3679 # There are a few types of lines that may extend beyond $max_line_length:
3680 # logging functions like pr_info that end in a string
3681 # lines with a single string
3682 # #defines that are a single string
3683 # lines with an RFC3986 like URL
3685 # There are 3 different line length message types:
3686 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3687 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3688 # LONG_LINE all other lines longer than $max_line_length
3690 # if LONG_LINE is ignored, the other 2 types are also ignored
3693 if ($line =~ /^\+/ && $length > $max_line_length) {
3694 my $msg_type = "LONG_LINE";
3696 # Check the allowed long line types first
3698 # logging functions that end in a string that starts
3699 # before $max_line_length
3700 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3701 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3704 # lines with only strings (w/ possible termination)
3705 # #defines with only strings
3706 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3707 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3710 # More special cases
3711 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3712 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3715 # URL ($rawline is used in case the URL is in a comment)
3716 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3719 # Otherwise set the alternate message types
3721 # a comment starts before $max_line_length
3722 } elsif ($line =~ /($;[\s$;]*)$/ &&
3723 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3724 $msg_type = "LONG_LINE_COMMENT"
3726 # a quoted string starts before $max_line_length
3727 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3728 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3729 $msg_type = "LONG_LINE_STRING"
3732 if ($msg_type ne "" &&
3733 (show_type("LONG_LINE") || show_type($msg_type))) {
3734 my $msg_level = \&WARN;
3735 $msg_level = \&CHK if ($file);
3736 &{$msg_level}($msg_type,
3737 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3741 # check for adding lines without a newline.
3742 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3743 if (WARN("MISSING_EOF_NEWLINE",
3744 "adding a line without newline at end of file\n" . $herecurr) &&
3746 fix_delete_line($fixlinenr+1, "No newline at end of file");
3750 # check for .L prefix local symbols in .S files
3751 if ($realfile =~ /\.S$/ &&
3752 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3753 WARN("AVOID_L_PREFIX",
3754 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/asm-annotations.rst\n" . $herecurr);
3757 # check we are in a valid source file C or perl if not then ignore this hunk
3758 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3760 # at the beginning of a line any tabs must come first and anything
3761 # more than $tabsize must use tabs.
3762 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3763 $rawline =~ /^\+\s* \s*/) {
3764 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3766 if (ERROR("CODE_INDENT",
3767 "code indent should use tabs where possible\n" . $herevet) &&
3769 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3773 # check for space before tabs.
3774 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3775 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3776 if (WARN("SPACE_BEFORE_TAB",
3777 "please, no space before tabs\n" . $herevet) &&
3779 while ($fixed[$fixlinenr] =~
3780 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3781 while ($fixed[$fixlinenr] =~
3782 s/(^\+.*) +\t/$1\t/) {}
3786 # check for assignments on the start of a line
3787 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3789 if (CHK("ASSIGNMENT_CONTINUATIONS",
3790 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3791 $fix && $prevrawline =~ /^\+/) {
3792 # add assignment operator to the previous line, remove from current line
3793 $fixed[$fixlinenr - 1] .= " $operator";
3794 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3798 # check for && or || at the start of a line
3799 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3801 if (CHK("LOGICAL_CONTINUATIONS",
3802 "Logical continuations should be on the previous line\n" . $hereprev) &&
3803 $fix && $prevrawline =~ /^\+/) {
3804 # insert logical operator at last non-comment, non-whitepsace char on previous line
3805 $prevline =~ /[\s$;]*$/;
3806 my $line_end = substr($prevrawline, $-[0]);
3807 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3808 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3812 # check indentation starts on a tab stop
3813 if ($perl_version_ok &&
3814 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3815 my $indent = length($1);
3816 if ($indent % $tabsize) {
3818 "Statements should start on a tabstop\n" . $herecurr) &&
3820 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3825 # check multi-line statement indentation matches previous line
3826 if ($perl_version_ok &&
3827 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3828 $prevline =~ /^\+(\t*)(.*)$/;
3832 my $pos = pos_last_openparen($rest);
3834 $line =~ /^(\+| )([ \t]*)/;
3837 my $goodtabindent = $oldindent .
3838 "\t" x ($pos / $tabsize) .
3839 " " x ($pos % $tabsize);
3840 my $goodspaceindent = $oldindent . " " x $pos;
3842 if ($newindent ne $goodtabindent &&
3843 $newindent ne $goodspaceindent) {
3845 if (CHK("PARENTHESIS_ALIGNMENT",
3846 "Alignment should match open parenthesis\n" . $hereprev) &&
3847 $fix && $line =~ /^\+/) {
3848 $fixed[$fixlinenr] =~
3849 s/^\+[ \t]*/\+$goodtabindent/;
3855 # check for space after cast like "(int) foo" or "(struct foo) bar"
3856 # avoid checking a few false positives:
3857 # "sizeof(<type>)" or "__alignof__(<type>)"
3858 # function pointer declarations like "(*foo)(int) = bar;"
3859 # structure definitions like "(struct foo) { 0 };"
3860 # multiline macros that define functions
3861 # known attributes or the __attribute__ keyword
3862 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3863 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3865 "No space is necessary after a cast\n" . $herecurr) &&
3867 $fixed[$fixlinenr] =~
3868 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3872 # Block comment styles
3873 # Networking with an initial /*
3874 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3875 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3876 $rawline =~ /^\+[ \t]*\*/ &&
3877 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3878 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3879 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3882 # Block comments use * on subsequent lines
3883 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3884 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3885 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3886 $rawline =~ /^\+/ && #line is new
3887 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3888 WARN("BLOCK_COMMENT_STYLE",
3889 "Block comments use * on subsequent lines\n" . $hereprev);
3892 # Block comments use */ on trailing lines
3893 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3894 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3895 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3896 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3897 WARN("BLOCK_COMMENT_STYLE",
3898 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3901 # Block comment * alignment
3902 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3903 $line =~ /^\+[ \t]*$;/ && #leading comment
3904 $rawline =~ /^\+[ \t]*\*/ && #leading *
3905 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3906 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3907 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3909 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3911 $oldindent = expand_tabs($1);
3913 $prevrawline =~ m@^\+(.*/?)\*@;
3914 $oldindent = expand_tabs($1);
3916 $rawline =~ m@^\+([ \t]*)\*@;
3918 $newindent = expand_tabs($newindent);
3919 if (length($oldindent) ne length($newindent)) {
3920 WARN("BLOCK_COMMENT_STYLE",
3921 "Block comments should align the * on each line\n" . $hereprev);
3925 # check for missing blank lines after struct/union declarations
3926 # with exceptions for various attributes and macros
3927 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3929 !($line =~ /^\+\s*$/ ||
3930 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
3931 $line =~ /^\+\s*MODULE_/i ||
3932 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3933 $line =~ /^\+[a-z_]*init/ ||
3934 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3935 $line =~ /^\+\s*DECLARE/ ||
3936 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3937 $line =~ /^\+\s*__setup/)) {
3938 if (CHK("LINE_SPACING",
3939 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3941 fix_insert_line($fixlinenr, "\+");
3945 # check for multiple consecutive blank lines
3946 if ($prevline =~ /^[\+ ]\s*$/ &&
3947 $line =~ /^\+\s*$/ &&
3948 $last_blank_line != ($linenr - 1)) {
3949 if (CHK("LINE_SPACING",
3950 "Please don't use multiple blank lines\n" . $hereprev) &&
3952 fix_delete_line($fixlinenr, $rawline);
3955 $last_blank_line = $linenr;
3958 # check for missing blank lines after declarations
3959 # (declarations must have the same indentation and not be at the start of line)
3960 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
3964 # remove $Attribute/$Sparse uses to simplify comparisons
3965 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3966 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
3967 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3968 # function pointer declarations
3969 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3970 # foo bar; where foo is some local typedef or #define
3971 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3972 # known declaration macros
3973 $pl =~ /^\+\s+$declaration_macros/) &&
3974 # for "else if" which can look like "$Ident $Ident"
3975 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
3976 # other possible extensions of declaration lines
3977 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3978 # not starting a section or a macro "\" extended line
3979 $pl =~ /(?:\{\s*|\\)$/) &&
3980 # looks like a declaration
3981 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3982 # function pointer declarations
3983 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3984 # foo bar; where foo is some local typedef or #define
3985 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3986 # known declaration macros
3987 $sl =~ /^\+\s+$declaration_macros/ ||
3988 # start of struct or union or enum
3989 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3990 # start or end of block or continuation of declaration
3991 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3992 # bitfield continuation
3993 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3994 # other possible extensions of declaration lines
3995 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
3996 if (WARN("LINE_SPACING",
3997 "Missing a blank line after declarations\n" . $hereprev) &&
3999 fix_insert_line($fixlinenr, "\+");
4004 # check for spaces at the beginning of a line.
4006 # 1) within comments
4007 # 2) indented preprocessor commands
4009 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4010 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4011 if (WARN("LEADING_SPACE",
4012 "please, no spaces at the start of a line\n" . $herevet) &&
4014 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4018 # check we are in a valid C source file if not then ignore this hunk
4019 next if ($realfile !~ /\.(h|c)$/);
4021 # check for unusual line ending [ or (
4022 if ($line =~ /^\+.*([\[\(])\s*$/) {
4023 CHK("OPEN_ENDED_LINE",
4024 "Lines should not end with a '$1'\n" . $herecurr);
4027 # check if this appears to be the start function declaration, save the name
4028 if ($sline =~ /^\+\{\s*$/ &&
4029 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4030 $context_function = $1;
4033 # check if this appears to be the end of function declaration
4034 if ($sline =~ /^\+\}\s*$/) {
4035 undef $context_function;
4038 # check indentation of any line with a bare else
4039 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4040 # if the previous line is a break or return and is indented 1 tab more...
4041 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4042 my $tabs = length($1) + 1;
4043 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4044 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4045 defined $lines[$linenr] &&
4046 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4047 WARN("UNNECESSARY_ELSE",
4048 "else is not generally useful after a break or return\n" . $hereprev);
4052 # check indentation of a line with a break;
4053 # if the previous line is a goto, return or break
4054 # and is indented the same # of tabs
4055 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4057 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4058 if (WARN("UNNECESSARY_BREAK",
4059 "break is not useful after a $1\n" . $hereprev) &&
4061 fix_delete_line($fixlinenr, $rawline);
4066 # check for RCS/CVS revision markers
4067 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4069 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4072 # check for old HOTPLUG __dev<foo> section markings
4073 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4074 WARN("HOTPLUG_SECTION",
4075 "Using $1 is unnecessary\n" . $herecurr);
4078 # Check for potential 'bare' types
4079 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4081 #print "LINE<$line>\n";
4082 if ($linenr > $suppress_statement &&
4083 $realcnt && $sline =~ /.\s*\S/) {
4084 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4085 ctx_statement_block($linenr, $realcnt, 0);
4086 $stat =~ s/\n./\n /g;
4087 $cond =~ s/\n./\n /g;
4089 #print "linenr<$linenr> <$stat>\n";
4090 # If this statement has no statement boundaries within
4091 # it there is no point in retrying a statement scan
4092 # until we hit end of it.
4093 my $frag = $stat; $frag =~ s/;+\s*$//;
4094 if ($frag !~ /(?:{|;)/) {
4095 #print "skip<$line_nr_next>\n";
4096 $suppress_statement = $line_nr_next;
4099 # Find the real next line.
4100 $realline_next = $line_nr_next;
4101 if (defined $realline_next &&
4102 (!defined $lines[$realline_next - 1] ||
4103 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4110 # Ignore goto labels.
4111 if ($s =~ /$Ident:\*$/s) {
4113 # Ignore functions being called
4114 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4116 } elsif ($s =~ /^.\s*else\b/s) {
4118 # declarations always start with types
4119 } 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) {
4122 possible($type, "A:" . $s);
4124 # definitions in global scope can only start with types
4125 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4126 possible($1, "B:" . $s);
4129 # any (foo ... *) is a pointer cast, and foo is a type
4130 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4131 possible($1, "C:" . $s);
4134 # Check for any sort of function declaration.
4135 # int foo(something bar, other baz);
4136 # void (*store_gdt)(x86_descr_ptr *);
4137 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4138 my ($name_len) = length($1);
4141 substr($ctx, 0, $name_len + 1, '');
4142 $ctx =~ s/\)[^\)]*$//;
4144 for my $arg (split(/\s*,\s*/, $ctx)) {
4145 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4147 possible($1, "D:" . $s);
4155 # Checks which may be anchored in the context.
4158 # Check for switch () and associated case and default
4159 # statements should be at the same indent.
4160 if ($line=~/\bswitch\s*\(.*\)/) {
4163 my @ctx = ctx_block_outer($linenr, $realcnt);
4165 for my $ctx (@ctx) {
4166 my ($clen, $cindent) = line_stats($ctx);
4167 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4168 $indent != $cindent) {
4169 $err .= "$sep$ctx\n";
4176 ERROR("SWITCH_CASE_INDENT_LEVEL",
4177 "switch and case should be at the same indent\n$hereline$err");
4181 # if/while/etc brace do not go on next line, unless defining a do while loop,
4182 # or if that brace on the next line is for something else
4183 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4184 my $pre_ctx = "$1$2";
4186 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4188 if ($line =~ /^\+\t{6,}/) {
4189 WARN("DEEP_INDENTATION",
4190 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4193 my $ctx_cnt = $realcnt - $#ctx - 1;
4194 my $ctx = join("\n", @ctx);
4196 my $ctx_ln = $linenr;
4197 my $ctx_skip = $realcnt;
4199 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4200 defined $lines[$ctx_ln - 1] &&
4201 $lines[$ctx_ln - 1] =~ /^-/)) {
4202 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4203 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4207 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4208 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4210 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4212 "that open brace { should be on the previous line\n" .
4213 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4215 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4216 $ctx =~ /\)\s*\;\s*$/ &&
4217 defined $lines[$ctx_ln - 1])
4219 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4220 if ($nindent > $indent) {
4221 WARN("TRAILING_SEMICOLON",
4222 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4223 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4228 # Check relative indent for conditionals and blocks.
4229 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4230 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4231 ctx_statement_block($linenr, $realcnt, 0)
4232 if (!defined $stat);
4233 my ($s, $c) = ($stat, $cond);
4235 substr($s, 0, length($c), '');
4237 # remove inline comments
4241 # Find out how long the conditional actually is.
4242 my @newlines = ($c =~ /\n/gs);
4243 my $cond_lines = 1 + $#newlines;
4245 # Make sure we remove the line prefixes as we have
4246 # none on the first line, and are going to readd them
4249 while ($s =~ /\n\s+\\\n/) {
4250 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4253 # We want to check the first line inside the block
4254 # starting at the end of the conditional, so remove:
4255 # 1) any blank line termination
4256 # 2) any opening brace { on end of the line
4258 my $continuation = 0;
4260 $s =~ s/^.*\bdo\b//;
4262 if ($s =~ s/^\s*\\//) {
4265 if ($s =~ s/^\s*?\n//) {
4270 # Also ignore a loop construct at the end of a
4271 # preprocessor statement.
4272 if (($prevline =~ /^.\s*#\s*define\s/ ||
4273 $prevline =~ /\\\s*$/) && $continuation == 0) {
4279 while ($cond_ptr != $cond_lines) {
4280 $cond_ptr = $cond_lines;
4282 # If we see an #else/#elif then the code
4284 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4289 # 1) blank lines, they should be at 0,
4290 # 2) preprocessor lines, and
4292 if ($continuation ||
4294 $s =~ /^\s*#\s*?/ ||
4295 $s =~ /^\s*$Ident\s*:/) {
4296 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4297 if ($s =~ s/^.*?\n//) {
4303 my (undef, $sindent) = line_stats("+" . $s);
4304 my $stat_real = raw_line($linenr, $cond_lines);
4306 # Check if either of these lines are modified, else
4307 # this is not this patch's fault.
4308 if (!defined($stat_real) ||
4309 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4312 if (defined($stat_real) && $cond_lines > 1) {
4313 $stat_real = "[...]\n$stat_real";
4316 #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";
4318 if ($check && $s ne '' &&
4319 (($sindent % $tabsize) != 0 ||
4320 ($sindent < $indent) ||
4321 ($sindent == $indent &&
4322 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4323 ($sindent > $indent + $tabsize))) {
4324 WARN("SUSPECT_CODE_INDENT",
4325 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4329 # Track the 'values' across context and added lines.
4330 my $opline = $line; $opline =~ s/^./ /;
4331 my ($curr_values, $curr_vars) =
4332 annotate_values($opline . "\n", $prev_values);
4333 $curr_values = $prev_values . $curr_values;
4335 my $outline = $opline; $outline =~ s/\t/ /g;
4336 print "$linenr > .$outline\n";
4337 print "$linenr > $curr_values\n";
4338 print "$linenr > $curr_vars\n";
4340 $prev_values = substr($curr_values, -1);
4342 #ignore lines not being added
4343 next if ($line =~ /^[^\+]/);
4345 # check for self assignments used to avoid compiler warnings
4346 # e.g.: int foo = foo, *bar = NULL;
4347 # struct foo bar = *(&(bar));
4348 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4350 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4351 WARN("SELF_ASSIGNMENT",
4352 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4356 # check for dereferences that span multiple lines
4357 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4358 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4359 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4361 $line =~ /^.\s*($Lval)/;
4364 WARN("MULTILINE_DEREFERENCE",
4365 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4368 # check for declarations of signed or unsigned without int
4369 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4372 $var = "" if (!defined $var);
4373 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4377 $pointer = "" if (!defined $pointer);
4379 if (WARN("UNSPECIFIED_INT",
4380 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4382 my $decl = trim($sign) . " int ";
4383 my $comp_pointer = $pointer;
4384 $comp_pointer =~ s/\s//g;
4385 $decl .= $comp_pointer;
4386 $decl = rtrim($decl) if ($var eq "");
4387 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4392 # TEST: allow direct testing of the type matcher.
4394 if ($line =~ /^.\s*$Declare\s*$/) {
4396 "TEST: is type\n" . $herecurr);
4397 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4398 ERROR("TEST_NOT_TYPE",
4399 "TEST: is not type ($1 is)\n". $herecurr);
4403 # TEST: allow direct testing of the attribute matcher.
4405 if ($line =~ /^.\s*$Modifier\s*$/) {
4407 "TEST: is attr\n" . $herecurr);
4408 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4409 ERROR("TEST_NOT_ATTR",
4410 "TEST: is not attr ($1 is)\n". $herecurr);
4415 # check for initialisation to aggregates open brace on the next line
4416 if ($line =~ /^.\s*{/ &&
4417 $prevline =~ /(?:^|[^=])=\s*$/) {
4418 if (ERROR("OPEN_BRACE",
4419 "that open brace { should be on the previous line\n" . $hereprev) &&
4420 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4421 fix_delete_line($fixlinenr - 1, $prevrawline);
4422 fix_delete_line($fixlinenr, $rawline);
4423 my $fixedline = $prevrawline;
4424 $fixedline =~ s/\s*=\s*$/ = {/;
4425 fix_insert_line($fixlinenr, $fixedline);
4427 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4428 fix_insert_line($fixlinenr, $fixedline);
4433 # Checks which are anchored on the added line.
4436 # check for malformed paths in #include statements (uses RAW line)
4437 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4439 if ($path =~ m{//}) {
4440 ERROR("MALFORMED_INCLUDE",
4441 "malformed #include filename\n" . $herecurr);
4443 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4444 ERROR("UAPI_INCLUDE",
4445 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4449 # no C99 // comments
4450 if ($line =~ m{//}) {
4451 if (ERROR("C99_COMMENTS",
4452 "do not use C99 // comments\n" . $herecurr) &&
4454 my $line = $fixed[$fixlinenr];
4455 if ($line =~ /\/\/(.*)$/) {
4456 my $comment = trim($1);
4457 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4461 # Remove C99 comments.
4463 $opline =~ s@//.*@@;
4465 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4466 # the whole statement.
4467 #print "APW <$lines[$realline_next - 1]>\n";
4468 if (defined $realline_next &&
4469 exists $lines[$realline_next - 1] &&
4470 !defined $suppress_export{$realline_next} &&
4471 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4472 # Handle definitions which produce identifiers with
4475 # EXPORT_SYMBOL(something_foo);
4477 $name =~ s/^\s*($Ident).*/$1/;
4478 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4479 $name =~ /^${Ident}_$2/) {
4480 #print "FOO C name<$name>\n";
4481 $suppress_export{$realline_next} = 1;
4483 } elsif ($stat !~ /(?:
4485 ^.DEFINE_$Ident\(\Q$name\E\)|
4486 ^.DECLARE_$Ident\(\Q$name\E\)|
4487 ^.LIST_HEAD\(\Q$name\E\)|
4488 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4489 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4491 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4492 $suppress_export{$realline_next} = 2;
4494 $suppress_export{$realline_next} = 1;
4497 if (!defined $suppress_export{$linenr} &&
4498 $prevline =~ /^.\s*$/ &&
4499 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4500 #print "FOO B <$lines[$linenr - 1]>\n";
4501 $suppress_export{$linenr} = 2;
4503 if (defined $suppress_export{$linenr} &&
4504 $suppress_export{$linenr} == 2) {
4505 WARN("EXPORT_SYMBOL",
4506 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4509 # check for global initialisers.
4510 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4511 !exclude_global_initialisers($realfile)) {
4512 if (ERROR("GLOBAL_INITIALISERS",
4513 "do not initialise globals to $1\n" . $herecurr) &&
4515 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4518 # check for static initialisers.
4519 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4520 if (ERROR("INITIALISED_STATIC",
4521 "do not initialise statics to $1\n" .
4524 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4528 # check for misordered declarations of char/short/int/long with signed/unsigned
4529 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4531 WARN("MISORDERED_TYPE",
4532 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4535 # check for unnecessary <signed> int declarations of short/long/long long
4536 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4537 my $type = trim($1);
4538 next if ($type !~ /\bint\b/);
4539 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4540 my $new_type = $type;
4541 $new_type =~ s/\b\s*int\s*\b/ /;
4542 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4543 $new_type =~ s/^const\s+//;
4544 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4545 $new_type = "const $new_type" if ($type =~ /^const\b/);
4546 $new_type =~ s/\s+/ /g;
4547 $new_type = trim($new_type);
4548 if (WARN("UNNECESSARY_INT",
4549 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4551 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4555 # check for static const char * arrays.
4556 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4557 WARN("STATIC_CONST_CHAR_ARRAY",
4558 "static const char * array should probably be static const char * const\n" .
4562 # check for initialized const char arrays that should be static const
4563 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4564 if (WARN("STATIC_CONST_CHAR_ARRAY",
4565 "const array should probably be static const\n" . $herecurr) &&
4567 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4571 # check for static char foo[] = "bar" declarations.
4572 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4573 WARN("STATIC_CONST_CHAR_ARRAY",
4574 "static char array declaration should probably be static const char\n" .
4578 # check for const <foo> const where <foo> is not a pointer or array type
4579 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4581 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4583 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4584 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4586 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4590 # check for const static or static <non ptr type> const declarations
4591 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4592 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4593 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4594 if (WARN("STATIC_CONST",
4595 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4597 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4598 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4602 # check for non-global char *foo[] = {"bar", ...} declarations.
4603 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4604 WARN("STATIC_CONST_CHAR_ARRAY",
4605 "char * array declaration might be better as static const\n" .
4609 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4610 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4612 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4614 if (WARN("ARRAY_SIZE",
4615 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4617 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4622 # check for function declarations without arguments like "int foo()"
4623 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4624 if (ERROR("FUNCTION_WITHOUT_ARGS",
4625 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4627 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4631 # check for new typedefs, only function parameters and sparse annotations
4633 if ($line =~ /\btypedef\s/ &&
4634 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4635 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4636 $line !~ /\b$typeTypedefs\b/ &&
4637 $line !~ /\b__bitwise\b/) {
4638 WARN("NEW_TYPEDEFS",
4639 "do not add new typedefs\n" . $herecurr);
4642 # * goes on variable not on type
4644 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4646 my ($ident, $from, $to) = ($1, $2, $2);
4648 # Should start with a space.
4649 $to =~ s/^(\S)/ $1/;
4650 # Should not end with a space.
4652 # '*'s should not have spaces between.
4653 while ($to =~ s/\*\s+\*/\*\*/) {
4656 ## print "1: from<$from> to<$to> ident<$ident>\n";
4658 if (ERROR("POINTER_LOCATION",
4659 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4661 my $sub_from = $ident;
4662 my $sub_to = $ident;
4663 $sub_to =~ s/\Q$from\E/$to/;
4664 $fixed[$fixlinenr] =~
4665 s@\Q$sub_from\E@$sub_to@;
4669 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4671 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4673 # Should start with a space.
4674 $to =~ s/^(\S)/ $1/;
4675 # Should not end with a space.
4677 # '*'s should not have spaces between.
4678 while ($to =~ s/\*\s+\*/\*\*/) {
4680 # Modifiers should have spaces.
4681 $to =~ s/(\b$Modifier$)/$1 /;
4683 ## print "2: from<$from> to<$to> ident<$ident>\n";
4684 if ($from ne $to && $ident !~ /^$Modifier$/) {
4685 if (ERROR("POINTER_LOCATION",
4686 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4689 my $sub_from = $match;
4690 my $sub_to = $match;
4691 $sub_to =~ s/\Q$from\E/$to/;
4692 $fixed[$fixlinenr] =~
4693 s@\Q$sub_from\E@$sub_to@;
4698 # avoid BUG() or BUG_ON()
4699 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4700 my $msg_level = \&WARN;
4701 $msg_level = \&CHK if ($file);
4702 &{$msg_level}("AVOID_BUG",
4703 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4706 # avoid LINUX_VERSION_CODE
4707 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4708 WARN("LINUX_VERSION_CODE",
4709 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4712 # check for uses of printk_ratelimit
4713 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4714 WARN("PRINTK_RATELIMITED",
4715 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4718 # printk should use KERN_* levels
4719 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4720 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4721 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4724 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4725 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4729 $modifier = "" if (!defined($modifier));
4730 my $level = lc($orig);
4731 $level = "warn" if ($level eq "warning");
4732 my $level2 = $level;
4733 $level2 = "dbg" if ($level eq "debug");
4734 $level .= $modifier;
4735 $level2 .= $modifier;
4736 WARN("PREFER_PR_LEVEL",
4737 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4740 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4741 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4743 my $level = lc($orig);
4744 $level = "warn" if ($level eq "warning");
4745 $level = "dbg" if ($level eq "debug");
4746 WARN("PREFER_DEV_LEVEL",
4747 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4750 # trace_printk should not be used in production code.
4751 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4752 WARN("TRACE_PRINTK",
4753 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4756 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4757 # number of false positives, but assembly files are not checked, so at
4758 # least the arch entry code will not trigger this warning.
4759 if ($line =~ /\bENOSYS\b/) {
4761 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4764 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4765 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4766 # Similarly to ENOSYS warning a small number of false positives is expected.
4767 if (!$file && $line =~ /\bENOTSUPP\b/) {
4768 if (WARN("ENOTSUPP",
4769 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4771 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4775 # function brace can't be on same line, except for #defines of do while,
4776 # or if closed on same line
4777 if ($perl_version_ok &&
4778 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4779 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4781 if (ERROR("OPEN_BRACE",
4782 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4784 fix_delete_line($fixlinenr, $rawline);
4785 my $fixed_line = $rawline;
4786 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4789 fix_insert_line($fixlinenr, ltrim($line1));
4790 fix_insert_line($fixlinenr, "\+{");
4791 if ($line2 !~ /^\s*$/) {
4792 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4797 # open braces for enum, union and struct go on the same line.
4798 if ($line =~ /^.\s*{/ &&
4799 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4800 if (ERROR("OPEN_BRACE",
4801 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4802 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4803 fix_delete_line($fixlinenr - 1, $prevrawline);
4804 fix_delete_line($fixlinenr, $rawline);
4805 my $fixedline = rtrim($prevrawline) . " {";
4806 fix_insert_line($fixlinenr, $fixedline);
4807 $fixedline = $rawline;
4808 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4809 if ($fixedline !~ /^\+\s*$/) {
4810 fix_insert_line($fixlinenr, $fixedline);
4815 # missing space after union, struct or enum definition
4816 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4818 "missing space after $1 definition\n" . $herecurr) &&
4820 $fixed[$fixlinenr] =~
4821 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4825 # Function pointer declarations
4826 # check spacing between type, funcptr, and args
4827 # canonical declaration is "type (*funcptr)(args...)"
4828 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4830 my $pre_pointer_space = $2;
4831 my $post_pointer_space = $3;
4833 my $post_funcname_space = $5;
4834 my $pre_args_space = $6;
4836 # the $Declare variable will capture all spaces after the type
4837 # so check it for a missing trailing missing space but pointer return types
4838 # don't need a space so don't warn for those.
4839 my $post_declare_space = "";
4840 if ($declare =~ /(\s+)$/) {
4841 $post_declare_space = $1;
4842 $declare = rtrim($declare);
4844 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4846 "missing space after return type\n" . $herecurr);
4847 $post_declare_space = " ";
4850 # unnecessary space "type (*funcptr)(args...)"
4851 # This test is not currently implemented because these declarations are
4853 # int foo(int bar, ...)
4854 # and this is form shouldn't/doesn't generate a checkpatch warning.
4856 # elsif ($declare =~ /\s{2,}$/) {
4858 # "Multiple spaces after return type\n" . $herecurr);
4861 # unnecessary space "type ( *funcptr)(args...)"
4862 if (defined $pre_pointer_space &&
4863 $pre_pointer_space =~ /^\s/) {
4865 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4868 # unnecessary space "type (* funcptr)(args...)"
4869 if (defined $post_pointer_space &&
4870 $post_pointer_space =~ /^\s/) {
4872 "Unnecessary space before function pointer name\n" . $herecurr);
4875 # unnecessary space "type (*funcptr )(args...)"
4876 if (defined $post_funcname_space &&
4877 $post_funcname_space =~ /^\s/) {
4879 "Unnecessary space after function pointer name\n" . $herecurr);
4882 # unnecessary space "type (*funcptr) (args...)"
4883 if (defined $pre_args_space &&
4884 $pre_args_space =~ /^\s/) {
4886 "Unnecessary space before function pointer arguments\n" . $herecurr);
4889 if (show_type("SPACING") && $fix) {
4890 $fixed[$fixlinenr] =~
4891 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4895 # check for spacing round square brackets; allowed:
4896 # 1. with a type on the left -- int [] a;
4897 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4898 # 3. inside a curly brace -- = { [0...10] = 5 }
4899 while ($line =~ /(.*?\s)\[/g) {
4900 my ($where, $prefix) = ($-[1], $1);
4901 if ($prefix !~ /$Type\s+$/ &&
4902 ($where != 0 || $prefix !~ /^.\s+$/) &&
4903 $prefix !~ /[{,:]\s+$/) {
4904 if (ERROR("BRACKET_SPACE",
4905 "space prohibited before open square bracket '['\n" . $herecurr) &&
4907 $fixed[$fixlinenr] =~
4908 s/^(\+.*?)\s+\[/$1\[/;
4913 # check for spaces between functions and their parentheses.
4914 while ($line =~ /($Ident)\s+\(/g) {
4916 my $ctx_before = substr($line, 0, $-[1]);
4917 my $ctx = "$ctx_before$name";
4919 # Ignore those directives where spaces _are_ permitted.
4921 if|for|while|switch|return|case|
4922 volatile|__volatile__|
4923 __attribute__|format|__extension__|
4926 # cpp #define statements have non-optional spaces, ie
4927 # if there is a space between the name and the open
4928 # parenthesis it is simply not a parameter group.
4929 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4931 # cpp #elif statement condition may start with a (
4932 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4934 # If this whole things ends with a type its most
4935 # likely a typedef for a function.
4936 } elsif ($ctx =~ /$Type$/) {
4940 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4942 $fixed[$fixlinenr] =~
4943 s/\b$name\s+\(/$name\(/;
4948 # Check operator spacing.
4949 if (!($line=~/\#\s*include/)) {
4950 my $fixed_line = "";
4954 <<=|>>=|<=|>=|==|!=|
4955 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4956 =>|->|<<|>>|<|>|=|!|~|
4957 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4960 my @elements = split(/($ops|;)/, $opline);
4962 ## print("element count: <" . $#elements . ">\n");
4963 ## foreach my $el (@elements) {
4964 ## print("el: <$el>\n");
4967 my @fix_elements = ();
4970 foreach my $el (@elements) {
4971 push(@fix_elements, substr($rawline, $off, length($el)));
4972 $off += length($el);
4977 my $blank = copy_spacing($opline);
4978 my $last_after = -1;
4980 for (my $n = 0; $n < $#elements; $n += 2) {
4982 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4984 ## print("n: <$n> good: <$good>\n");
4986 $off += length($elements[$n]);
4988 # Pick up the preceding and succeeding characters.
4989 my $ca = substr($opline, 0, $off);
4991 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4992 $cc = substr($opline, $off + length($elements[$n + 1]));
4994 my $cb = "$ca$;$cc";
4997 $a = 'V' if ($elements[$n] ne '');
4998 $a = 'W' if ($elements[$n] =~ /\s$/);
4999 $a = 'C' if ($elements[$n] =~ /$;$/);
5000 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5001 $a = 'O' if ($elements[$n] eq '');
5002 $a = 'E' if ($ca =~ /^\s*$/);
5004 my $op = $elements[$n + 1];
5007 if (defined $elements[$n + 2]) {
5008 $c = 'V' if ($elements[$n + 2] ne '');
5009 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5010 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5011 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5012 $c = 'O' if ($elements[$n + 2] eq '');
5013 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5018 my $ctx = "${a}x${c}";
5020 my $at = "(ctx:$ctx)";
5022 my $ptr = substr($blank, 0, $off) . "^";
5023 my $hereptr = "$hereline$ptr\n";
5025 # Pull out the value of this operator.
5026 my $op_type = substr($curr_values, $off + 1, 1);
5028 # Get the full operator variant.
5029 my $opv = $op . substr($curr_vars, $off, 1);
5031 # Ignore operators passed as parameters.
5032 if ($op_type ne 'V' &&
5033 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5036 # } elsif ($op =~ /^$;+$/) {
5038 # ; should have either the end of line or a space or \ after it
5039 } elsif ($op eq ';') {
5040 if ($ctx !~ /.x[WEBC]/ &&
5041 $cc !~ /^\\/ && $cc !~ /^;/) {
5042 if (ERROR("SPACING",
5043 "space required after that '$op' $at\n" . $hereptr)) {
5044 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5050 } elsif ($op eq '//') {
5052 # : when part of a bitfield
5053 } elsif ($opv eq ':B') {
5054 # skip the bitfield test for now
5058 } elsif ($op eq '->') {
5059 if ($ctx =~ /Wx.|.xW/) {
5060 if (ERROR("SPACING",
5061 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5062 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5063 if (defined $fix_elements[$n + 2]) {
5064 $fix_elements[$n + 2] =~ s/^\s+//;
5070 # , must not have a space before and must have a space on the right.
5071 } elsif ($op eq ',') {
5072 my $rtrim_before = 0;
5073 my $space_after = 0;
5074 if ($ctx =~ /Wx./) {
5075 if (ERROR("SPACING",
5076 "space prohibited before that '$op' $at\n" . $hereptr)) {
5081 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5082 if (ERROR("SPACING",
5083 "space required after that '$op' $at\n" . $hereptr)) {
5089 if ($rtrim_before || $space_after) {
5090 if ($rtrim_before) {
5091 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5093 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5100 # '*' as part of a type definition -- reported already.
5101 } elsif ($opv eq '*_') {
5102 #warn "'*' is part of type\n";
5104 # unary operators should have a space before and
5105 # none after. May be left adjacent to another
5106 # unary operator, or a cast
5107 } elsif ($op eq '!' || $op eq '~' ||
5108 $opv eq '*U' || $opv eq '-U' ||
5109 $opv eq '&U' || $opv eq '&&U') {
5110 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5111 if (ERROR("SPACING",
5112 "space required before that '$op' $at\n" . $hereptr)) {
5113 if ($n != $last_after + 2) {
5114 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5119 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5120 # A unary '*' may be const
5122 } elsif ($ctx =~ /.xW/) {
5123 if (ERROR("SPACING",
5124 "space prohibited after that '$op' $at\n" . $hereptr)) {
5125 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5126 if (defined $fix_elements[$n + 2]) {
5127 $fix_elements[$n + 2] =~ s/^\s+//;
5133 # unary ++ and unary -- are allowed no space on one side.
5134 } elsif ($op eq '++' or $op eq '--') {
5135 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5136 if (ERROR("SPACING",
5137 "space required one side of that '$op' $at\n" . $hereptr)) {
5138 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5142 if ($ctx =~ /Wx[BE]/ ||
5143 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5144 if (ERROR("SPACING",
5145 "space prohibited before that '$op' $at\n" . $hereptr)) {
5146 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5150 if ($ctx =~ /ExW/) {
5151 if (ERROR("SPACING",
5152 "space prohibited after that '$op' $at\n" . $hereptr)) {
5153 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5154 if (defined $fix_elements[$n + 2]) {
5155 $fix_elements[$n + 2] =~ s/^\s+//;
5161 # << and >> may either have or not have spaces both sides
5162 } elsif ($op eq '<<' or $op eq '>>' or
5163 $op eq '&' or $op eq '^' or $op eq '|' or
5164 $op eq '+' or $op eq '-' or
5165 $op eq '*' or $op eq '/' or
5169 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5171 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5172 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5173 $fix_elements[$n + 2] =~ s/^\s+//;
5176 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5178 "space preferred before that '$op' $at\n" . $hereptr)) {
5179 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5183 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5184 if (ERROR("SPACING",
5185 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5186 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5187 if (defined $fix_elements[$n + 2]) {
5188 $fix_elements[$n + 2] =~ s/^\s+//;
5194 # A colon needs no spaces before when it is
5195 # terminating a case value or a label.
5196 } elsif ($opv eq ':C' || $opv eq ':L') {
5197 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5198 if (ERROR("SPACING",
5199 "space prohibited before that '$op' $at\n" . $hereptr)) {
5200 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5205 # All the others need spaces both sides.
5206 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5209 # Ignore email addresses <foo@bar>
5211 $cc =~ /^\S+\@\S+>/) ||
5213 $ca =~ /<\S+\@\S+$/))
5218 # for asm volatile statements
5219 # ignore a colon with another
5220 # colon immediately before or after
5222 ($ca =~ /:$/ || $cc =~ /^:/)) {
5226 # messages are ERROR, but ?: are CHK
5228 my $msg_level = \&ERROR;
5229 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5231 if (&{$msg_level}("SPACING",
5232 "spaces required around that '$op' $at\n" . $hereptr)) {
5233 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5234 if (defined $fix_elements[$n + 2]) {
5235 $fix_elements[$n + 2] =~ s/^\s+//;
5241 $off += length($elements[$n + 1]);
5243 ## print("n: <$n> GOOD: <$good>\n");
5245 $fixed_line = $fixed_line . $good;
5248 if (($#elements % 2) == 0) {
5249 $fixed_line = $fixed_line . $fix_elements[$#elements];
5252 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5253 $fixed[$fixlinenr] = $fixed_line;
5259 # check for whitespace before a non-naked semicolon
5260 if ($line =~ /^\+.*\S\s+;\s*$/) {
5262 "space prohibited before semicolon\n" . $herecurr) &&
5264 1 while $fixed[$fixlinenr] =~
5265 s/^(\+.*\S)\s+;/$1;/;
5269 # check for multiple assignments
5270 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5271 CHK("MULTIPLE_ASSIGNMENTS",
5272 "multiple assignments should be avoided\n" . $herecurr);
5275 ## # check for multiple declarations, allowing for a function declaration
5277 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5278 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5280 ## # Remove any bracketed sections to ensure we do not
5281 ## # falsely report the parameters of functions.
5283 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5285 ## if ($ln =~ /,/) {
5286 ## WARN("MULTIPLE_DECLARATION",
5287 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5291 #need space before brace following if, while, etc
5292 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5293 $line =~ /\b(?:else|do)\{/) {
5294 if (ERROR("SPACING",
5295 "space required before the open brace '{'\n" . $herecurr) &&
5297 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5301 ## # check for blank lines before declarations
5302 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5303 ## $prevrawline =~ /^.\s*$/) {
5305 ## "No blank lines before declarations\n" . $hereprev);
5309 # closing brace should have a space following it when it has anything
5311 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5312 if (ERROR("SPACING",
5313 "space required after that close brace '}'\n" . $herecurr) &&
5315 $fixed[$fixlinenr] =~
5316 s/}((?!(?:,|;|\)))\S)/} $1/;
5320 # check spacing on square brackets
5321 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5322 if (ERROR("SPACING",
5323 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5325 $fixed[$fixlinenr] =~
5329 if ($line =~ /\s\]/) {
5330 if (ERROR("SPACING",
5331 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5333 $fixed[$fixlinenr] =~
5338 # check spacing on parentheses
5339 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5340 $line !~ /for\s*\(\s+;/) {
5341 if (ERROR("SPACING",
5342 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5344 $fixed[$fixlinenr] =~
5348 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5349 $line !~ /for\s*\(.*;\s+\)/ &&
5350 $line !~ /:\s+\)/) {
5351 if (ERROR("SPACING",
5352 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5354 $fixed[$fixlinenr] =~
5359 # check unnecessary parentheses around addressof/dereference single $Lvals
5360 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5362 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5364 if (CHK("UNNECESSARY_PARENTHESES",
5365 "Unnecessary parentheses around $var\n" . $herecurr) &&
5367 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5371 # check for unnecessary parentheses around function pointer uses
5372 # ie: (foo->bar)(); should be foo->bar();
5373 # but not "if (foo->bar) (" to avoid some false positives
5374 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5376 if (CHK("UNNECESSARY_PARENTHESES",
5377 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5379 my $var2 = deparenthesize($var);
5381 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5385 # check for unnecessary parentheses around comparisons in if uses
5386 # when !drivers/staging or command-line uses --strict
5387 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5388 $perl_version_ok && defined($stat) &&
5389 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5391 my $test = substr($2, 1, -1);
5393 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5395 # avoid parentheses around potential macro args
5396 next if ($match =~ /^\s*\w+\s*$/);
5397 if (!defined($herectx)) {
5398 $herectx = $here . "\n";
5399 my $cnt = statement_rawlines($if_stat);
5400 for (my $n = 0; $n < $cnt; $n++) {
5401 my $rl = raw_line($linenr, $n);
5402 $herectx .= $rl . "\n";
5403 last if $rl =~ /^[ \+].*\{/;
5406 CHK("UNNECESSARY_PARENTHESES",
5407 "Unnecessary parentheses around '$match'\n" . $herectx);
5411 # check that goto labels aren't indented (allow a single space indentation)
5412 # and ignore bitfield definitions like foo:1
5413 # Strictly, labels can have whitespace after the identifier and before the :
5414 # but this is not allowed here as many ?: uses would appear to be labels
5415 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5416 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5417 $sline !~ /^.\s+default:/) {
5418 if (WARN("INDENTED_LABEL",
5419 "labels should not be indented\n" . $herecurr) &&
5421 $fixed[$fixlinenr] =~
5426 # check if a statement with a comma should be two statements like:
5427 # foo = bar(), /* comma should be semicolon */
5429 if (defined($stat) &&
5430 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5431 my $cnt = statement_rawlines($stat);
5432 my $herectx = get_stat_here($linenr, $cnt, $here);
5433 WARN("SUSPECT_COMMA_SEMICOLON",
5434 "Possible comma where semicolon could be used\n" . $herectx);
5437 # return is not a function
5438 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5440 if ($perl_version_ok &&
5441 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5443 $value = deparenthesize($value);
5444 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5445 ERROR("RETURN_PARENTHESES",
5446 "return is not a function, parentheses are not required\n" . $herecurr);
5448 } elsif ($spacing !~ /\s+/) {
5450 "space required before the open parenthesis '('\n" . $herecurr);
5454 # unnecessary return in a void function
5455 # at end-of-function, with the previous line a single leading tab, then return;
5456 # and the line before that not a goto label target like "out:"
5457 if ($sline =~ /^[ \+]}\s*$/ &&
5458 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5460 $lines[$linenr - 3] =~ /^[ +]/ &&
5461 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5463 "void function return statements are not generally useful\n" . $hereprev);
5466 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5467 if ($perl_version_ok &&
5468 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5469 my $openparens = $1;
5470 my $count = $openparens =~ tr@\(@\(@;
5472 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5473 my $comp = $4; #Not $1 because of $LvalOrFunc
5474 $msg = " - maybe == should be = ?" if ($comp eq "==");
5475 WARN("UNNECESSARY_PARENTHESES",
5476 "Unnecessary parentheses$msg\n" . $herecurr);
5480 # comparisons with a constant or upper case identifier on the left
5481 # avoid cases like "foo + BAR < baz"
5482 # only fix matches surrounded by parentheses to avoid incorrect
5483 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5484 if ($perl_version_ok &&
5485 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5490 my $newcomp = $comp;
5491 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5492 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5493 WARN("CONSTANT_COMPARISON",
5494 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5498 } elsif ($comp eq "<=") {
5500 } elsif ($comp eq ">") {
5502 } elsif ($comp eq ">=") {
5505 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5509 # Return of what appears to be an errno should normally be negative
5510 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5512 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5513 WARN("USE_NEGATIVE_ERRNO",
5514 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5518 # Need a space before open parenthesis after if, while etc
5519 if ($line =~ /\b(if|while|for|switch)\(/) {
5520 if (ERROR("SPACING",
5521 "space required before the open parenthesis '('\n" . $herecurr) &&
5523 $fixed[$fixlinenr] =~
5524 s/\b(if|while|for|switch)\(/$1 \(/;
5528 # Check for illegal assignment in if conditional -- and check for trailing
5529 # statements after the conditional.
5530 if ($line =~ /do\s*(?!{)/) {
5531 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5532 ctx_statement_block($linenr, $realcnt, 0)
5533 if (!defined $stat);
5534 my ($stat_next) = ctx_statement_block($line_nr_next,
5535 $remain_next, $off_next);
5536 $stat_next =~ s/\n./\n /g;
5537 ##print "stat<$stat> stat_next<$stat_next>\n";
5539 if ($stat_next =~ /^\s*while\b/) {
5540 # If the statement carries leading newlines,
5541 # then count those as offsets.
5543 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5545 statement_rawlines($whitespace) - 1;
5547 $suppress_whiletrailers{$line_nr_next +
5551 if (!defined $suppress_whiletrailers{$linenr} &&
5552 defined($stat) && defined($cond) &&
5553 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5554 my ($s, $c) = ($stat, $cond);
5555 my $fixed_assign_in_if = 0;
5557 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5558 if (ERROR("ASSIGN_IN_IF",
5559 "do not use assignment in if condition\n" . $herecurr) &&
5560 $fix && $perl_version_ok) {
5561 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5569 fix_delete_line($fixlinenr, $rawline);
5570 fix_insert_line($fixlinenr, "$space$statement;");
5571 my $newline = "${space}if (";
5572 $newline .= '!' if defined($not);
5573 $newline .= '(' if (defined $not && defined($test) && defined($against));
5574 $newline .= "$assigned";
5575 $newline .= " $test $against" if (defined($test) && defined($against));
5576 $newline .= ')' if (defined $not && defined($test) && defined($against));
5578 $newline .= " {" if (defined($brace));
5579 fix_insert_line($fixlinenr + 1, $newline);
5580 $fixed_assign_in_if = 1;
5585 # Find out what is on the end of the line after the
5587 substr($s, 0, length($c), '');
5589 $s =~ s/$;//g; # Remove any comments
5590 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5591 $c !~ /}\s*while\s*/)
5593 # Find out how long the conditional actually is.
5594 my @newlines = ($c =~ /\n/gs);
5595 my $cond_lines = 1 + $#newlines;
5598 $stat_real = raw_line($linenr, $cond_lines)
5599 . "\n" if ($cond_lines);
5600 if (defined($stat_real) && $cond_lines > 1) {
5601 $stat_real = "[...]\n$stat_real";
5604 if (ERROR("TRAILING_STATEMENTS",
5605 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5606 !$fixed_assign_in_if &&
5608 $fix && $perl_version_ok &&
5609 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5612 my $rest = rtrim($4);
5613 if ($rest =~ /;$/) {
5614 $fixed[$fixlinenr] = "\+$indent$test";
5615 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5621 # Check for bitwise tests written as boolean
5633 WARN("HEXADECIMAL_BOOLEAN_TEST",
5634 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5637 # if and else should not have general statements after it
5638 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5640 $s =~ s/$;//g; # Remove any comments
5641 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5642 ERROR("TRAILING_STATEMENTS",
5643 "trailing statements should be on next line\n" . $herecurr);
5646 # if should not continue a brace
5647 if ($line =~ /}\s*if\b/) {
5648 ERROR("TRAILING_STATEMENTS",
5649 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5652 # case and default should not have general statements after them
5653 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5655 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5659 ERROR("TRAILING_STATEMENTS",
5660 "trailing statements should be on next line\n" . $herecurr);
5663 # Check for }<nl>else {, these must be at the same
5664 # indent level to be relevant to each other.
5665 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5666 $previndent == $indent) {
5667 if (ERROR("ELSE_AFTER_BRACE",
5668 "else should follow close brace '}'\n" . $hereprev) &&
5669 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5670 fix_delete_line($fixlinenr - 1, $prevrawline);
5671 fix_delete_line($fixlinenr, $rawline);
5672 my $fixedline = $prevrawline;
5673 $fixedline =~ s/}\s*$//;
5674 if ($fixedline !~ /^\+\s*$/) {
5675 fix_insert_line($fixlinenr, $fixedline);
5677 $fixedline = $rawline;
5678 $fixedline =~ s/^(.\s*)else/$1} else/;
5679 fix_insert_line($fixlinenr, $fixedline);
5683 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5684 $previndent == $indent) {
5685 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5687 # Find out what is on the end of the line after the
5689 substr($s, 0, length($c), '');
5692 if ($s =~ /^\s*;/) {
5693 if (ERROR("WHILE_AFTER_BRACE",
5694 "while should follow close brace '}'\n" . $hereprev) &&
5695 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5696 fix_delete_line($fixlinenr - 1, $prevrawline);
5697 fix_delete_line($fixlinenr, $rawline);
5698 my $fixedline = $prevrawline;
5699 my $trailing = $rawline;
5700 $trailing =~ s/^\+//;
5701 $trailing = trim($trailing);
5702 $fixedline =~ s/}\s*$/} $trailing/;
5703 fix_insert_line($fixlinenr, $fixedline);
5708 #Specific variable tests
5709 while ($line =~ m{($Constant|$Lval)}g) {
5713 if ($var !~ /^$Constant$/ &&
5714 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5715 #Ignore some autogenerated defines and enum values
5716 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5717 #Ignore Page<foo> variants
5718 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5719 #Ignore SI style variants like nS, mV and dB
5720 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5721 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5722 #Ignore some three character SI units explicitly, like MiB and KHz
5723 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5724 while ($var =~ m{\b($Ident)}g) {
5726 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5728 seed_camelcase_includes();
5729 if (!$file && !$camelcase_file_seeded) {
5730 seed_camelcase_file($realfile);
5731 $camelcase_file_seeded = 1;
5734 if (!defined $camelcase{$word}) {
5735 $camelcase{$word} = 1;
5737 "Avoid CamelCase: <$word>\n" . $herecurr);
5743 #no spaces allowed after \ in define
5744 if ($line =~ /\#\s*define.*\\\s+$/) {
5745 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5746 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5748 $fixed[$fixlinenr] =~ s/\s+$//;
5752 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5753 # itself <asm/foo.h> (uses RAW line)
5754 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5756 my $checkfile = "include/linux/$file";
5757 if (-f "$root/$checkfile" &&
5758 $realfile ne $checkfile &&
5759 $1 !~ /$allowed_asm_includes/)
5761 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5762 if ($asminclude > 0) {
5763 if ($realfile =~ m{^arch/}) {
5764 CHK("ARCH_INCLUDE_LINUX",
5765 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5767 WARN("INCLUDE_LINUX",
5768 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5774 # multi-statement macros should be enclosed in a do while loop, grab the
5775 # first statement and ensure its the whole macro if its not enclosed
5776 # in a known good container
5777 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5778 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5781 my ($off, $dstat, $dcond, $rest);
5783 my $has_flow_statement = 0;
5784 my $has_arg_concat = 0;
5785 ($dstat, $dcond, $ln, $cnt, $off) =
5786 ctx_statement_block($linenr, $realcnt, 0);
5788 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5789 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5791 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5792 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5794 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5795 my $define_args = $1;
5796 my $define_stmt = $dstat;
5799 if (defined $define_args && $define_args ne "") {
5800 $define_args = substr($define_args, 1, length($define_args) - 2);
5801 $define_args =~ s/\s*//g;
5802 $define_args =~ s/\\\+?//g;
5803 @def_args = split(",", $define_args);
5807 $dstat =~ s/\\\n.//g;
5808 $dstat =~ s/^\s*//s;
5809 $dstat =~ s/\s*$//s;
5811 # Flatten any parentheses and braces
5812 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5813 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5814 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5818 # Flatten any obvious string concatenation.
5819 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5820 $dstat =~ s/$Ident\s*($String)/$1/)
5824 # Make asm volatile uses seem like a generic function
5825 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5827 my $exceptions = qr{
5840 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5843 my $stmt_cnt = statement_rawlines($ctx);
5844 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5847 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5848 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5849 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5850 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5851 $dstat !~ /$exceptions/ &&
5852 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5853 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5854 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5855 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5856 $dstat !~ /^for\s*$Constant$/ && # for (...)
5857 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5858 $dstat !~ /^do\s*{/ && # do {...
5859 $dstat !~ /^\(\{/ && # ({...
5860 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5862 if ($dstat =~ /^\s*if\b/) {
5863 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5864 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5865 } elsif ($dstat =~ /;/) {
5866 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5867 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5869 ERROR("COMPLEX_MACRO",
5870 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5875 # Make $define_stmt single line, comment-free, etc
5876 my @stmt_array = split('\n', $define_stmt);
5879 foreach my $l (@stmt_array) {
5884 } elsif ($l =~ /^[\+ ]/) {
5885 $define_stmt .= substr($l, 1);
5888 $define_stmt =~ s/$;//g;
5889 $define_stmt =~ s/\s+/ /g;
5890 $define_stmt = trim($define_stmt);
5892 # check if any macro arguments are reused (ignore '...' and 'type')
5893 foreach my $arg (@def_args) {
5894 next if ($arg =~ /\.\.\./);
5895 next if ($arg =~ /^type$/i);
5896 my $tmp_stmt = $define_stmt;
5897 $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;
5898 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5899 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5900 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5902 CHK("MACRO_ARG_REUSE",
5903 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5905 # check if any macro arguments may have other precedence issues
5906 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5907 ((defined($1) && $1 ne ',') ||
5908 (defined($2) && $2 ne ','))) {
5909 CHK("MACRO_ARG_PRECEDENCE",
5910 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5914 # check for macros with flow control, but without ## concatenation
5915 # ## concatenation is commonly a macro that defines a function so ignore those
5916 if ($has_flow_statement && !$has_arg_concat) {
5917 my $cnt = statement_rawlines($ctx);
5918 my $herectx = get_stat_here($linenr, $cnt, $here);
5920 WARN("MACRO_WITH_FLOW_CONTROL",
5921 "Macros with flow control statements should be avoided\n" . "$herectx");
5924 # check for line continuations outside of #defines, preprocessor #, and asm
5927 if ($prevline !~ /^..*\\$/ &&
5928 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5929 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5930 $line =~ /^\+.*\\$/) {
5931 WARN("LINE_CONTINUATIONS",
5932 "Avoid unnecessary line continuations\n" . $herecurr);
5936 # do {} while (0) macro tests:
5937 # single-statement macros do not need to be enclosed in do while (0) loop,
5938 # macro should not end with a semicolon
5939 if ($perl_version_ok &&
5940 $realfile !~ m@/vmlinux.lds.h$@ &&
5941 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5944 my ($off, $dstat, $dcond, $rest);
5946 ($dstat, $dcond, $ln, $cnt, $off) =
5947 ctx_statement_block($linenr, $realcnt, 0);
5950 $dstat =~ s/\\\n.//g;
5953 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5958 my $cnt = statement_rawlines($ctx);
5959 my $herectx = get_stat_here($linenr, $cnt, $here);
5961 if (($stmts =~ tr/;/;/) == 1 &&
5962 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5963 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5964 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5966 if (defined $semis && $semis ne "") {
5967 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5968 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5970 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5972 my $cnt = statement_rawlines($ctx);
5973 my $herectx = get_stat_here($linenr, $cnt, $here);
5975 WARN("TRAILING_SEMICOLON",
5976 "macros should not use a trailing semicolon\n" . "$herectx");
5980 # check for redundant bracing round if etc
5981 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5982 my ($level, $endln, @chunks) =
5983 ctx_statement_full($linenr, $realcnt, 1);
5984 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5985 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5986 if ($#chunks > 0 && $level == 0) {
5990 my $herectx = $here . "\n";
5991 my $ln = $linenr - 1;
5992 for my $chunk (@chunks) {
5993 my ($cond, $block) = @{$chunk};
5995 # If the condition carries leading newlines, then count those as offsets.
5996 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5997 my $offset = statement_rawlines($whitespace) - 1;
5999 $allowed[$allow] = 0;
6000 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6002 # We have looked at and allowed this specific line.
6003 $suppress_ifbraces{$ln + $offset} = 1;
6005 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6006 $ln += statement_rawlines($block) - 1;
6008 substr($block, 0, length($cond), '');
6010 $seen++ if ($block =~ /^\s*{/);
6012 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6013 if (statement_lines($cond) > 1) {
6014 #print "APW: ALLOWED: cond<$cond>\n";
6015 $allowed[$allow] = 1;
6017 if ($block =~/\b(?:if|for|while)\b/) {
6018 #print "APW: ALLOWED: block<$block>\n";
6019 $allowed[$allow] = 1;
6021 if (statement_block_size($block) > 1) {
6022 #print "APW: ALLOWED: lines block<$block>\n";
6023 $allowed[$allow] = 1;
6028 my $sum_allowed = 0;
6029 foreach (@allowed) {
6032 if ($sum_allowed == 0) {
6034 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6035 } elsif ($sum_allowed != $allow &&
6038 "braces {} should be used on all arms of this statement\n" . $herectx);
6043 if (!defined $suppress_ifbraces{$linenr - 1} &&
6044 $line =~ /\b(if|while|for|else)\b/) {
6047 # Check the pre-context.
6048 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6049 #print "APW: ALLOWED: pre<$1>\n";
6053 my ($level, $endln, @chunks) =
6054 ctx_statement_full($linenr, $realcnt, $-[0]);
6056 # Check the condition.
6057 my ($cond, $block) = @{$chunks[0]};
6058 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6059 if (defined $cond) {
6060 substr($block, 0, length($cond), '');
6062 if (statement_lines($cond) > 1) {
6063 #print "APW: ALLOWED: cond<$cond>\n";
6066 if ($block =~/\b(?:if|for|while)\b/) {
6067 #print "APW: ALLOWED: block<$block>\n";
6070 if (statement_block_size($block) > 1) {
6071 #print "APW: ALLOWED: lines block<$block>\n";
6074 # Check the post-context.
6075 if (defined $chunks[1]) {
6076 my ($cond, $block) = @{$chunks[1]};
6077 if (defined $cond) {
6078 substr($block, 0, length($cond), '');
6080 if ($block =~ /^\s*\{/) {
6081 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6085 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6086 my $cnt = statement_rawlines($block);
6087 my $herectx = get_stat_here($linenr, $cnt, $here);
6090 "braces {} are not necessary for single statement blocks\n" . $herectx);
6094 # check for single line unbalanced braces
6095 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6096 $sline =~ /^.\s*else\s*\{\s*$/) {
6097 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6100 # check for unnecessary blank lines around braces
6101 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6103 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6104 $fix && $prevrawline =~ /^\+/) {
6105 fix_delete_line($fixlinenr - 1, $prevrawline);
6108 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6110 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6112 fix_delete_line($fixlinenr, $rawline);
6116 # no volatiles please
6117 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6118 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6120 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6123 # Check for user-visible strings broken across lines, which breaks the ability
6124 # to grep for the string. Make exceptions when the previous string ends in a
6125 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6126 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6127 if ($line =~ /^\+\s*$String/ &&
6128 $prevline =~ /"\s*$/ &&
6129 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6130 if (WARN("SPLIT_STRING",
6131 "quoted string split across lines\n" . $hereprev) &&
6133 $prevrawline =~ /^\+.*"\s*$/ &&
6134 $last_coalesced_string_linenr != $linenr - 1) {
6135 my $extracted_string = get_quoted_string($line, $rawline);
6136 my $comma_close = "";
6137 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6141 fix_delete_line($fixlinenr - 1, $prevrawline);
6142 fix_delete_line($fixlinenr, $rawline);
6143 my $fixedline = $prevrawline;
6144 $fixedline =~ s/"\s*$//;
6145 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6146 fix_insert_line($fixlinenr - 1, $fixedline);
6147 $fixedline = $rawline;
6148 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6149 if ($fixedline !~ /\+\s*$/) {
6150 fix_insert_line($fixlinenr, $fixedline);
6152 $last_coalesced_string_linenr = $linenr;
6156 # check for missing a space in a string concatenation
6157 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6158 WARN('MISSING_SPACE',
6159 "break quoted strings at a space character\n" . $hereprev);
6162 # check for an embedded function name in a string when the function is known
6163 # This does not work very well for -f --file checking as it depends on patch
6164 # context providing the function name or a single line form for in-file
6165 # function declarations
6166 if ($line =~ /^\+.*$String/ &&
6167 defined($context_function) &&
6168 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6169 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6170 WARN("EMBEDDED_FUNCTION_NAME",
6171 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6174 # check for unnecessary function tracing like uses
6175 # This does not use $logFunctions because there are many instances like
6176 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6177 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6178 if (WARN("TRACING_LOGGING",
6179 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6181 fix_delete_line($fixlinenr, $rawline);
6185 # check for spaces before a quoted newline
6186 if ($rawline =~ /^.*\".*\s\\n/) {
6187 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6188 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6190 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6195 # concatenated string without spaces between elements
6196 if ($line =~ /$String[A-Z_]/ ||
6197 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6198 if (CHK("CONCATENATED_STRING",
6199 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6201 while ($line =~ /($String)/g) {
6202 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6203 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6204 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6209 # uncoalesced string fragments
6210 if ($line =~ /$String\s*[Lu]?"/) {
6211 if (WARN("STRING_FRAGMENTS",
6212 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6214 while ($line =~ /($String)(?=\s*")/g) {
6215 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6216 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6221 # check for non-standard and hex prefixed decimal printf formats
6222 my $show_L = 1; #don't show the same defect twice
6224 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6225 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6226 $string =~ s/%%/__/g;
6228 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6230 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6234 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6236 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6239 # check for 0x<decimal>
6240 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6241 ERROR("PRINTF_0XDECIMAL",
6242 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6246 # check for line continuations in quoted strings with odd counts of "
6247 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6248 WARN("LINE_CONTINUATIONS",
6249 "Avoid line continuations in quoted strings\n" . $herecurr);
6253 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6255 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6259 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6261 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6264 # check for needless "if (<foo>) fn(<foo>)" uses
6265 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6266 my $tested = quotemeta($1);
6267 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6268 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6270 if (WARN('NEEDLESS_IF',
6271 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6274 my $leading_tabs = "";
6275 my $new_leading_tabs = "";
6276 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6281 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6282 $new_leading_tabs = $1;
6283 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6290 fix_delete_line($fixlinenr - 1, $prevrawline);
6291 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6297 # check for unnecessary "Out of Memory" messages
6298 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6299 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6300 (defined $1 || defined $3) &&
6303 my $testline = $lines[$linenr - 3];
6305 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6306 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6308 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6309 $s !~ /\b__GFP_NOWARN\b/ ) {
6311 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6315 # check for logging functions with KERN_<LEVEL>
6316 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6317 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6319 if (WARN("UNNECESSARY_KERN_LEVEL",
6320 "Possible unnecessary $level\n" . $herecurr) &&
6322 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6326 # check for logging continuations
6327 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6328 WARN("LOGGING_CONTINUATION",
6329 "Avoid logging continuation uses where feasible\n" . $herecurr);
6332 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6333 if (defined $stat &&
6334 $line =~ /\b$logFunctions\s*\(/ &&
6335 index($stat, '"') >= 0) {
6336 my $lc = $stat =~ tr@\n@@;
6337 $lc = $lc + $linenr;
6338 my $stat_real = get_stat_real($linenr, $lc);
6339 pos($stat_real) = index($stat_real, '"');
6340 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6343 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6344 if (WARN("UNNECESSARY_MODIFIER",
6345 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6346 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6349 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6354 # check for mask then right shift without a parentheses
6355 if ($perl_version_ok &&
6356 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6357 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6358 WARN("MASK_THEN_SHIFT",
6359 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6362 # check for pointer comparisons to NULL
6363 if ($perl_version_ok) {
6364 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6367 $equal = "" if ($4 eq "!=");
6368 if (CHK("COMPARISON_TO_NULL",
6369 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6371 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6376 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6377 if ($line =~ /(\b$InitAttribute\b)/) {
6379 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6382 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6383 ERROR("MISPLACED_INIT",
6384 "$attr should be placed after $var\n" . $herecurr)) ||
6385 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6386 WARN("MISPLACED_INIT",
6387 "$attr should be placed after $var\n" . $herecurr))) &&
6389 $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;
6394 # check for $InitAttributeData (ie: __initdata) with const
6395 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6397 $attr =~ /($InitAttributePrefix)(.*)/;
6398 my $attr_prefix = $1;
6400 if (ERROR("INIT_ATTRIBUTE",
6401 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6403 $fixed[$fixlinenr] =~
6404 s/$InitAttributeData/${attr_prefix}initconst/;
6408 # check for $InitAttributeConst (ie: __initconst) without const
6409 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6411 if (ERROR("INIT_ATTRIBUTE",
6412 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6414 my $lead = $fixed[$fixlinenr] =~
6415 /(^\+\s*(?:static\s+))/;
6417 $lead = "$lead " if ($lead !~ /^\+$/);
6418 $lead = "${lead}const ";
6419 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6423 # check for __read_mostly with const non-pointer (should just be const)
6424 if ($line =~ /\b__read_mostly\b/ &&
6425 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6426 if (ERROR("CONST_READ_MOSTLY",
6427 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6429 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6433 # don't use __constant_<foo> functions outside of include/uapi/
6434 if ($realfile !~ m@^include/uapi/@ &&
6435 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6436 my $constant_func = $1;
6437 my $func = $constant_func;
6438 $func =~ s/^__constant_//;
6439 if (WARN("CONSTANT_CONVERSION",
6440 "$constant_func should be $func\n" . $herecurr) &&
6442 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6446 # prefer usleep_range over udelay
6447 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6449 # ignore udelay's < 10, however
6450 if (! ($delay < 10) ) {
6452 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6454 if ($delay > 2000) {
6456 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6460 # warn about unexpectedly long msleep's
6461 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6464 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6468 # check for comparisons of jiffies
6469 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6470 WARN("JIFFIES_COMPARISON",
6471 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6474 # check for comparisons of get_jiffies_64()
6475 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6476 WARN("JIFFIES_COMPARISON",
6477 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6480 # warn about #ifdefs in C files
6481 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6482 # print "#ifdef in C files should be avoided\n";
6483 # print "$herecurr";
6487 # warn about spacing in #ifdefs
6488 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6489 if (ERROR("SPACING",
6490 "exactly one space required after that #$1\n" . $herecurr) &&
6492 $fixed[$fixlinenr] =~
6493 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6498 # check for spinlock_t definitions without a comment.
6499 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6500 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6502 if (!ctx_has_comment($first_line, $linenr)) {
6503 CHK("UNCOMMENTED_DEFINITION",
6504 "$1 definition without comment\n" . $herecurr);
6507 # check for memory barriers without a comment.
6514 my $barrier_stems = qr{
6522 my $all_barriers = qr{
6524 smp_(?:$barrier_stems)|
6525 virt_(?:$barrier_stems)
6528 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6529 if (!ctx_has_comment($first_line, $linenr)) {
6530 WARN("MEMORY_BARRIER",
6531 "memory barrier without comment\n" . $herecurr);
6535 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6537 if ($realfile !~ m@^include/asm-generic/@ &&
6538 $realfile !~ m@/barrier\.h$@ &&
6539 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6540 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6541 WARN("MEMORY_BARRIER",
6542 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6545 # check for waitqueue_active without a comment.
6546 if ($line =~ /\bwaitqueue_active\s*\(/) {
6547 if (!ctx_has_comment($first_line, $linenr)) {
6548 WARN("WAITQUEUE_ACTIVE",
6549 "waitqueue_active without comment\n" . $herecurr);
6553 # check for data_race without a comment.
6554 if ($line =~ /\bdata_race\s*\(/) {
6555 if (!ctx_has_comment($first_line, $linenr)) {
6557 "data_race without comment\n" . $herecurr);
6561 # check of hardware specific defines
6562 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6564 "architecture specific defines should be avoided\n" . $herecurr);
6567 # check that the storage class is not after a type
6568 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6569 WARN("STORAGE_CLASS",
6570 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6572 # Check that the storage class is at the beginning of a declaration
6573 if ($line =~ /\b$Storage\b/ &&
6574 $line !~ /^.\s*$Storage/ &&
6575 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6576 $1 !~ /[\,\)]\s*$/) {
6577 WARN("STORAGE_CLASS",
6578 "storage class should be at the beginning of the declaration\n" . $herecurr);
6581 # check the location of the inline attribute, that it is between
6582 # storage class and type.
6583 if ($line =~ /\b$Type\s+$Inline\b/ ||
6584 $line =~ /\b$Inline\s+$Storage\b/) {
6585 ERROR("INLINE_LOCATION",
6586 "inline keyword should sit between storage class and type\n" . $herecurr);
6589 # Check for __inline__ and __inline, prefer inline
6590 if ($realfile !~ m@\binclude/uapi/@ &&
6591 $line =~ /\b(__inline__|__inline)\b/) {
6593 "plain inline is preferred over $1\n" . $herecurr) &&
6595 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6600 # Check for compiler attributes
6601 if ($realfile !~ m@\binclude/uapi/@ &&
6602 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6604 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6607 "alias" => "__alias",
6608 "aligned" => "__aligned",
6609 "always_inline" => "__always_inline",
6610 "assume_aligned" => "__assume_aligned",
6612 "const" => "__attribute_const__",
6614 "designated_init" => "__designated_init",
6615 "externally_visible" => "__visible",
6616 "format" => "printf|scanf",
6617 "gnu_inline" => "__gnu_inline",
6618 "malloc" => "__malloc",
6620 "no_caller_saved_registers" => "__no_caller_saved_registers",
6621 "noclone" => "__noclone",
6622 "noinline" => "noinline",
6623 "nonstring" => "__nonstring",
6624 "noreturn" => "__noreturn",
6625 "packed" => "__packed",
6627 "section" => "__section",
6632 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6635 $params = $2 if defined($2);
6636 my $curr_attr = $orig_attr;
6637 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6638 if (exists($attr_list{$curr_attr})) {
6639 my $new = $attr_list{$curr_attr};
6640 if ($curr_attr eq "format" && $params) {
6641 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6644 $new = "$new$params";
6646 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6647 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6649 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6650 $fixed[$fixlinenr] =~ s/$remove//;
6651 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6652 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6653 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6658 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6659 if ($attr =~ /^_*unused/) {
6660 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6661 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6665 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6666 if ($perl_version_ok &&
6667 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6668 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6669 $line =~ /\b__weak\b/)) {
6670 ERROR("WEAK_DECLARATION",
6671 "Using weak declarations can have unintended link defects\n" . $herecurr);
6674 # check for c99 types like uint8_t used outside of uapi/ and tools/
6675 if ($realfile !~ m@\binclude/uapi/@ &&
6676 $realfile !~ m@\btools/@ &&
6677 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6679 if ($type =~ /\b($typeC99Typedefs)\b/) {
6681 my $kernel_type = 'u';
6682 $kernel_type = 's' if ($type =~ /^_*[si]/);
6685 if (CHK("PREFER_KERNEL_TYPES",
6686 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6688 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6693 # check for cast of C90 native int or longer types constants
6694 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6698 my $newconst = $const;
6699 $newconst =~ s/${Int_type}$//;
6700 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6701 if ($cast =~ /\blong\s+long\b/) {
6703 } elsif ($cast =~ /\blong\b/) {
6706 if (WARN("TYPECAST_INT_CONSTANT",
6707 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6709 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6713 # check for sizeof(&)
6714 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6715 WARN("SIZEOF_ADDRESS",
6716 "sizeof(& should be avoided\n" . $herecurr);
6719 # check for sizeof without parenthesis
6720 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6721 if (WARN("SIZEOF_PARENTHESIS",
6722 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6724 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6728 # check for struct spinlock declarations
6729 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6730 WARN("USE_SPINLOCK_T",
6731 "struct spinlock should be spinlock_t\n" . $herecurr);
6734 # check for seq_printf uses that could be seq_puts
6735 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6736 my $fmt = get_quoted_string($line, $rawline);
6739 if (WARN("PREFER_SEQ_PUTS",
6740 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6742 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6747 # check for vsprintf extension %p<foo> misuses
6748 if ($perl_version_ok &&
6750 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6751 $1 !~ /^_*volatile_*$/) {
6754 my $lc = $stat =~ tr@\n@@;
6755 $lc = $lc + $linenr;
6756 for (my $count = $linenr; $count <= $lc; $count++) {
6760 my $bad_specifier = "";
6761 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6764 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6768 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6769 ($extension eq "f" &&
6770 defined $qualifier && $qualifier !~ /^w/) ||
6771 ($extension eq "4" &&
6772 defined $qualifier && $qualifier !~ /^cc/)) {
6773 $bad_specifier = $specifier;
6776 if ($extension eq "x" && !defined($stat_real)) {
6777 if (!defined($stat_real)) {
6778 $stat_real = get_stat_real($linenr, $lc);
6780 WARN("VSPRINTF_SPECIFIER_PX",
6781 "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");
6784 if ($bad_specifier ne "") {
6785 my $stat_real = get_stat_real($linenr, $lc);
6786 my $ext_type = "Invalid";
6788 if ($bad_specifier =~ /p[Ff]/) {
6789 $use = " - use %pS instead";
6790 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6793 WARN("VSPRINTF_POINTER_EXTENSION",
6794 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6799 # Check for misused memsets
6800 if ($perl_version_ok &&
6802 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6808 if ($ms_size =~ /^(0x|)0$/i) {
6810 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6811 } elsif ($ms_size =~ /^(0x|)1$/i) {
6813 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6817 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6818 # if ($perl_version_ok &&
6820 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6821 # if (WARN("PREFER_ETHER_ADDR_COPY",
6822 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6824 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6828 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6829 # if ($perl_version_ok &&
6831 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6832 # WARN("PREFER_ETHER_ADDR_EQUAL",
6833 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6836 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6837 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6838 # if ($perl_version_ok &&
6840 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6844 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6845 # if (WARN("PREFER_ETH_ZERO_ADDR",
6846 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6848 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6850 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6851 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6852 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6854 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6859 # strlcpy uses that should likely be strscpy
6860 if ($line =~ /\bstrlcpy\s*\(/) {
6862 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6865 # typecasts on min/max could be min_t/max_t
6866 if ($perl_version_ok &&
6868 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6869 if (defined $2 || defined $7) {
6871 my $cast1 = deparenthesize($2);
6873 my $cast2 = deparenthesize($7);
6877 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6878 $cast = "$cast1 or $cast2";
6879 } elsif ($cast1 ne "") {
6885 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6889 # check usleep_range arguments
6890 if ($perl_version_ok &&
6892 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6896 WARN("USLEEP_RANGE",
6897 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6898 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6900 WARN("USLEEP_RANGE",
6901 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6905 # check for naked sscanf
6906 if ($perl_version_ok &&
6908 $line =~ /\bsscanf\b/ &&
6909 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6910 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6911 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6912 my $lc = $stat =~ tr@\n@@;
6913 $lc = $lc + $linenr;
6914 my $stat_real = get_stat_real($linenr, $lc);
6915 WARN("NAKED_SSCANF",
6916 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6919 # check for simple sscanf that should be kstrto<foo>
6920 if ($perl_version_ok &&
6922 $line =~ /\bsscanf\b/) {
6923 my $lc = $stat =~ tr@\n@@;
6924 $lc = $lc + $linenr;
6925 my $stat_real = get_stat_real($linenr, $lc);
6926 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6928 my $count = $format =~ tr@%@%@;
6930 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6931 WARN("SSCANF_TO_KSTRTO",
6932 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6937 # check for new externs in .h files.
6938 if ($realfile =~ /\.h$/ &&
6939 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6940 if (CHK("AVOID_EXTERNS",
6941 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6943 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6947 # check for new externs in .c files.
6948 if ($realfile =~ /\.c$/ && defined $stat &&
6949 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6951 my $function_name = $1;
6952 my $paren_space = $2;
6955 if (defined $cond) {
6956 substr($s, 0, length($cond), '');
6960 WARN("AVOID_EXTERNS",
6961 "externs should be avoided in .c files\n" . $herecurr);
6964 if ($paren_space =~ /\n/) {
6965 WARN("FUNCTION_ARGUMENTS",
6966 "arguments for function declarations should follow identifier\n" . $herecurr);
6969 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6970 $stat =~ /^.\s*extern\s+/)
6972 WARN("AVOID_EXTERNS",
6973 "externs should be avoided in .c files\n" . $herecurr);
6976 # check for function declarations that have arguments without identifier names
6977 if (defined $stat &&
6978 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6980 my $args = trim($1);
6981 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6983 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6984 WARN("FUNCTION_ARGUMENTS",
6985 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6990 # check for function definitions
6991 if ($perl_version_ok &&
6993 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6994 $context_function = $1;
6996 # check for multiline function definition with misplaced open brace
6998 my $cnt = statement_rawlines($stat);
6999 my $herectx = $here . "\n";
7000 for (my $n = 0; $n < $cnt; $n++) {
7001 my $rl = raw_line($linenr, $n);
7002 $herectx .= $rl . "\n";
7003 $ok = 1 if ($rl =~ /^[ \+]\{/);
7004 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7005 last if $rl =~ /^[ \+].*\{/;
7009 "open brace '{' following function definitions go on the next line\n" . $herectx);
7013 # checks for new __setup's
7014 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7017 if (!grep(/$name/, @setup_docs)) {
7018 CHK("UNDOCUMENTED_SETUP",
7019 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7023 # check for pointless casting of alloc functions
7024 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7025 WARN("UNNECESSARY_CASTS",
7026 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7030 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7031 if ($perl_version_ok &&
7032 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7033 CHK("ALLOC_SIZEOF_STRUCT",
7034 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7037 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7038 if ($perl_version_ok &&
7040 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7044 my $newfunc = "kmalloc_array";
7045 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7046 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7047 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7050 if ($a1 =~ /^sizeof\s*\S/) {
7054 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7055 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7056 my $cnt = statement_rawlines($stat);
7057 my $herectx = get_stat_here($linenr, $cnt, $here);
7059 if (WARN("ALLOC_WITH_MULTIPLY",
7060 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7063 $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;
7068 # check for krealloc arg reuse
7069 if ($perl_version_ok &&
7070 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7072 WARN("KREALLOC_ARG_REUSE",
7073 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7076 # check for alloc argument mismatch
7077 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7078 WARN("ALLOC_ARRAY_ARGS",
7079 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7082 # check for multiple semicolons
7083 if ($line =~ /;\s*;\s*$/) {
7084 if (WARN("ONE_SEMICOLON",
7085 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7087 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7091 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7092 if ($realfile !~ m@^include/uapi/@ &&
7093 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7095 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7096 if (CHK("BIT_MACRO",
7097 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7099 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7103 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7104 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7105 WARN("IS_ENABLED_CONFIG",
7106 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7109 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7110 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7112 if (WARN("PREFER_IS_ENABLED",
7113 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7115 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7119 # check for /* fallthrough */ like comment, prefer fallthrough;
7120 my @fallthroughs = (
7123 'lint -fallthrough[ \t]*',
7124 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7125 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7126 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7127 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7129 if ($raw_comment ne '') {
7130 foreach my $ft (@fallthroughs) {
7131 if ($raw_comment =~ /$ft/) {
7132 my $msg_level = \&WARN;
7133 $msg_level = \&CHK if ($file);
7134 &{$msg_level}("PREFER_FALLTHROUGH",
7135 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7141 # check for switch/default statements without a break;
7142 if ($perl_version_ok &&
7144 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7145 my $cnt = statement_rawlines($stat);
7146 my $herectx = get_stat_here($linenr, $cnt, $here);
7148 WARN("DEFAULT_NO_BREAK",
7149 "switch default: should use break\n" . $herectx);
7152 # check for gcc specific __FUNCTION__
7153 if ($line =~ /\b__FUNCTION__\b/) {
7154 if (WARN("USE_FUNC",
7155 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7157 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7161 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7162 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7164 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7167 # check for use of yield()
7168 if ($line =~ /\byield\s*\(\s*\)/) {
7170 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7173 # check for comparisons against true and false
7174 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7182 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7184 my $type = lc($otype);
7185 if ($type =~ /^(?:true|false)$/) {
7186 if (("$test" eq "==" && "$type" eq "true") ||
7187 ("$test" eq "!=" && "$type" eq "false")) {
7191 CHK("BOOL_COMPARISON",
7192 "Using comparison to $otype is error prone\n" . $herecurr);
7194 ## maybe suggesting a correct construct would better
7195 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7200 # check for semaphores initialized locked
7201 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7202 WARN("CONSIDER_COMPLETION",
7203 "consider using a completion\n" . $herecurr);
7206 # recommend kstrto* over simple_strto* and strict_strto*
7207 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7208 WARN("CONSIDER_KSTRTO",
7209 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7212 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7213 if ($line =~ /^.\s*__initcall\s*\(/) {
7214 WARN("USE_DEVICE_INITCALL",
7215 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7218 # check for spin_is_locked(), suggest lockdep instead
7219 if ($line =~ /\bspin_is_locked\(/) {
7221 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7224 # check for deprecated apis
7225 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7226 my $deprecated_api = $1;
7227 my $new_api = $deprecated_apis{$deprecated_api};
7228 WARN("DEPRECATED_API",
7229 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7232 # check for various structs that are normally const (ops, kgdb, device_tree)
7233 # and avoid what seem like struct definitions 'struct foo {'
7234 if (defined($const_structs) &&
7235 $line !~ /\bconst\b/ &&
7236 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7237 WARN("CONST_STRUCT",
7238 "struct $1 should normally be const\n" . $herecurr);
7241 # use of NR_CPUS is usually wrong
7242 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7243 # ignore designated initializers using NR_CPUS
7244 if ($line =~ /\bNR_CPUS\b/ &&
7245 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7246 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7247 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7248 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7249 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7250 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7253 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7256 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7257 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7258 ERROR("DEFINE_ARCH_HAS",
7259 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7262 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7263 if ($perl_version_ok &&
7264 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7265 WARN("LIKELY_MISUSE",
7266 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7269 # return sysfs_emit(foo, fmt, ...) fmt without newline
7270 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7271 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7272 my $offset = $+[6] - 1;
7273 if (WARN("SYSFS_EMIT",
7274 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7276 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7280 # nested likely/unlikely calls
7281 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7282 WARN("LIKELY_MISUSE",
7283 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7286 # whine mightly about in_atomic
7287 if ($line =~ /\bin_atomic\s*\(/) {
7288 if ($realfile =~ m@^drivers/@) {
7290 "do not use in_atomic in drivers\n" . $herecurr);
7291 } elsif ($realfile !~ m@^kernel/@) {
7293 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7297 # check for lockdep_set_novalidate_class
7298 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7299 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7300 if ($realfile !~ m@^kernel/lockdep@ &&
7301 $realfile !~ m@^include/linux/lockdep@ &&
7302 $realfile !~ m@^drivers/base/core@) {
7304 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7308 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7309 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7310 WARN("EXPORTED_WORLD_WRITABLE",
7311 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7314 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7315 # and whether or not function naming is typical and if
7316 # DEVICE_ATTR permissions uses are unusual too
7317 if ($perl_version_ok &&
7319 $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*\)/) {
7324 my $octal_perms = perms_to_octal($perms);
7325 if ($show =~ /^${var}_show$/ &&
7326 $store =~ /^${var}_store$/ &&
7327 $octal_perms eq "0644") {
7328 if (WARN("DEVICE_ATTR_RW",
7329 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7331 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7333 } elsif ($show =~ /^${var}_show$/ &&
7334 $store =~ /^NULL$/ &&
7335 $octal_perms eq "0444") {
7336 if (WARN("DEVICE_ATTR_RO",
7337 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7339 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7341 } elsif ($show =~ /^NULL$/ &&
7342 $store =~ /^${var}_store$/ &&
7343 $octal_perms eq "0200") {
7344 if (WARN("DEVICE_ATTR_WO",
7345 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7347 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7349 } elsif ($octal_perms eq "0644" ||
7350 $octal_perms eq "0444" ||
7351 $octal_perms eq "0200") {
7352 my $newshow = "$show";
7353 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7354 my $newstore = $store;
7355 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7357 if ($show ne $newshow) {
7358 $rename .= " '$show' to '$newshow'";
7360 if ($store ne $newstore) {
7361 $rename .= " '$store' to '$newstore'";
7363 WARN("DEVICE_ATTR_FUNCTIONS",
7364 "Consider renaming function(s)$rename\n" . $herecurr);
7366 WARN("DEVICE_ATTR_PERMS",
7367 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7371 # Mode permission misuses where it seems decimal should be octal
7372 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7373 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7374 # specific definition of not visible in sysfs.
7375 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7376 # use the default permissions
7377 if ($perl_version_ok &&
7379 $line =~ /$mode_perms_search/) {
7380 foreach my $entry (@mode_permission_funcs) {
7381 my $func = $entry->[0];
7382 my $arg_pos = $entry->[1];
7384 my $lc = $stat =~ tr@\n@@;
7385 $lc = $lc + $linenr;
7386 my $stat_real = get_stat_real($linenr, $lc);
7391 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7393 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7394 if ($stat =~ /$test/) {
7396 $val = $6 if ($skip_args ne "");
7397 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7398 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7399 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7400 ERROR("NON_OCTAL_PERMISSIONS",
7401 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7403 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7404 ERROR("EXPORTED_WORLD_WRITABLE",
7405 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7411 # check for uses of S_<PERMS> that could be octal for readability
7412 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7414 my $octal = perms_to_octal($oval);
7415 if (WARN("SYMBOLIC_PERMS",
7416 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7418 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7422 # validate content of MODULE_LICENSE against list from include/linux/module.h
7423 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7424 my $extracted_string = get_quoted_string($line, $rawline);
7425 my $valid_licenses = qr{
7428 GPL\ and\ additional\ rights|
7434 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7435 WARN("MODULE_LICENSE",
7436 "unknown module license " . $extracted_string . "\n" . $herecurr);
7438 if (!$file && $extracted_string eq '"GPL v2"') {
7439 if (WARN("MODULE_LICENSE",
7440 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7442 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7447 # check for sysctl duplicate constants
7448 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7449 WARN("DUPLICATED_SYSCTL_CONST",
7450 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7454 # If we have no input at all, then there is nothing to report on
7455 # so just keep quiet.
7456 if ($#rawlines == -1) {
7460 # In mailback mode only produce a report in the negative, for
7461 # things that appear to be patches.
7462 if ($mailback && ($clean == 1 || !$is_patch)) {
7466 # This is not a patch, and we are in 'no-patch' mode so
7468 if (!$chk_patch && !$is_patch) {
7472 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7473 ERROR("NOT_UNIFIED_DIFF",
7474 "Does not appear to be a unified-diff format patch\n");
7476 if ($is_patch && $has_commit_log && $chk_signoff) {
7477 if ($signoff == 0) {
7478 ERROR("MISSING_SIGN_OFF",
7479 "Missing Signed-off-by: line(s)\n");
7480 } elsif ($authorsignoff != 1) {
7481 # authorsignoff values:
7482 # 0 -> missing sign off
7483 # 1 -> sign off identical
7484 # 2 -> names and addresses match, comments mismatch
7485 # 3 -> addresses match, names different
7486 # 4 -> names match, addresses different
7487 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7489 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7491 if ($authorsignoff == 0) {
7492 ERROR("NO_AUTHOR_SIGN_OFF",
7493 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7494 } elsif ($authorsignoff == 2) {
7495 CHK("FROM_SIGN_OFF_MISMATCH",
7496 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7497 } elsif ($authorsignoff == 3) {
7498 WARN("FROM_SIGN_OFF_MISMATCH",
7499 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7500 } elsif ($authorsignoff == 4) {
7501 WARN("FROM_SIGN_OFF_MISMATCH",
7502 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7503 } elsif ($authorsignoff == 5) {
7504 WARN("FROM_SIGN_OFF_MISMATCH",
7505 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7510 print report_dump();
7511 if ($summary && !($clean == 1 && $quiet == 1)) {
7512 print "$filename " if ($summary_file);
7513 print "total: $cnt_error errors, $cnt_warn warnings, " .
7514 (($check)? "$cnt_chk checks, " : "") .
7515 "$cnt_lines lines checked\n";
7519 # If there were any defects found and not already fixing them
7520 if (!$clean and !$fix) {
7523 NOTE: For some of the reported defects, checkpatch may be able to
7524 mechanically convert to the typical style using --fix or --fix-inplace.
7527 # If there were whitespace errors which cleanpatch can fix
7528 # then suggest that.
7529 if ($rpt_cleaners) {
7533 NOTE: Whitespace errors detected.
7534 You may wish to use scripts/cleanpatch or scripts/cleanfile
7539 if ($clean == 0 && $fix &&
7540 ("@rawlines" ne "@fixed" ||
7541 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7542 my $newfile = $filename;
7543 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7547 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7549 open($f, '>', $newfile)
7550 or die "$P: Can't open $newfile for write\n";
7551 foreach my $fixed_line (@fixed) {
7554 if ($linecount > 3) {
7555 $fixed_line =~ s/^\+//;
7556 print $f $fixed_line . "\n";
7559 print $f $fixed_line . "\n";
7567 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7569 Do _NOT_ trust the results written to this file.
7570 Do _NOT_ submit these changes without inspecting them for correctness.
7572 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7573 No warranties, expressed or implied...
7581 print "$vname has no obvious style problems and is ready for submission.\n";
7583 print "$vname has style problems, please review.\n";