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_";
77 my %maybe_linker_symbol; # for externs in c exceptions, when seen in *vmlinux.lds.h
83 Usage: $P [OPTION]... [FILE]...
88 -v, --verbose verbose mode
89 --no-tree run without a kernel tree
90 --no-signoff do not check for 'Signed-off-by' line
91 --patch treat FILE as patchfile (default)
92 --emacs emacs compile window format
93 --terse one line per report
94 --showfile emit diffed file position, not input file position
95 -g, --git treat FILE as a single commit or git revision range
96 single git commit with:
100 multiple git commits with:
104 git merges are ignored
105 -f, --file treat FILE as regular source file
106 --subjective, --strict enable more subjective tests
107 --list-types list the possible message types
108 --types TYPE(,TYPE2...) show only these comma separated message types
109 --ignore TYPE(,TYPE2...) ignore various comma separated message types
110 --show-types show the specific message type in the output
111 --max-line-length=n set the maximum line length, (default $max_line_length)
112 if exceeded, warn on patches
113 requires --strict for use with --file
114 --min-conf-desc-length=n set the min description length, if shorter, warn
115 --tab-size=n set the number of spaces for tab (default $tabsize)
116 --root=PATH PATH to the kernel tree root
117 --no-summary suppress the per-file summary
118 --mailback only produce a report in case of warnings/errors
119 --summary-file include the filename in summary
120 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
121 'values', 'possible', 'type', and 'attr' (default
123 --test-only=WORD report only warnings/errors containing WORD
125 --fix EXPERIMENTAL - may create horrible results
126 If correctable single-line errors exist, create
127 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
128 with potential errors corrected to the preferred
130 --fix-inplace EXPERIMENTAL - may create horrible results
131 Is the same as --fix, but overwrites the input
132 file. It's your fault if there's no backup or git
133 --ignore-perl-version override checking of perl version. expect
135 --codespell Use the codespell dictionary for spelling/typos
136 (default:$codespellfile)
137 --codespellfile Use this codespell dictionary
138 --typedefsfile Read additional types from this file
139 --color[=WHEN] Use colors 'always', 'never', or only when output
140 is a terminal ('auto'). Default is 'auto'.
141 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
143 -h, --help, --version display this help and exit
145 When FILE is - read standard input.
153 return grep { !$seen{$_}++ } @_;
163 open(my $script, '<', abs_path($P)) or
164 die "$P: Can't read '$P' $!\n";
166 my $text = <$script>;
170 # Also catch when type or level is passed through a variable
171 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
173 if (exists($types{$2})) {
174 $types{$2} .= ",$1" if ($types{$2} ne $1);
179 $types{$2} = "UNDETERMINED";
183 print("#\tMessage type\n\n");
185 print(" ( Color coding: ");
186 print(RED . "ERROR" . RESET);
188 print(YELLOW . "WARNING" . RESET);
190 print(GREEN . "CHECK" . RESET);
192 print("Multiple levels / Undetermined");
196 foreach my $type (sort keys %types) {
197 my $orig_type = $type;
199 my $level = $types{$type};
200 if ($level eq "ERROR") {
201 $type = RED . $type . RESET;
202 } elsif ($level eq "WARN") {
203 $type = YELLOW . $type . RESET;
204 } elsif ($level eq "CHK") {
205 $type = GREEN . $type . RESET;
208 print(++$count . "\t" . $type . "\n");
209 if ($verbose && exists($verbose_messages{$orig_type})) {
210 my $message = $verbose_messages{$orig_type};
211 $message =~ s/\n/\n\t/g;
212 print("\t" . $message . "\n\n");
219 my $conf = which_conf($configuration_file);
222 open(my $conffile, '<', "$conf")
223 or warn "$P: Can't find a readable $configuration_file file $!\n";
225 while (<$conffile>) {
228 $line =~ s/\s*\n?$//g;
232 next if ($line =~ m/^\s*#/);
233 next if ($line =~ m/^\s*$/);
235 my @words = split(" ", $line);
236 foreach my $word (@words) {
237 last if ($word =~ m/^#/);
238 push (@conf_args, $word);
242 unshift(@ARGV, @conf_args) if @conf_args;
246 open(my $docs, '<', "$docsfile")
247 or warn "$P: Can't read the documentation file $docsfile $!\n";
258 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
260 $verbose_messages{$type} = trim($desc);
266 if ($line =~ /^(?:\s{4,}|$)/) {
271 $verbose_messages{$type} = trim($desc);
280 $verbose_messages{$type} = trim($desc);
285 # Perl's Getopt::Long allows options to take optional arguments after a space.
286 # Prevent --color by itself from consuming other arguments
288 if ($_ eq "--color" || $_ eq "-color") {
289 $_ = "--color=$color";
294 'q|quiet+' => \$quiet,
295 'v|verbose!' => \$verbose,
297 'signoff!' => \$chk_signoff,
298 'patch!' => \$chk_patch,
301 'showfile!' => \$showfile,
304 'subjective!' => \$check,
305 'strict!' => \$check,
306 'ignore=s' => \@ignore,
308 'show-types!' => \$show_types,
309 'list-types!' => \$list_types,
310 'max-line-length=i' => \$max_line_length,
311 'min-conf-desc-length=i' => \$min_conf_desc_length,
312 'tab-size=i' => \$tabsize,
314 'summary!' => \$summary,
315 'mailback!' => \$mailback,
316 'summary-file!' => \$summary_file,
318 'fix-inplace!' => \$fix_inplace,
319 'ignore-perl-version!' => \$ignore_perl_version,
320 'debug=s' => \%debug,
321 'test-only=s' => \$tst_only,
322 'codespell!' => \$codespell,
323 'codespellfile=s' => \$user_codespellfile,
324 'typedefsfile=s' => \$typedefsfile,
325 'color=s' => \$color,
326 'no-color' => \$color, #keep old behaviors of -nocolor
327 'nocolor' => \$color, #keep old behaviors of -nocolor
328 'kconfig-prefix=s' => \${CONFIG_},
333 if ($user_codespellfile) {
334 # Use the user provided codespell file unconditionally
335 $codespellfile = $user_codespellfile;
336 } elsif (!(-f $codespellfile)) {
337 # If /usr/share/codespell/dictionary.txt is not present, try to find it
338 # under codespell's install directory: <codespell_root>/data/dictionary.txt
339 if (($codespell || $help) && which("python3") ne "") {
340 my $python_codespell_dict = << "EOF";
344 codespell_dir = op.dirname(codespell_lib.__file__)
345 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
346 print(codespell_file, end='')
349 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
350 $codespellfile = $codespell_dict if (-f $codespell_dict);
354 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
355 # $help is 2 if invalid option is passed - exitcode: 1
356 help($help - 1) if ($help);
358 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
359 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
361 if ($color =~ /^[01]$/) {
363 } elsif ($color =~ /^always$/i) {
365 } elsif ($color =~ /^never$/i) {
367 } elsif ($color =~ /^auto$/i) {
368 $color = (-t STDOUT);
370 die "$P: Invalid color mode: $color\n";
373 load_docs() if ($verbose);
374 list_types(0) if ($list_types);
376 $fix = 1 if ($fix_inplace);
377 $check_orig = $check;
381 my $perl_version_ok = 1;
382 if ($^V && $^V lt $minimum_perl_version) {
383 $perl_version_ok = 0;
384 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
385 exit(1) if (!$ignore_perl_version);
388 #if no filenames are given, push '-' to read patch from stdin
393 # skip TAB size 1 to avoid additional checks on $tabsize - 1
394 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
396 sub hash_save_array_words {
397 my ($hashRef, $arrayRef) = @_;
399 my @array = split(/,/, join(',', @$arrayRef));
400 foreach my $word (@array) {
401 $word =~ s/\s*\n?$//g;
404 $word =~ tr/[a-z]/[A-Z]/;
406 next if ($word =~ m/^\s*#/);
407 next if ($word =~ m/^\s*$/);
413 sub hash_show_words {
414 my ($hashRef, $prefix) = @_;
416 if (keys %$hashRef) {
417 print "\nNOTE: $prefix message types:";
418 foreach my $word (sort keys %$hashRef) {
425 hash_save_array_words(\%ignore_type, \@ignore);
426 hash_save_array_words(\%use_type, \@use);
429 my $dbg_possible = 0;
432 for my $key (keys %debug) {
434 eval "\${dbg_$key} = '$debug{$key}';";
438 my $rpt_cleaners = 0;
447 if (!top_of_kernel_tree($root)) {
448 die "$P: $root: --root does not point at a valid tree\n";
451 if (top_of_kernel_tree('.')) {
453 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
454 top_of_kernel_tree($1)) {
459 if (!defined $root) {
460 print "Must be run from the top-level dir. of a kernel tree\n";
465 my $emitted_corrupt = 0;
468 [A-Za-z_][A-Za-z\d_]*
469 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
471 our $Storage = qr{extern|static|asmlinkage};
485 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
486 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
487 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
488 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
489 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
491 # Notes to $Attribute:
492 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
515 ____cacheline_aligned|
516 ____cacheline_aligned_in_smp|
517 ____cacheline_internodealigned_in_smp|
519 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
522 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
523 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
524 our $Lval = qr{$Ident(?:$Member)*};
526 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
527 our $Binary = qr{(?i)0b[01]+$Int_type?};
528 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
529 our $Int = qr{[0-9]+$Int_type?};
530 our $Octal = qr{0[0-7]+$Int_type?};
531 our $String = qr{(?:\b[Lu])?"[X\t]*"};
532 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
533 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
534 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
535 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
536 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
537 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
538 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
539 our $Arithmetic = qr{\+|-|\*|\/|%};
543 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
546 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
550 our $NonptrTypeMisordered;
551 our $NonptrTypeWithAttr;
555 our $DeclareMisordered;
557 our $NON_ASCII_UTF8 = qr{
558 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
559 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
560 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
561 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
562 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
563 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
564 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
568 [\x09\x0A\x0D\x20-\x7E] # ASCII
572 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
573 our $typeOtherOSTypedefs = qr{(?x:
574 u_(?:char|short|int|long) | # bsd
575 u(?:nchar|short|int|long) # sysv
577 our $typeKernelTypedefs = qr{(?x:
578 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
581 our $typeStdioTypedefs = qr{(?x:
584 our $typeTypedefs = qr{(?x:
586 $typeOtherOSTypedefs\b|
587 $typeKernelTypedefs\b|
591 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
593 our $logFunctions = qr{(?x:
594 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
595 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
597 WARN(?:_RATELIMIT|_ONCE|)|
600 seq_vprintf|seq_printf|seq_puts
603 our $allocFunctions = qr{(?x:
605 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
608 (?:\w+)?alloc_skb(?:_ip_align)? |
609 # dev_alloc_skb/netdev_alloc_skb, et al
613 our $signature_tags = qr{(?xi:
625 our @link_tags = qw(Link Closes);
627 #Create a search and print patterns for all these strings to be used directly below
628 our $link_tags_search = "";
629 our $link_tags_print = "";
630 foreach my $entry (@link_tags) {
631 if ($link_tags_search ne "") {
632 $link_tags_search .= '|';
633 $link_tags_print .= ' or ';
636 $link_tags_search .= $entry;
637 $link_tags_print .= "'$entry'";
639 $link_tags_search = "(?:${link_tags_search})";
641 our $tracing_logging_tags = qr{(?xi:
665 sub edit_distance_min {
667 my $len = scalar @arr;
668 if ((scalar @arr) < 1) {
669 # if underflow, return
673 for my $i (0 .. ($len-1)) {
674 if ($arr[$i] < $min) {
681 sub get_edit_distance {
682 my ($str1, $str2) = @_;
687 my $len1 = length($str1);
688 my $len2 = length($str2);
689 # two dimensional array storing minimum edit distance
691 for my $i (0 .. $len1) {
692 for my $j (0 .. $len2) {
694 $distance[$i][$j] = $j;
696 $distance[$i][$j] = $i;
697 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
698 $distance[$i][$j] = $distance[$i - 1][$j - 1];
700 my $dist1 = $distance[$i][$j - 1]; #insert distance
701 my $dist2 = $distance[$i - 1][$j]; # remove
702 my $dist3 = $distance[$i - 1][$j - 1]; #replace
703 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
707 return $distance[$len1][$len2];
710 sub find_standard_signature {
712 my @standard_signature_tags = (
713 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
714 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
716 foreach my $signature (@standard_signature_tags) {
717 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
723 our $obsolete_archives = qr{(?xi:
724 \Qfreedesktop.org/archives/dri-devel\E |
725 \Qlists.infradead.org\E |
727 \Qmail-archive.com\E |
728 \Qmailman.alsa-project.org/pipermail\E |
730 \Qozlabs.org/pipermail\E |
734 our @typeListMisordered = (
735 qr{char\s+(?:un)?signed},
736 qr{int\s+(?:(?:un)?signed\s+)?short\s},
737 qr{int\s+short(?:\s+(?:un)?signed)},
738 qr{short\s+int(?:\s+(?:un)?signed)},
739 qr{(?:un)?signed\s+int\s+short},
740 qr{short\s+(?:un)?signed},
741 qr{long\s+int\s+(?:un)?signed},
742 qr{int\s+long\s+(?:un)?signed},
743 qr{long\s+(?:un)?signed\s+int},
744 qr{int\s+(?:un)?signed\s+long},
745 qr{int\s+(?:un)?signed},
746 qr{int\s+long\s+long\s+(?:un)?signed},
747 qr{long\s+long\s+int\s+(?:un)?signed},
748 qr{long\s+long\s+(?:un)?signed\s+int},
749 qr{long\s+long\s+(?:un)?signed},
750 qr{long\s+(?:un)?signed},
755 qr{(?:(?:un)?signed\s+)?char},
756 qr{(?:(?:un)?signed\s+)?short\s+int},
757 qr{(?:(?:un)?signed\s+)?short},
758 qr{(?:(?:un)?signed\s+)?int},
759 qr{(?:(?:un)?signed\s+)?long\s+int},
760 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
761 qr{(?:(?:un)?signed\s+)?long\s+long},
762 qr{(?:(?:un)?signed\s+)?long},
771 qr{${Ident}_handler},
772 qr{${Ident}_handler_fn},
776 our $C90_int_types = qr{(?x:
777 long\s+long\s+int\s+(?:un)?signed|
778 long\s+long\s+(?:un)?signed\s+int|
779 long\s+long\s+(?:un)?signed|
780 (?:(?:un)?signed\s+)?long\s+long\s+int|
781 (?:(?:un)?signed\s+)?long\s+long|
782 int\s+long\s+long\s+(?:un)?signed|
783 int\s+(?:(?:un)?signed\s+)?long\s+long|
785 long\s+int\s+(?:un)?signed|
786 long\s+(?:un)?signed\s+int|
787 long\s+(?:un)?signed|
788 (?:(?:un)?signed\s+)?long\s+int|
789 (?:(?:un)?signed\s+)?long|
790 int\s+long\s+(?:un)?signed|
791 int\s+(?:(?:un)?signed\s+)?long|
794 (?:(?:un)?signed\s+)?int
797 our @typeListFile = ();
798 our @typeListWithAttr = (
800 qr{struct\s+$InitAttribute\s+$Ident},
801 qr{union\s+$InitAttribute\s+$Ident},
804 our @modifierList = (
807 our @modifierListFile = ();
809 our @mode_permission_funcs = (
811 ["module_param_(?:array|named|string)", 4],
812 ["module_param_array_named", 5],
813 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
814 ["proc_create(?:_data|)", 2],
815 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
816 ["IIO_DEV_ATTR_[A-Z_]+", 1],
817 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
818 ["SENSOR_TEMPLATE(?:_2|)", 3],
822 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
824 #Create a search pattern for all these functions to speed up a loop below
825 our $mode_perms_search = "";
826 foreach my $entry (@mode_permission_funcs) {
827 $mode_perms_search .= '|' if ($mode_perms_search ne "");
828 $mode_perms_search .= $entry->[0];
830 $mode_perms_search = "(?:${mode_perms_search})";
832 our %deprecated_apis = (
833 "synchronize_rcu_bh" => "synchronize_rcu",
834 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
835 "call_rcu_bh" => "call_rcu",
836 "rcu_barrier_bh" => "rcu_barrier",
837 "synchronize_sched" => "synchronize_rcu",
838 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
839 "call_rcu_sched" => "call_rcu",
840 "rcu_barrier_sched" => "rcu_barrier",
841 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
842 "cond_synchronize_sched" => "cond_synchronize_rcu",
843 "kmap" => "kmap_local_page",
844 "kunmap" => "kunmap_local",
845 "kmap_atomic" => "kmap_local_page",
846 "kunmap_atomic" => "kunmap_local",
849 #Create a search pattern for all these strings to speed up a loop below
850 our $deprecated_apis_search = "";
851 foreach my $entry (keys %deprecated_apis) {
852 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
853 $deprecated_apis_search .= $entry;
855 $deprecated_apis_search = "(?:${deprecated_apis_search})";
857 our $mode_perms_world_writable = qr{
865 our %mode_permission_string_types = (
884 #Create a search pattern for all these strings to speed up a loop below
885 our $mode_perms_string_search = "";
886 foreach my $entry (keys %mode_permission_string_types) {
887 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
888 $mode_perms_string_search .= $entry;
890 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
891 our $multi_mode_perms_string_search = qr{
892 ${single_mode_perms_string_search}
893 (?:\s*\|\s*${single_mode_perms_string_search})*
899 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
906 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
907 $curpos = pos($string);
910 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
912 $to |= $mode_permission_string_types{$match};
913 $val .= '\s*\|\s*' if ($val ne "");
917 $oval =~ s/^\s*\|\s*//;
918 $oval =~ s/\s*\|\s*$//;
919 return sprintf("%04o", $to);
922 our $allowed_asm_includes = qr{(?x:
928 # memory.h: ARM has a custom one
930 # Load common spelling mistakes and build regular expression list.
934 if (open(my $spelling, '<', $spelling_file)) {
935 while (<$spelling>) {
938 $line =~ s/\s*\n?$//g;
941 next if ($line =~ m/^\s*#/);
942 next if ($line =~ m/^\s*$/);
944 my ($suspect, $fix) = split(/\|\|/, $line);
946 $spelling_fix{$suspect} = $fix;
950 warn "No typos will be found - file '$spelling_file': $!\n";
954 if (open(my $spelling, '<', $codespellfile)) {
955 while (<$spelling>) {
958 $line =~ s/\s*\n?$//g;
961 next if ($line =~ m/^\s*#/);
962 next if ($line =~ m/^\s*$/);
963 next if ($line =~ m/, disabled/i);
967 my ($suspect, $fix) = split(/->/, $line);
969 $spelling_fix{$suspect} = $fix;
973 warn "No codespell typos will be found - file '$codespellfile': $!\n";
977 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
980 my ($wordsRef, $file) = @_;
982 if (open(my $words, '<', $file)) {
986 $line =~ s/\s*\n?$//g;
989 next if ($line =~ m/^\s*#/);
990 next if ($line =~ m/^\s*$/);
992 print("$file: '$line' invalid - ignored\n");
996 $$wordsRef .= '|' if (defined $$wordsRef);
1007 if (show_type("CONST_STRUCT")) {
1008 read_words(\$const_structs, $conststructsfile)
1009 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1012 if (defined($typedefsfile)) {
1013 my $typeOtherTypedefs;
1014 read_words(\$typeOtherTypedefs, $typedefsfile)
1015 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
1016 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1020 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1021 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1022 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
1023 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1024 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1026 (?:$typeTypedefs\b)|
1030 (?:$Modifier\s+|const\s+)*
1032 (?:typeof|__typeof__)\s*\([^\)]*\)|
1033 (?:$typeTypedefs\b)|
1036 (?:\s+$Modifier|\s+const)*
1038 $NonptrTypeMisordered = qr{
1039 (?:$Modifier\s+|const\s+)*
1043 (?:\s+$Modifier|\s+const)*
1045 $NonptrTypeWithAttr = qr{
1046 (?:$Modifier\s+|const\s+)*
1048 (?:typeof|__typeof__)\s*\([^\)]*\)|
1049 (?:$typeTypedefs\b)|
1050 (?:${allWithAttr}\b)
1052 (?:\s+$Modifier|\s+const)*
1056 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1057 (?:\s+$Inline|\s+$Modifier)*
1059 $TypeMisordered = qr{
1060 $NonptrTypeMisordered
1061 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1062 (?:\s+$Inline|\s+$Modifier)*
1064 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1065 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1069 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1071 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1072 # requires at least perl version v5.10.0
1073 # Any use must be runtime checked with $^V
1075 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1076 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1077 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1079 our $declaration_macros = qr{(?x:
1080 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1081 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1082 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1083 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1086 our %allow_repeated_words = (
1093 sub deparenthesize {
1095 return "" if (!defined($string));
1097 while ($string =~ /^\s*\(.*\)\s*$/) {
1098 $string =~ s@^\s*\(\s*@@;
1099 $string =~ s@\s*\)\s*$@@;
1102 $string =~ s@\s+@ @g;
1107 sub seed_camelcase_file {
1110 return if (!(-f $file));
1114 open(my $include_file, '<', "$file")
1115 or warn "$P: Can't read '$file' $!\n";
1116 my $text = <$include_file>;
1117 close($include_file);
1119 my @lines = split('\n', $text);
1121 foreach my $line (@lines) {
1122 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1123 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1125 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1127 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1133 our %maintained_status = ();
1135 sub is_maintained_obsolete {
1136 my ($filename) = @_;
1138 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1140 if (!exists($maintained_status{$filename})) {
1141 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1144 return $maintained_status{$filename} =~ /obsolete/i;
1147 sub is_SPDX_License_valid {
1150 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1152 my $root_path = abs_path($root);
1153 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1154 return 0 if ($status ne "");
1158 my $camelcase_seeded = 0;
1159 sub seed_camelcase_includes {
1160 return if ($camelcase_seeded);
1163 my $camelcase_cache = "";
1164 my @include_files = ();
1166 $camelcase_seeded = 1;
1168 if (-e "$gitroot") {
1169 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1170 chomp $git_last_include_commit;
1171 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1173 my $last_mod_date = 0;
1174 $files = `find $root/include -name "*.h"`;
1175 @include_files = split('\n', $files);
1176 foreach my $file (@include_files) {
1177 my $date = POSIX::strftime("%Y%m%d%H%M",
1178 localtime((stat $file)[9]));
1179 $last_mod_date = $date if ($last_mod_date < $date);
1181 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1184 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1185 open(my $camelcase_file, '<', "$camelcase_cache")
1186 or warn "$P: Can't read '$camelcase_cache' $!\n";
1187 while (<$camelcase_file>) {
1191 close($camelcase_file);
1196 if (-e "$gitroot") {
1197 $files = `${git_command} ls-files "include/*.h"`;
1198 @include_files = split('\n', $files);
1201 foreach my $file (@include_files) {
1202 seed_camelcase_file($file);
1205 if ($camelcase_cache ne "") {
1206 unlink glob ".checkpatch-camelcase.*";
1207 open(my $camelcase_file, '>', "$camelcase_cache")
1208 or warn "$P: Can't write '$camelcase_cache' $!\n";
1209 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1210 print $camelcase_file ("$_\n");
1212 close($camelcase_file);
1216 sub git_is_single_file {
1217 my ($filename) = @_;
1219 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1221 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1222 my $count = $output =~ tr/\n//;
1223 return $count eq 1 && $output =~ m{^${filename}$};
1226 sub git_commit_info {
1227 my ($commit, $id, $desc) = @_;
1229 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1231 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1232 $output =~ s/^\s*//gm;
1233 my @lines = split("\n", $output);
1235 return ($id, $desc) if ($#lines < 0);
1237 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1238 # Maybe one day convert this block of bash into something that returns
1239 # all matching commit ids, but it's very slow...
1241 # echo "checking commits $1..."
1242 # git rev-list --remotes | grep -i "^$1" |
1243 # while read line ; do
1244 # git log --format='%H %s' -1 $line |
1245 # echo "commit $(cut -c 1-12,41-)"
1247 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1248 $lines[0] =~ /^fatal: bad object $commit/) {
1251 $id = substr($lines[0], 0, 12);
1252 $desc = substr($lines[0], 41);
1255 return ($id, $desc);
1258 $chk_signoff = 0 if ($file);
1263 my @fixed_inserted = ();
1264 my @fixed_deleted = ();
1267 # If input is git commits, extract all commits from the commit expressions.
1268 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1269 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1273 foreach my $commit_expr (@ARGV) {
1275 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1276 $git_range = "-$2 $1";
1277 } elsif ($commit_expr =~ m/\.\./) {
1278 $git_range = "$commit_expr";
1280 $git_range = "-1 $commit_expr";
1282 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1283 foreach my $line (split(/\n/, $lines)) {
1284 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1285 next if (!defined($1) || !defined($2));
1288 unshift(@commits, $sha1);
1289 $git_commits{$sha1} = $subject;
1292 die "$P: no git commits after extraction!\n" if (@commits == 0);
1297 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1298 for my $filename (@ARGV) {
1300 my $is_git_file = git_is_single_file($filename);
1301 my $oldfile = $file;
1302 $file = 1 if ($is_git_file);
1304 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1305 die "$P: $filename: git format-patch failed - $!\n";
1307 open($FILE, '-|', "diff -u /dev/null $filename") ||
1308 die "$P: $filename: diff failed - $!\n";
1309 } elsif ($filename eq '-') {
1310 open($FILE, '<&STDIN');
1312 open($FILE, '<', "$filename") ||
1313 die "$P: $filename: open failed - $!\n";
1315 if ($filename eq '-') {
1316 $vname = 'Your patch';
1318 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1324 push(@rawlines, $_);
1325 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1329 if ($#ARGV > 0 && $quiet == 0) {
1330 print '-' x length($vname) . "\n";
1332 print '-' x length($vname) . "\n";
1335 if (!process($filename)) {
1341 @fixed_inserted = ();
1342 @fixed_deleted = ();
1344 @modifierListFile = ();
1347 $file = $oldfile if ($is_git_file);
1351 hash_show_words(\%use_type, "Used");
1352 hash_show_words(\%ignore_type, "Ignored");
1354 if (!$perl_version_ok) {
1357 NOTE: perl $^V is not modern enough to detect all possible issues.
1358 An upgrade to at least perl $minimum_perl_version is suggested.
1364 NOTE: If any of the errors are false positives, please report
1365 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1372 sub top_of_kernel_tree {
1376 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1377 "README", "Documentation", "arch", "include", "drivers",
1378 "fs", "init", "ipc", "kernel", "lib", "scripts",
1381 foreach my $check (@tree_check) {
1382 if (! -e $root . '/' . $check) {
1390 my ($formatted_email) = @_;
1394 my $name_comment = "";
1398 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1401 $comment = $3 if defined $3;
1402 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1404 $comment = $2 if defined $2;
1405 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1407 $comment = $2 if defined $2;
1408 $formatted_email =~ s/\Q$address\E.*$//;
1409 $name = $formatted_email;
1410 $name = trim($name);
1411 $name =~ s/^\"|\"$//g;
1412 # If there's a name left after stripping spaces and
1413 # leading quotes, and the address doesn't have both
1414 # leading and trailing angle brackets, the address
1416 # "joe smith joe@smith.com" bad
1417 # "joe smith <joe@smith.com" bad
1418 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1425 # Extract comments from names excluding quoted parts
1426 # "John D. (Doe)" - Do not extract
1427 if ($name =~ s/\"(.+)\"//) {
1430 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1431 $name_comment .= trim($1);
1433 $name =~ s/^[ \"]+|[ \"]+$//g;
1434 $name = trim("$quoted $name");
1436 $address = trim($address);
1437 $address =~ s/^\<|\>$//g;
1438 $comment = trim($comment);
1440 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1441 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1442 $name = "\"$name\"";
1445 return ($name, $name_comment, $address, $comment);
1449 my ($name, $name_comment, $address, $comment) = @_;
1451 my $formatted_email;
1453 $name =~ s/^[ \"]+|[ \"]+$//g;
1454 $address = trim($address);
1455 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1457 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1458 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1459 $name = "\"$name\"";
1462 $name_comment = trim($name_comment);
1463 $name_comment = " $name_comment" if ($name_comment ne "");
1464 $comment = trim($comment);
1465 $comment = " $comment" if ($comment ne "");
1467 if ("$name" eq "") {
1468 $formatted_email = "$address";
1470 $formatted_email = "$name$name_comment <$address>";
1472 $formatted_email .= "$comment";
1473 return $formatted_email;
1476 sub reformat_email {
1479 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1480 return format_email($email_name, $name_comment, $email_address, $comment);
1483 sub same_email_addresses {
1484 my ($email1, $email2) = @_;
1486 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1487 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1489 return $email1_name eq $email2_name &&
1490 $email1_address eq $email2_address &&
1491 $name1_comment eq $name2_comment &&
1492 $comment1 eq $comment2;
1498 foreach my $path (split(/:/, $ENV{PATH})) {
1499 if (-e "$path/$bin") {
1500 return "$path/$bin";
1510 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1511 if (-e "$path/$conf") {
1512 return "$path/$conf";
1524 for my $c (split(//, $str)) {
1528 for (; ($n % $tabsize) != 0; $n++) {
1540 (my $res = shift) =~ tr/\t/ /c;
1547 # Drop the diff line leader and expand tabs
1549 $line = expand_tabs($line);
1551 # Pick the indent from the front of the line.
1552 my ($white) = ($line =~ /^(\s*)/);
1554 return (length($line), length($white));
1557 my $sanitise_quote = '';
1559 sub sanitise_line_reset {
1560 my ($in_comment) = @_;
1563 $sanitise_quote = '*/';
1565 $sanitise_quote = '';
1578 # Always copy over the diff marker.
1579 $res = substr($line, 0, 1);
1581 for ($off = 1; $off < length($line); $off++) {
1582 $c = substr($line, $off, 1);
1584 # Comments we are whacking completely including the begin
1585 # and end, all to $;.
1586 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1587 $sanitise_quote = '*/';
1589 substr($res, $off, 2, "$;$;");
1593 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1594 $sanitise_quote = '';
1595 substr($res, $off, 2, "$;$;");
1599 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1600 $sanitise_quote = '//';
1602 substr($res, $off, 2, $sanitise_quote);
1607 # A \ in a string means ignore the next character.
1608 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1610 substr($res, $off, 2, 'XX');
1615 if ($c eq "'" || $c eq '"') {
1616 if ($sanitise_quote eq '') {
1617 $sanitise_quote = $c;
1619 substr($res, $off, 1, $c);
1621 } elsif ($sanitise_quote eq $c) {
1622 $sanitise_quote = '';
1626 #print "c<$c> SQ<$sanitise_quote>\n";
1627 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1628 substr($res, $off, 1, $;);
1629 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1630 substr($res, $off, 1, $;);
1631 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1632 substr($res, $off, 1, 'X');
1634 substr($res, $off, 1, $c);
1638 if ($sanitise_quote eq '//') {
1639 $sanitise_quote = '';
1642 # The pathname on a #include may be surrounded by '<' and '>'.
1643 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1644 my $clean = 'X' x length($1);
1645 $res =~ s@\<.*\>@<$clean>@;
1647 # The whole of a #error is a string.
1648 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1649 my $clean = 'X' x length($1);
1650 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1653 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1655 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1661 sub get_quoted_string {
1662 my ($line, $rawline) = @_;
1664 return "" if (!defined($line) || !defined($rawline));
1665 return "" if ($line !~ m/($String)/g);
1666 return substr($rawline, $-[0], $+[0] - $-[0]);
1669 sub ctx_statement_block {
1670 my ($linenr, $remain, $off) = @_;
1671 my $line = $linenr - 1;
1674 my $coff = $off - 1;
1688 @stack = (['', 0]) if ($#stack == -1);
1690 #warn "CSB: blk<$blk> remain<$remain>\n";
1691 # If we are about to drop off the end, pull in more
1694 for (; $remain > 0; $line++) {
1695 last if (!defined $lines[$line]);
1696 next if ($lines[$line] =~ /^-/);
1699 $blk .= $lines[$line] . "\n";
1700 $len = length($blk);
1704 # Bail if there is no further context.
1705 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1709 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1715 $c = substr($blk, $off, 1);
1716 $remainder = substr($blk, $off);
1718 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1720 # Handle nested #if/#else.
1721 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1722 push(@stack, [ $type, $level ]);
1723 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1724 ($type, $level) = @{$stack[$#stack - 1]};
1725 } elsif ($remainder =~ /^#\s*endif\b/) {
1726 ($type, $level) = @{pop(@stack)};
1729 # Statement ends at the ';' or a close '}' at the
1731 if ($level == 0 && $c eq ';') {
1735 # An else is really a conditional as long as its not else if
1736 if ($level == 0 && $coff_set == 0 &&
1737 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1738 $remainder =~ /^(else)(?:\s|{)/ &&
1739 $remainder !~ /^else\s+if\b/) {
1740 $coff = $off + length($1) - 1;
1742 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1743 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1746 if (($type eq '' || $type eq '(') && $c eq '(') {
1750 if ($type eq '(' && $c eq ')') {
1752 $type = ($level != 0)? '(' : '';
1754 if ($level == 0 && $coff < $soff) {
1757 #warn "CSB: mark coff<$coff>\n";
1760 if (($type eq '' || $type eq '{') && $c eq '{') {
1764 if ($type eq '{' && $c eq '}') {
1766 $type = ($level != 0)? '{' : '';
1769 if (substr($blk, $off + 1, 1) eq ';') {
1775 # Preprocessor commands end at the newline unless escaped.
1776 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1784 # We are truly at the end, so shuffle to the next line.
1791 my $statement = substr($blk, $soff, $off - $soff + 1);
1792 my $condition = substr($blk, $soff, $coff - $soff + 1);
1794 #warn "STATEMENT<$statement>\n";
1795 #warn "CONDITION<$condition>\n";
1797 #print "coff<$coff> soff<$off> loff<$loff>\n";
1799 return ($statement, $condition,
1800 $line, $remain + 1, $off - $loff + 1, $level);
1803 sub statement_lines {
1806 # Strip the diff line prefixes and rip blank lines at start and end.
1807 $stmt =~ s/(^|\n)./$1/g;
1811 my @stmt_lines = ($stmt =~ /\n/g);
1813 return $#stmt_lines + 2;
1816 sub statement_rawlines {
1819 my @stmt_lines = ($stmt =~ /\n/g);
1821 return $#stmt_lines + 2;
1824 sub statement_block_size {
1827 $stmt =~ s/(^|\n)./$1/g;
1833 my @stmt_lines = ($stmt =~ /\n/g);
1834 my @stmt_statements = ($stmt =~ /;/g);
1836 my $stmt_lines = $#stmt_lines + 2;
1837 my $stmt_statements = $#stmt_statements + 1;
1839 if ($stmt_lines > $stmt_statements) {
1842 return $stmt_statements;
1846 sub ctx_statement_full {
1847 my ($linenr, $remain, $off) = @_;
1848 my ($statement, $condition, $level);
1852 # Grab the first conditional/block pair.
1853 ($statement, $condition, $linenr, $remain, $off, $level) =
1854 ctx_statement_block($linenr, $remain, $off);
1855 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1856 push(@chunks, [ $condition, $statement ]);
1857 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1858 return ($level, $linenr, @chunks);
1861 # Pull in the following conditional/block pairs and see if they
1862 # could continue the statement.
1864 ($statement, $condition, $linenr, $remain, $off, $level) =
1865 ctx_statement_block($linenr, $remain, $off);
1866 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1867 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1869 push(@chunks, [ $condition, $statement ]);
1872 return ($level, $linenr, @chunks);
1876 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1878 my $start = $linenr - 1;
1885 my @stack = ($level);
1886 for ($line = $start; $remain > 0; $line++) {
1887 next if ($rawlines[$line] =~ /^-/);
1890 $blk .= $rawlines[$line];
1892 # Handle nested #if/#else.
1893 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1894 push(@stack, $level);
1895 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1896 $level = $stack[$#stack - 1];
1897 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1898 $level = pop(@stack);
1901 foreach my $c (split(//, $lines[$line])) {
1902 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1908 if ($c eq $close && $level > 0) {
1910 last if ($level == 0);
1911 } elsif ($c eq $open) {
1916 if (!$outer || $level <= 1) {
1917 push(@res, $rawlines[$line]);
1920 last if ($level == 0);
1923 return ($level, @res);
1925 sub ctx_block_outer {
1926 my ($linenr, $remain) = @_;
1928 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1932 my ($linenr, $remain) = @_;
1934 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1938 my ($linenr, $remain, $off) = @_;
1940 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1943 sub ctx_block_level {
1944 my ($linenr, $remain) = @_;
1946 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1948 sub ctx_statement_level {
1949 my ($linenr, $remain, $off) = @_;
1951 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1954 sub ctx_locate_comment {
1955 my ($first_line, $end_line) = @_;
1957 # If c99 comment on the current line, or the line before or after
1958 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1959 return $current_comment if (defined $current_comment);
1960 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1961 return $current_comment if (defined $current_comment);
1962 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1963 return $current_comment if (defined $current_comment);
1965 # Catch a comment on the end of the line itself.
1966 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1967 return $current_comment if (defined $current_comment);
1969 # Look through the context and try and figure out if there is a
1972 $current_comment = '';
1973 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1974 my $line = $rawlines[$linenr - 1];
1976 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1979 if ($line =~ m@/\*@) {
1982 if (!$in_comment && $current_comment ne '') {
1983 $current_comment = '';
1985 $current_comment .= $line . "\n" if ($in_comment);
1986 if ($line =~ m@\*/@) {
1991 chomp($current_comment);
1992 return($current_comment);
1994 sub ctx_has_comment {
1995 my ($first_line, $end_line) = @_;
1996 my $cmt = ctx_locate_comment($first_line, $end_line);
1998 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1999 ##print "CMMT: $cmt\n";
2001 return ($cmt ne '');
2005 my ($linenr, $cnt) = @_;
2007 my $offset = $linenr - 1;
2012 $line = $rawlines[$offset++];
2013 next if (defined($line) && $line =~ /^-/);
2021 my ($linenr, $lc) = @_;
2023 my $stat_real = raw_line($linenr, 0);
2024 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2025 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2032 my ($linenr, $cnt, $here) = @_;
2034 my $herectx = $here . "\n";
2035 for (my $n = 0; $n < $cnt; $n++) {
2036 $herectx .= raw_line($linenr, $n) . "\n";
2047 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2050 $coded = sprintf("^%c", unpack('C', $2) + 64);
2059 my $av_preprocessor = 0;
2064 sub annotate_reset {
2065 $av_preprocessor = 0;
2067 @av_paren_type = ('E');
2068 $av_pend_colon = 'O';
2071 sub annotate_values {
2072 my ($stream, $type) = @_;
2075 my $var = '_' x length($stream);
2078 print "$stream\n" if ($dbg_values > 1);
2080 while (length($cur)) {
2081 @av_paren_type = ('E') if ($#av_paren_type < 0);
2082 print " <" . join('', @av_paren_type) .
2083 "> <$type> <$av_pending>" if ($dbg_values > 1);
2084 if ($cur =~ /^(\s+)/o) {
2085 print "WS($1)\n" if ($dbg_values > 1);
2086 if ($1 =~ /\n/ && $av_preprocessor) {
2087 $type = pop(@av_paren_type);
2088 $av_preprocessor = 0;
2091 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2092 print "CAST($1)\n" if ($dbg_values > 1);
2093 push(@av_paren_type, $type);
2096 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2097 print "DECLARE($1)\n" if ($dbg_values > 1);
2100 } elsif ($cur =~ /^($Modifier)\s*/) {
2101 print "MODIFIER($1)\n" if ($dbg_values > 1);
2104 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2105 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2106 $av_preprocessor = 1;
2107 push(@av_paren_type, $type);
2113 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2114 print "UNDEF($1)\n" if ($dbg_values > 1);
2115 $av_preprocessor = 1;
2116 push(@av_paren_type, $type);
2118 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2119 print "PRE_START($1)\n" if ($dbg_values > 1);
2120 $av_preprocessor = 1;
2122 push(@av_paren_type, $type);
2123 push(@av_paren_type, $type);
2126 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2127 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2128 $av_preprocessor = 1;
2130 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2134 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2135 print "PRE_END($1)\n" if ($dbg_values > 1);
2137 $av_preprocessor = 1;
2139 # Assume all arms of the conditional end as this
2140 # one does, and continue as if the #endif was not here.
2141 pop(@av_paren_type);
2142 push(@av_paren_type, $type);
2145 } elsif ($cur =~ /^(\\\n)/o) {
2146 print "PRECONT($1)\n" if ($dbg_values > 1);
2148 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2149 print "ATTR($1)\n" if ($dbg_values > 1);
2150 $av_pending = $type;
2153 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2154 print "SIZEOF($1)\n" if ($dbg_values > 1);
2160 } elsif ($cur =~ /^(if|while|for)\b/o) {
2161 print "COND($1)\n" if ($dbg_values > 1);
2165 } elsif ($cur =~/^(case)/o) {
2166 print "CASE($1)\n" if ($dbg_values > 1);
2167 $av_pend_colon = 'C';
2170 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2171 print "KEYWORD($1)\n" if ($dbg_values > 1);
2174 } elsif ($cur =~ /^(\()/o) {
2175 print "PAREN('$1')\n" if ($dbg_values > 1);
2176 push(@av_paren_type, $av_pending);
2180 } elsif ($cur =~ /^(\))/o) {
2181 my $new_type = pop(@av_paren_type);
2182 if ($new_type ne '_') {
2184 print "PAREN('$1') -> $type\n"
2185 if ($dbg_values > 1);
2187 print "PAREN('$1')\n" if ($dbg_values > 1);
2190 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2191 print "FUNC($1)\n" if ($dbg_values > 1);
2195 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2196 if (defined $2 && $type eq 'C' || $type eq 'T') {
2197 $av_pend_colon = 'B';
2198 } elsif ($type eq 'E') {
2199 $av_pend_colon = 'L';
2201 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2204 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2205 print "IDENT($1)\n" if ($dbg_values > 1);
2208 } elsif ($cur =~ /^($Assignment)/o) {
2209 print "ASSIGN($1)\n" if ($dbg_values > 1);
2212 } elsif ($cur =~/^(;|{|})/) {
2213 print "END($1)\n" if ($dbg_values > 1);
2215 $av_pend_colon = 'O';
2217 } elsif ($cur =~/^(,)/) {
2218 print "COMMA($1)\n" if ($dbg_values > 1);
2221 } elsif ($cur =~ /^(\?)/o) {
2222 print "QUESTION($1)\n" if ($dbg_values > 1);
2225 } elsif ($cur =~ /^(:)/o) {
2226 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2228 substr($var, length($res), 1, $av_pend_colon);
2229 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2234 $av_pend_colon = 'O';
2236 } elsif ($cur =~ /^(\[)/o) {
2237 print "CLOSE($1)\n" if ($dbg_values > 1);
2240 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2243 print "OPV($1)\n" if ($dbg_values > 1);
2250 substr($var, length($res), 1, $variant);
2253 } elsif ($cur =~ /^($Operators)/o) {
2254 print "OP($1)\n" if ($dbg_values > 1);
2255 if ($1 ne '++' && $1 ne '--') {
2259 } elsif ($cur =~ /(^.)/o) {
2260 print "C($1)\n" if ($dbg_values > 1);
2263 $cur = substr($cur, length($1));
2264 $res .= $type x length($1);
2268 return ($res, $var);
2272 my ($possible, $line) = @_;
2273 my $notPermitted = qr{(?:
2290 ^(?:typedef|struct|enum)\b
2292 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2293 if ($possible !~ $notPermitted) {
2294 # Check for modifiers.
2295 $possible =~ s/\s*$Storage\s*//g;
2296 $possible =~ s/\s*$Sparse\s*//g;
2297 if ($possible =~ /^\s*$/) {
2299 } elsif ($possible =~ /\s/) {
2300 $possible =~ s/\s*$Type\s*//g;
2301 for my $modifier (split(' ', $possible)) {
2302 if ($modifier !~ $notPermitted) {
2303 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2304 push(@modifierListFile, $modifier);
2309 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2310 push(@typeListFile, $possible);
2314 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2323 $type =~ tr/[a-z]/[A-Z]/;
2325 return defined $use_type{$type} if (scalar keys %use_type > 0);
2327 return !defined $ignore_type{$type};
2331 my ($level, $type, $msg) = @_;
2333 if (!show_type($type) ||
2334 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2339 if ($level eq 'ERROR') {
2341 } elsif ($level eq 'WARNING') {
2347 $output .= $prefix . $level . ':';
2349 $output .= BLUE if ($color);
2350 $output .= "$type:";
2352 $output .= RESET if ($color);
2353 $output .= ' ' . $msg . "\n";
2356 my @lines = split("\n", $output, -1);
2357 splice(@lines, 1, 1);
2358 $output = join("\n", @lines);
2362 $output = (split('\n', $output))[0] . "\n";
2365 if ($verbose && exists($verbose_messages{$type}) &&
2366 !exists($verbose_emitted{$type})) {
2367 $output .= $verbose_messages{$type} . "\n\n";
2368 $verbose_emitted{$type} = 1;
2371 push(our @report, $output);
2380 sub fixup_current_range {
2381 my ($lineRef, $offset, $length) = @_;
2383 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2386 my $no = $o + $offset;
2387 my $nl = $l + $length;
2388 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2392 sub fix_inserted_deleted_lines {
2393 my ($linesRef, $insertedRef, $deletedRef) = @_;
2395 my $range_last_linenr = 0;
2396 my $delta_offset = 0;
2401 my $next_insert = 0;
2402 my $next_delete = 0;
2406 my $inserted = @{$insertedRef}[$next_insert++];
2407 my $deleted = @{$deletedRef}[$next_delete++];
2409 foreach my $old_line (@{$linesRef}) {
2411 my $line = $old_line; #don't modify the array
2412 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2414 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2415 $range_last_linenr = $new_linenr;
2416 fixup_current_range(\$line, $delta_offset, 0);
2419 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2420 $deleted = @{$deletedRef}[$next_delete++];
2422 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2425 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2426 push(@lines, ${$inserted}{'LINE'});
2427 $inserted = @{$insertedRef}[$next_insert++];
2429 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2433 push(@lines, $line);
2443 sub fix_insert_line {
2444 my ($linenr, $line) = @_;
2450 push(@fixed_inserted, $inserted);
2453 sub fix_delete_line {
2454 my ($linenr, $line) = @_;
2461 push(@fixed_deleted, $deleted);
2465 my ($type, $msg) = @_;
2467 if (report("ERROR", $type, $msg)) {
2475 my ($type, $msg) = @_;
2477 if (report("WARNING", $type, $msg)) {
2485 my ($type, $msg) = @_;
2487 if ($check && report("CHECK", $type, $msg)) {
2495 sub check_absolute_file {
2496 my ($absolute, $herecurr) = @_;
2497 my $file = $absolute;
2499 ##print "absolute<$absolute>\n";
2501 # See if any suffix of this path is a path within the tree.
2502 while ($file =~ s@^[^/]*/@@) {
2503 if (-f "$root/$file") {
2504 ##print "file<$file>\n";
2512 # It is, so see if the prefix is acceptable.
2513 my $prefix = $absolute;
2514 substr($prefix, -length($file)) = '';
2516 ##print "prefix<$prefix>\n";
2517 if ($prefix ne ".../") {
2518 WARN("USE_RELATIVE_PATH",
2519 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2526 $string =~ s/^\s+|\s+$//g;
2534 $string =~ s/^\s+//;
2542 $string =~ s/\s+$//;
2547 sub string_find_replace {
2548 my ($string, $find, $replace) = @_;
2550 $string =~ s/$find/$replace/g;
2558 my $source_indent = $tabsize;
2559 my $max_spaces_before_tab = $source_indent - 1;
2560 my $spaces_to_tab = " " x $source_indent;
2562 #convert leading spaces to tabs
2563 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2564 #Remove spaces before a tab
2565 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2570 sub pos_last_openparen {
2575 my $opens = $line =~ tr/\(/\(/;
2576 my $closes = $line =~ tr/\)/\)/;
2578 my $last_openparen = 0;
2580 if (($opens == 0) || ($closes >= $opens)) {
2584 my $len = length($line);
2586 for ($pos = 0; $pos < $len; $pos++) {
2587 my $string = substr($line, $pos);
2588 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2589 $pos += length($1) - 1;
2590 } elsif (substr($line, $pos, 1) eq '(') {
2591 $last_openparen = $pos;
2592 } elsif (index($string, '(') == -1) {
2597 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2600 sub get_raw_comment {
2601 my ($line, $rawline) = @_;
2604 for my $i (0 .. (length($line) - 1)) {
2605 if (substr($line, $i, 1) eq "$;") {
2606 $comment .= substr($rawline, $i, 1);
2613 sub exclude_global_initialisers {
2614 my ($realfile) = @_;
2616 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2617 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2618 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2619 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2623 my $filename = shift;
2629 my $stashrawline="";
2639 my $authorsignoff = 0;
2640 my $author_sob = '';
2642 my $is_binding_patch = -1;
2643 my $in_header_lines = $file ? 0 : 1;
2644 my $in_commit_log = 0; #Scanning lines before patch
2645 my $has_patch_separator = 0; #Found a --- line
2646 my $has_commit_log = 0; #Encountered lines before patch
2647 my $commit_log_lines = 0; #Number of commit log lines
2648 my $commit_log_possible_stack_dump = 0;
2649 my $commit_log_long_line = 0;
2650 my $commit_log_has_diff = 0;
2651 my $reported_maintainer_file = 0;
2652 my $non_utf8_charset = 0;
2654 my $last_git_commit_id_linenr = -1;
2656 my $last_blank_line = 0;
2657 my $last_coalesced_string_linenr = -1;
2665 # Trace the real file/line as we go.
2670 my $context_function; #undef'd unless there's a known function
2672 my $comment_edge = 0;
2676 my $prev_values = 'E';
2679 my %suppress_ifbraces;
2680 my %suppress_whiletrailers;
2681 my %suppress_export;
2682 my $suppress_statement = 0;
2684 my %signatures = ();
2686 # Pre-scan the patch sanitizing the lines.
2687 # Pre-scan the patch looking for any __setup documentation.
2689 my @setup_docs = ();
2692 my $camelcase_file_seeded = 0;
2694 my $checklicenseline = 1;
2696 sanitise_line_reset();
2698 foreach my $rawline (@rawlines) {
2702 push(@fixed, $rawline) if ($fix);
2704 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2706 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2711 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2720 # Guestimate if this is a continuing comment. Run
2721 # the context looking for a comment "edge". If this
2722 # edge is a close comment then we must be in a comment
2726 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2727 next if (defined $rawlines[$ln - 1] &&
2728 $rawlines[$ln - 1] =~ /^-/);
2730 #print "RAW<$rawlines[$ln - 1]>\n";
2731 last if (!defined $rawlines[$ln - 1]);
2732 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2733 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2738 if (defined $edge && $edge eq '*/') {
2742 # Guestimate if this is a continuing comment. If this
2743 # is the start of a diff block and this line starts
2744 # ' *' then it is very likely a comment.
2745 if (!defined $edge &&
2746 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2751 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2752 sanitise_line_reset($in_comment);
2754 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2755 # Standardise the strings and chars within the input to
2756 # simplify matching -- only bother with positive lines.
2757 $line = sanitise_line($rawline);
2759 push(@lines, $line);
2762 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2767 #print "==>$rawline\n";
2768 #print "-->$line\n";
2770 if ($setup_docs && $line =~ /^\+/) {
2771 push(@setup_docs, $line);
2780 foreach my $line (@lines) {
2783 my $sline = $line; #copy of $line
2784 $sline =~ s/$;/ /g; #with comments as spaces
2786 my $rawline = $rawlines[$linenr - 1];
2787 my $raw_comment = get_raw_comment($line, $rawline);
2789 # check if it's a mode change, rename or start of a patch
2790 if (!$in_commit_log &&
2791 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2792 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2793 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2797 #extract the line range in the file after the patch is applied
2798 if (!$in_commit_log &&
2799 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2802 $first_line = $linenr + 1;
2812 %suppress_ifbraces = ();
2813 %suppress_whiletrailers = ();
2814 %suppress_export = ();
2815 $suppress_statement = 0;
2816 if ($context =~ /\b(\w+)\s*\(/) {
2817 $context_function = $1;
2819 undef $context_function;
2823 # track the line number as we move through the hunk, note that
2824 # new versions of GNU diff omit the leading space on completely
2825 # blank context lines so we need to count that too.
2826 } elsif ($line =~ /^( |\+|$)/) {
2828 $realcnt-- if ($realcnt != 0);
2830 # Measure the line length and indent.
2831 ($length, $indent) = line_stats($rawline);
2833 # Track the previous line.
2834 ($prevline, $stashline) = ($stashline, $line);
2835 ($previndent, $stashindent) = ($stashindent, $indent);
2836 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2838 #warn "line<$line>\n";
2840 } elsif ($realcnt == 1) {
2844 my $hunk_line = ($realcnt != 0);
2846 $here = "#$linenr: " if (!$file);
2847 $here = "#$realline: " if ($file);
2850 # extract the filename as it passes
2851 if ($line =~ /^diff --git.*?(\S+)$/) {
2853 $realfile =~ s@^([^/]*)/@@ if (!$file);
2856 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2858 $realfile =~ s@^([^/]*)/@@ if (!$file);
2862 if (!$file && $tree && $p1_prefix ne '' &&
2863 -e "$root/$p1_prefix") {
2864 WARN("PATCH_PREFIX",
2865 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2868 if ($realfile =~ m@^include/asm/@) {
2869 ERROR("MODIFIED_INCLUDE_ASM",
2870 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2875 #make up the handle for any error we report on this line
2877 $prefix = "$realfile:$realline: "
2880 $prefix = "$filename:$realline: ";
2882 $prefix = "$filename:$linenr: ";
2887 if (is_maintained_obsolete($realfile)) {
2889 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2891 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2894 $check = $check_orig;
2896 $checklicenseline = 1;
2898 if ($realfile !~ /^MAINTAINERS/) {
2899 my $last_binding_patch = $is_binding_patch;
2901 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2903 if (($last_binding_patch != -1) &&
2904 ($last_binding_patch ^ $is_binding_patch)) {
2905 WARN("DT_SPLIT_BINDING_PATCH",
2906 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2913 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2915 my $hereline = "$here\n$rawline\n";
2916 my $herecurr = "$here\n$rawline\n";
2917 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2919 $cnt_lines++ if ($realcnt != 0);
2921 # Verify the existence of a commit log if appropriate
2922 # 2 is used because a $signature is counted in $commit_log_lines
2923 if ($in_commit_log) {
2924 if ($line !~ /^\s*$/) {
2925 $commit_log_lines++; #could be a $signature
2927 } elsif ($has_commit_log && $commit_log_lines < 2) {
2928 WARN("COMMIT_MESSAGE",
2929 "Missing commit description - Add an appropriate one\n");
2930 $commit_log_lines = 2; #warn only once
2933 # Check if the commit log has what seems like a diff which can confuse patch
2934 if ($in_commit_log && !$commit_log_has_diff &&
2935 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2936 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2937 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2938 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2939 ERROR("DIFF_IN_COMMIT_MSG",
2940 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2941 $commit_log_has_diff = 1;
2944 # Check for incorrect file permissions
2945 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2946 my $permhere = $here . "FILE: $realfile\n";
2947 if ($realfile !~ m@scripts/@ &&
2948 $realfile !~ /\.(py|pl|awk|sh)$/) {
2949 ERROR("EXECUTE_PERMISSIONS",
2950 "do not set execute permissions for source files\n" . $permhere);
2954 # Check the patch for a From:
2955 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2957 my $curline = $linenr;
2958 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2961 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2963 $author = reformat_email($author);
2966 # Check the patch for a signoff:
2967 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2970 if ($author ne '' && $authorsignoff != 1) {
2971 if (same_email_addresses($1, $author)) {
2975 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2976 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2978 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
2981 } elsif (lc $email_address eq lc $author_address) {
2984 } elsif ($email_name eq $author_name) {
2988 my $address1 = $email_address;
2989 my $address2 = $author_address;
2991 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2994 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2997 if ($address1 eq $address2) {
3005 # Check for patch separator
3006 if ($line =~ /^---$/) {
3007 $has_patch_separator = 1;
3011 # Check if MAINTAINERS is being updated. If so, there's probably no need to
3012 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
3013 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3014 $reported_maintainer_file = 1;
3017 # Check signature styles
3018 if (!$in_header_lines &&
3019 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3020 my $space_before = $1;
3022 my $space_after = $3;
3024 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3026 if ($sign_off !~ /$signature_tags/) {
3027 my $suggested_signature = find_standard_signature($sign_off);
3028 if ($suggested_signature eq "") {
3029 WARN("BAD_SIGN_OFF",
3030 "Non-standard signature: $sign_off\n" . $herecurr);
3032 if (WARN("BAD_SIGN_OFF",
3033 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3035 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3039 if (defined $space_before && $space_before ne "") {
3040 if (WARN("BAD_SIGN_OFF",
3041 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3043 $fixed[$fixlinenr] =
3044 "$ucfirst_sign_off $email";
3047 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3048 if (WARN("BAD_SIGN_OFF",
3049 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3051 $fixed[$fixlinenr] =
3052 "$ucfirst_sign_off $email";
3056 if (!defined $space_after || $space_after ne " ") {
3057 if (WARN("BAD_SIGN_OFF",
3058 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3060 $fixed[$fixlinenr] =
3061 "$ucfirst_sign_off $email";
3065 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3066 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3067 if ($suggested_email eq "") {
3068 ERROR("BAD_SIGN_OFF",
3069 "Unrecognized email address: '$email'\n" . $herecurr);
3071 my $dequoted = $suggested_email;
3072 $dequoted =~ s/^"//;
3073 $dequoted =~ s/" </ </;
3074 # Don't force email to have quotes
3075 # Allow just an angle bracketed address
3076 if (!same_email_addresses($email, $suggested_email)) {
3077 if (WARN("BAD_SIGN_OFF",
3078 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3080 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3084 # Address part shouldn't have comments
3085 my $stripped_address = $email_address;
3086 $stripped_address =~ s/\([^\(\)]*\)//g;
3087 if ($email_address ne $stripped_address) {
3088 if (WARN("BAD_SIGN_OFF",
3089 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3091 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3095 # Only one name comment should be allowed
3096 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3097 if ($comment_count > 1) {
3098 WARN("BAD_SIGN_OFF",
3099 "Use a single name comment in email: '$email'\n" . $herecurr);
3103 # stable@vger.kernel.org or stable@kernel.org shouldn't
3104 # have an email name. In addition comments should strictly
3106 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3107 if (($comment ne "" && $comment !~ /^#.+/) ||
3108 ($email_name ne "")) {
3109 my $cur_name = $email_name;
3110 my $new_comment = $comment;
3111 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3113 # Remove brackets enclosing comment text
3114 # and # from start of comments to get comment text
3115 $new_comment =~ s/^\((.*)\)$/$1/;
3116 $new_comment =~ s/^\[(.*)\]$/$1/;
3117 $new_comment =~ s/^[\s\#]+|\s+$//g;
3119 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3120 $new_comment = " # $new_comment" if ($new_comment ne "");
3121 my $new_email = "$email_address$new_comment";
3123 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3124 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3126 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3129 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3130 my $new_comment = $comment;
3132 # Extract comment text from within brackets or
3133 # c89 style /*...*/ comments
3134 $new_comment =~ s/^\[(.*)\]$/$1/;
3135 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3137 $new_comment = trim($new_comment);
3138 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3139 $new_comment = "($new_comment)" if ($new_comment ne "");
3140 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3142 if (WARN("BAD_SIGN_OFF",
3143 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3145 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3150 # Check for duplicate signatures
3151 my $sig_nospace = $line;
3152 $sig_nospace =~ s/\s//g;
3153 $sig_nospace = lc($sig_nospace);
3154 if (defined $signatures{$sig_nospace}) {
3155 WARN("BAD_SIGN_OFF",
3156 "Duplicate signature\n" . $herecurr);
3158 $signatures{$sig_nospace} = 1;
3161 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3162 if ($sign_off =~ /^co-developed-by:$/i) {
3163 if ($email eq $author) {
3164 WARN("BAD_SIGN_OFF",
3165 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
3167 if (!defined $lines[$linenr]) {
3168 WARN("BAD_SIGN_OFF",
3169 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3170 } elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
3171 WARN("BAD_SIGN_OFF",
3172 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
3173 } elsif ($1 ne $email) {
3174 WARN("BAD_SIGN_OFF",
3175 "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
3179 # check if Reported-by: is followed by a Closes: tag
3180 if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3181 if (!defined $lines[$linenr]) {
3182 WARN("BAD_REPORTED_BY_LINK",
3183 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
3184 } elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
3185 WARN("BAD_REPORTED_BY_LINK",
3186 "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
3192 # Check Fixes: styles is correct
3193 if (!$in_header_lines &&
3194 $line =~ /^\s*fixes:?\s*(?:commit\s*)?[0-9a-f]{5,}\b/i) {
3195 my $orig_commit = "";
3196 my $id = "0123456789ab";
3197 my $title = "commit title";
3202 my $title_has_quotes = 0;
3204 if ($line =~ /(\s*fixes:?)\s+([0-9a-f]{5,})\s+($balanced_parens)/i) {
3209 $tag_case = 0 if $tag eq "Fixes:";
3210 $tag_space = 0 if ($line =~ /^fixes:? [0-9a-f]{5,} ($balanced_parens)/i);
3212 $id_length = 0 if ($orig_commit =~ /^[0-9a-f]{12}$/i);
3213 $id_case = 0 if ($orig_commit !~ /[A-F]/);
3215 # Always strip leading/trailing parens then double quotes if existing
3216 $title = substr($title, 1, -1);
3217 if ($title =~ /^".*"$/) {
3218 $title = substr($title, 1, -1);
3219 $title_has_quotes = 1;
3223 my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3226 if ($ctitle ne $title || $tag_case || $tag_space ||
3227 $id_length || $id_case || !$title_has_quotes) {
3228 if (WARN("BAD_FIXES_TAG",
3229 "Please use correct Fixes: style 'Fixes: <12 chars of sha1> (\"<title line>\")' - ie: 'Fixes: $cid (\"$ctitle\")'\n" . $herecurr) &&
3231 $fixed[$fixlinenr] = "Fixes: $cid (\"$ctitle\")";
3236 # Check email subject for common tools that don't need to be mentioned
3237 if ($in_header_lines &&
3238 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3239 WARN("EMAIL_SUBJECT",
3240 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3243 # Check for Gerrit Change-Ids not in any patch context
3244 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3245 if (ERROR("GERRIT_CHANGE_ID",
3246 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3248 fix_delete_line($fixlinenr, $rawline);
3252 # Check if the commit log is in a possible stack dump
3253 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3254 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3255 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3257 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3258 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3259 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3260 # stack dump address styles
3261 $commit_log_possible_stack_dump = 1;
3264 # Check for line lengths > 75 in commit log, warn once
3265 if ($in_commit_log && !$commit_log_long_line &&
3266 length($line) > 75 &&
3267 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3268 # file delta changes
3269 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3271 $line =~ /^\s*(?:Fixes:|$link_tags_search|$signature_tags)/i ||
3272 # A Fixes:, link or signature tag line
3273 $commit_log_possible_stack_dump)) {
3274 WARN("COMMIT_LOG_LONG_LINE",
3275 "Prefer a maximum 75 chars per line (possible unwrapped commit description?)\n" . $herecurr);
3276 $commit_log_long_line = 1;
3279 # Reset possible stack dump if a blank line is found
3280 if ($in_commit_log && $commit_log_possible_stack_dump &&
3282 $commit_log_possible_stack_dump = 0;
3285 # Check for odd tags before a URI/URL
3286 if ($in_commit_log &&
3287 $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
3288 if ($1 =~ /^v(?:ersion)?\d+/i) {
3289 WARN("COMMIT_LOG_VERSIONING",
3290 "Patch version information should be after the --- line\n" . $herecurr);
3292 WARN("COMMIT_LOG_USE_LINK",
3293 "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
3297 # Check for misuse of the link tags
3298 if ($in_commit_log &&
3299 $line =~ /^\s*(\w+:)\s*(\S+)/) {
3302 if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3303 WARN("COMMIT_LOG_WRONG_LINK",
3304 "'$tag' should be followed by a public http(s) link\n" . $herecurr);
3308 # Check for lines starting with a #
3309 if ($in_commit_log && $line =~ /^#/) {
3310 if (WARN("COMMIT_COMMENT_SYMBOL",
3311 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3313 $fixed[$fixlinenr] =~ s/^/ /;
3317 # Check for git id commit length and improperly formed commit descriptions
3318 # A correctly formed commit description is:
3319 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3320 # with the commit subject '("' prefix and '")' suffix
3321 # This is a fairly compilicated block as it tests for what appears to be
3322 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3323 # possible SHA-1 matches.
3324 # A commit match can span multiple lines so this block attempts to find a
3325 # complete typical commit on a maximum of 3 lines
3326 if ($perl_version_ok &&
3327 $in_commit_log && !$commit_log_possible_stack_dump &&
3328 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3329 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3330 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3331 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3332 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3333 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3334 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3335 my $init_char = "c";
3336 my $orig_commit = "";
3341 my $id = '0123456789ab';
3342 my $orig_desc = "commit description";
3343 my $description = "";
3344 my $herectx = $herecurr;
3349 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3350 for (my $n = 0; $n < 2; $n++) {
3351 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3354 # Always strip leading/trailing parens then double quotes if existing
3355 $orig_desc = substr($orig_desc, 1, -1);
3356 if ($orig_desc =~ /^".*"$/) {
3357 $orig_desc = substr($orig_desc, 1, -1);
3362 last if ($#lines < $linenr + $n);
3363 $input .= " " . trim($rawlines[$linenr + $n]);
3364 $herectx .= "$rawlines[$linenr + $n]\n";
3366 $herectx = $herecurr if (!$has_parens);
3369 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3371 $orig_commit = lc($2);
3372 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3373 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3374 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3375 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3376 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3377 $orig_commit = lc($1);
3380 ($id, $description) = git_commit_info($orig_commit,
3384 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3385 $last_git_commit_id_linenr != $linenr - 1) {
3386 ERROR("GIT_COMMIT_ID",
3387 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3389 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3390 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3393 # Check for mailing list archives other than lore.kernel.org
3394 if ($rawline =~ m{http.*\b$obsolete_archives}) {
3395 WARN("PREFER_LORE_ARCHIVE",
3396 "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3399 # Check for added, moved or deleted files
3400 if (!$reported_maintainer_file && !$in_commit_log &&
3401 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3402 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3403 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3404 (defined($1) || defined($2))))) {
3406 $reported_maintainer_file = 1;
3407 WARN("FILE_PATH_CHANGES",
3408 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3411 # Check for adding new DT bindings not in schema format
3412 if (!$in_commit_log &&
3413 ($line =~ /^new file mode\s*\d+\s*$/) &&
3414 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3415 WARN("DT_SCHEMA_BINDING_PATCH",
3416 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3419 # Check for wrappage within a valid hunk of the file
3420 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3421 ERROR("CORRUPTED_PATCH",
3422 "patch seems to be corrupt (line wrapped?)\n" .
3423 $herecurr) if (!$emitted_corrupt++);
3426 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3427 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3428 $rawline !~ m/^$UTF8*$/) {
3429 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3431 my $blank = copy_spacing($rawline);
3432 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3433 my $hereptr = "$hereline$ptr\n";
3436 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3439 # Check if it's the start of a commit log
3440 # (not a header line and we haven't seen the patch filename)
3441 if ($in_header_lines && $realfile =~ /^$/ &&
3442 !($rawline =~ /^\s+(?:\S|$)/ ||
3443 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3444 $in_header_lines = 0;
3446 $has_commit_log = 1;
3449 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3450 # declined it, i.e defined some charset where it is missing.
3451 if ($in_header_lines &&
3452 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3454 $non_utf8_charset = 1;
3457 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3458 $rawline =~ /$NON_ASCII_UTF8/) {
3459 WARN("UTF8_BEFORE_PATCH",
3460 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3463 # Check for absolute kernel paths in commit message
3464 if ($tree && $in_commit_log) {
3465 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3468 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3469 check_absolute_file($1, $herecurr)) {
3472 check_absolute_file($file, $herecurr);
3477 # Check for various typo / spelling mistakes
3478 if (defined($misspellings) &&
3479 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3480 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3482 my $blank = copy_spacing($rawline);
3483 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3484 my $hereptr = "$hereline$ptr\n";
3485 my $typo_fix = $spelling_fix{lc($typo)};
3486 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3487 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3488 my $msg_level = \&WARN;
3489 $msg_level = \&CHK if ($file);
3490 if (&{$msg_level}("TYPO_SPELLING",
3491 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3493 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3498 # check for invalid commit id
3499 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3502 ($id, $description) = git_commit_info($2, undef, undef);
3503 if (!defined($id)) {
3504 WARN("UNKNOWN_COMMIT_ID",
3505 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3509 # check for repeated words separated by a single space
3510 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3511 if (($rawline =~ /^\+/ || $in_commit_log) &&
3512 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3513 pos($rawline) = 1 if (!$in_commit_log);
3514 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3518 my $start_pos = $-[1];
3519 my $end_pos = $+[2];
3520 if ($first =~ /(?:struct|union|enum)/) {
3521 pos($rawline) += length($first) + length($second) + 1;
3525 next if (lc($first) ne lc($second));
3526 next if ($first eq 'long');
3528 # check for character before and after the word matches
3529 my $start_char = '';
3531 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3532 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3534 next if ($start_char =~ /^\S$/);
3535 next if (index(" \t.,;?!", $end_char) == -1);
3537 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3538 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3539 next if (!exists($allow_repeated_words{lc($first)}));
3542 if (WARN("REPEATED_WORD",
3543 "Possible repeated word: '$first'\n" . $herecurr) &&
3545 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3549 # if it's a repeated word on consecutive lines in a comment block
3550 if ($prevline =~ /$;+\s*$/ &&
3551 $prevrawline =~ /($word_pattern)\s*$/) {
3553 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3554 if (WARN("REPEATED_WORD",
3555 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3557 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3563 # ignore non-hunk lines and lines being removed
3564 next if (!$hunk_line || $line =~ /^-/);
3566 #trailing whitespace
3567 if ($line =~ /^\+.*\015/) {
3568 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3569 if (ERROR("DOS_LINE_ENDINGS",
3570 "DOS line endings\n" . $herevet) &&
3572 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3574 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3575 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3576 if (ERROR("TRAILING_WHITESPACE",
3577 "trailing whitespace\n" . $herevet) &&
3579 $fixed[$fixlinenr] =~ s/\s+$//;
3585 # Check for FSF mailing addresses.
3586 if ($rawline =~ /\bwrite to the Free/i ||
3587 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3588 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3589 $rawline =~ /\b51\s+Franklin\s+St/i) {
3590 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3591 my $msg_level = \&ERROR;
3592 $msg_level = \&CHK if ($file);
3593 &{$msg_level}("FSF_MAILING_ADDRESS",
3594 "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)
3597 # check for Kconfig help text having a real description
3598 # Only applies when adding the entry originally, after that we do not have
3599 # sufficient context to determine whether it is indeed long enough.
3600 if ($realfile =~ /Kconfig/ &&
3601 # 'choice' is usually the last thing on the line (though
3602 # Kconfig supports named choices), so use a word boundary
3603 # (\b) rather than a whitespace character (\s)
3604 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3608 my $help_length = 0;
3609 while (defined $lines[$ln]) {
3610 my $f = $lines[$ln++];
3612 next if ($f =~ /^-/);
3613 last if ($f !~ /^[\+ ]/); # !patch context
3615 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3619 if ($f =~ /^\+\s*help\s*$/) {
3624 $f =~ s/^.//; # strip patch context [+ ]
3625 $f =~ s/#.*//; # strip # directives
3626 $f =~ s/^\s+//; # strip leading blanks
3627 next if ($f =~ /^$/); # skip blank lines
3629 # At the end of this Kconfig block:
3630 # This only checks context lines in the patch
3631 # and so hopefully shouldn't trigger false
3632 # positives, even though some of these are
3633 # common words in help texts
3634 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3635 if|endif|menu|endmenu|source)\b/x) {
3638 $help_length++ if ($has_help);
3641 $help_length < $min_conf_desc_length) {
3642 my $stat_real = get_stat_real($linenr, $ln - 1);
3643 WARN("CONFIG_DESCRIPTION",
3644 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3648 # check MAINTAINERS entries
3649 if ($realfile =~ /^MAINTAINERS$/) {
3650 # check MAINTAINERS entries for the right form
3651 if ($rawline =~ /^\+[A-Z]:/ &&
3652 $rawline !~ /^\+[A-Z]:\t\S/) {
3653 if (WARN("MAINTAINERS_STYLE",
3654 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3656 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3659 # check MAINTAINERS entries for the right ordering too
3660 my $preferred_order = 'MRLSWQBCPTFXNK';
3661 if ($rawline =~ /^\+[A-Z]:/ &&
3662 $prevrawline =~ /^[\+ ][A-Z]:/) {
3663 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3666 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3669 my $curindex = index($preferred_order, $cur);
3670 my $previndex = index($preferred_order, $prev);
3671 if ($curindex < 0) {
3672 WARN("MAINTAINERS_STYLE",
3673 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3675 if ($previndex >= 0 && $curindex < $previndex) {
3676 WARN("MAINTAINERS_STYLE",
3677 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3678 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3679 ($prev eq 'X' && $cur eq 'X')) &&
3680 ($prevval cmp $curval) > 0) {
3681 WARN("MAINTAINERS_STYLE",
3682 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3688 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3689 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3692 'EXTRA_AFLAGS' => 'asflags-y',
3693 'EXTRA_CFLAGS' => 'ccflags-y',
3694 'EXTRA_CPPFLAGS' => 'cppflags-y',
3695 'EXTRA_LDFLAGS' => 'ldflags-y',
3698 WARN("DEPRECATED_VARIABLE",
3699 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3702 # check for DT compatible documentation
3703 if (defined $root &&
3704 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3705 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3707 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3709 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3710 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3712 foreach my $compat (@compats) {
3713 my $compat2 = $compat;
3714 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3715 my $compat3 = $compat;
3716 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3717 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3719 WARN("UNDOCUMENTED_DT_STRING",
3720 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3723 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3725 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3727 WARN("UNDOCUMENTED_DT_STRING",
3728 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3733 # check for using SPDX license tag at beginning of files
3734 if ($realline == $checklicenseline) {
3735 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3736 $checklicenseline = 2;
3737 } elsif ($rawline =~ /^\+/) {
3739 if ($realfile =~ /\.(h|s|S)$/) {
3741 } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3743 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3745 } elsif ($realfile =~ /\.rst$/) {
3749 # check SPDX comment style for .[chsS] files
3750 if ($realfile =~ /\.[chsS]$/ &&
3751 $rawline =~ /SPDX-License-Identifier:/ &&
3752 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3753 WARN("SPDX_LICENSE_TAG",
3754 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3757 if ($comment !~ /^$/ &&
3758 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3759 WARN("SPDX_LICENSE_TAG",
3760 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3761 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3762 my $spdx_license = $1;
3763 if (!is_SPDX_License_valid($spdx_license)) {
3764 WARN("SPDX_LICENSE_TAG",
3765 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3767 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3768 $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
3769 my $msg_level = \&WARN;
3770 $msg_level = \&CHK if ($file);
3771 if (&{$msg_level}("SPDX_LICENSE_TAG",
3773 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3775 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3778 if ($realfile =~ m@^include/dt-bindings/@ &&
3779 $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3780 WARN("SPDX_LICENSE_TAG",
3781 "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3787 # check for embedded filenames
3788 if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
3789 WARN("EMBEDDED_FILENAME",
3790 "It's generally not useful to have the filename in the file\n" . $herecurr);
3793 # check we are in a valid source file if not then ignore this hunk
3794 next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3796 # check for using SPDX-License-Identifier on the wrong line number
3797 if ($realline != $checklicenseline &&
3798 $rawline =~ /\bSPDX-License-Identifier:/ &&
3799 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3800 WARN("SPDX_LICENSE_TAG",
3801 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3804 # line length limit (with some exclusions)
3806 # There are a few types of lines that may extend beyond $max_line_length:
3807 # logging functions like pr_info that end in a string
3808 # lines with a single string
3809 # #defines that are a single string
3810 # lines with an RFC3986 like URL
3812 # There are 3 different line length message types:
3813 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3814 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3815 # LONG_LINE all other lines longer than $max_line_length
3817 # if LONG_LINE is ignored, the other 2 types are also ignored
3820 if ($line =~ /^\+/ && $length > $max_line_length) {
3821 my $msg_type = "LONG_LINE";
3823 # Check the allowed long line types first
3825 # logging functions that end in a string that starts
3826 # before $max_line_length
3827 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3828 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3831 # lines with only strings (w/ possible termination)
3832 # #defines with only strings
3833 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3834 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3837 # More special cases
3838 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3839 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3842 # URL ($rawline is used in case the URL is in a comment)
3843 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3846 # Otherwise set the alternate message types
3848 # a comment starts before $max_line_length
3849 } elsif ($line =~ /($;[\s$;]*)$/ &&
3850 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3851 $msg_type = "LONG_LINE_COMMENT"
3853 # a quoted string starts before $max_line_length
3854 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3855 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3856 $msg_type = "LONG_LINE_STRING"
3859 if ($msg_type ne "" &&
3860 (show_type("LONG_LINE") || show_type($msg_type))) {
3861 my $msg_level = \&WARN;
3862 $msg_level = \&CHK if ($file);
3863 &{$msg_level}($msg_type,
3864 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3868 # check for adding lines without a newline.
3869 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3870 if (WARN("MISSING_EOF_NEWLINE",
3871 "adding a line without newline at end of file\n" . $herecurr) &&
3873 fix_delete_line($fixlinenr+1, "No newline at end of file");
3877 # check for .L prefix local symbols in .S files
3878 if ($realfile =~ /\.S$/ &&
3879 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3880 WARN("AVOID_L_PREFIX",
3881 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr);
3884 # check we are in a valid source file C or perl if not then ignore this hunk
3885 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3887 # at the beginning of a line any tabs must come first and anything
3888 # more than $tabsize must use tabs.
3889 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3890 $rawline =~ /^\+\s* \s*/) {
3891 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3893 if (ERROR("CODE_INDENT",
3894 "code indent should use tabs where possible\n" . $herevet) &&
3896 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3900 # check for space before tabs.
3901 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3902 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3903 if (WARN("SPACE_BEFORE_TAB",
3904 "please, no space before tabs\n" . $herevet) &&
3906 while ($fixed[$fixlinenr] =~
3907 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3908 while ($fixed[$fixlinenr] =~
3909 s/(^\+.*) +\t/$1\t/) {}
3913 # check for assignments on the start of a line
3914 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3916 if (CHK("ASSIGNMENT_CONTINUATIONS",
3917 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3918 $fix && $prevrawline =~ /^\+/) {
3919 # add assignment operator to the previous line, remove from current line
3920 $fixed[$fixlinenr - 1] .= " $operator";
3921 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3925 # check for && or || at the start of a line
3926 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3928 if (CHK("LOGICAL_CONTINUATIONS",
3929 "Logical continuations should be on the previous line\n" . $hereprev) &&
3930 $fix && $prevrawline =~ /^\+/) {
3931 # insert logical operator at last non-comment, non-whitepsace char on previous line
3932 $prevline =~ /[\s$;]*$/;
3933 my $line_end = substr($prevrawline, $-[0]);
3934 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3935 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3939 # check indentation starts on a tab stop
3940 if ($perl_version_ok &&
3941 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3942 my $indent = length($1);
3943 if ($indent % $tabsize) {
3945 "Statements should start on a tabstop\n" . $herecurr) &&
3947 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3952 # check multi-line statement indentation matches previous line
3953 if ($perl_version_ok &&
3954 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3955 $prevline =~ /^\+(\t*)(.*)$/;
3959 my $pos = pos_last_openparen($rest);
3961 $line =~ /^(\+| )([ \t]*)/;
3964 my $goodtabindent = $oldindent .
3965 "\t" x ($pos / $tabsize) .
3966 " " x ($pos % $tabsize);
3967 my $goodspaceindent = $oldindent . " " x $pos;
3969 if ($newindent ne $goodtabindent &&
3970 $newindent ne $goodspaceindent) {
3972 if (CHK("PARENTHESIS_ALIGNMENT",
3973 "Alignment should match open parenthesis\n" . $hereprev) &&
3974 $fix && $line =~ /^\+/) {
3975 $fixed[$fixlinenr] =~
3976 s/^\+[ \t]*/\+$goodtabindent/;
3982 # check for space after cast like "(int) foo" or "(struct foo) bar"
3983 # avoid checking a few false positives:
3984 # "sizeof(<type>)" or "__alignof__(<type>)"
3985 # function pointer declarations like "(*foo)(int) = bar;"
3986 # structure definitions like "(struct foo) { 0 };"
3987 # multiline macros that define functions
3988 # known attributes or the __attribute__ keyword
3989 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3990 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3992 "No space is necessary after a cast\n" . $herecurr) &&
3994 $fixed[$fixlinenr] =~
3995 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3999 # Block comment styles
4000 # Networking with an initial /*
4001 if ($realfile =~ m@^(drivers/net/|net/)@ &&
4002 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
4003 $rawline =~ /^\+[ \t]*\*/ &&
4004 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
4005 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
4006 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
4009 # Block comments use * on subsequent lines
4010 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4011 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
4012 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
4013 $rawline =~ /^\+/ && #line is new
4014 $rawline !~ /^\+[ \t]*\*/) { #no leading *
4015 WARN("BLOCK_COMMENT_STYLE",
4016 "Block comments use * on subsequent lines\n" . $hereprev);
4019 # Block comments use */ on trailing lines
4020 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
4021 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
4022 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
4023 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
4024 WARN("BLOCK_COMMENT_STYLE",
4025 "Block comments use a trailing */ on a separate line\n" . $herecurr);
4028 # Block comment * alignment
4029 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4030 $line =~ /^\+[ \t]*$;/ && #leading comment
4031 $rawline =~ /^\+[ \t]*\*/ && #leading *
4032 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
4033 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
4034 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4036 $prevrawline =~ m@^\+([ \t]*/?)\*@;
4038 $oldindent = expand_tabs($1);
4040 $prevrawline =~ m@^\+(.*/?)\*@;
4041 $oldindent = expand_tabs($1);
4043 $rawline =~ m@^\+([ \t]*)\*@;
4045 $newindent = expand_tabs($newindent);
4046 if (length($oldindent) ne length($newindent)) {
4047 WARN("BLOCK_COMMENT_STYLE",
4048 "Block comments should align the * on each line\n" . $hereprev);
4052 # check for missing blank lines after struct/union declarations
4053 # with exceptions for various attributes and macros
4054 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4056 !($line =~ /^\+\s*$/ ||
4057 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
4058 $line =~ /^\+\s*MODULE_/i ||
4059 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4060 $line =~ /^\+[a-z_]*init/ ||
4061 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4062 $line =~ /^\+\s*DECLARE/ ||
4063 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4064 $line =~ /^\+\s*__setup/)) {
4065 if (CHK("LINE_SPACING",
4066 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4068 fix_insert_line($fixlinenr, "\+");
4072 # check for multiple consecutive blank lines
4073 if ($prevline =~ /^[\+ ]\s*$/ &&
4074 $line =~ /^\+\s*$/ &&
4075 $last_blank_line != ($linenr - 1)) {
4076 if (CHK("LINE_SPACING",
4077 "Please don't use multiple blank lines\n" . $hereprev) &&
4079 fix_delete_line($fixlinenr, $rawline);
4082 $last_blank_line = $linenr;
4085 # check for missing blank lines after declarations
4086 # (declarations must have the same indentation and not be at the start of line)
4087 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4091 # remove $Attribute/$Sparse uses to simplify comparisons
4092 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4093 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4094 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4095 # function pointer declarations
4096 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4097 # foo bar; where foo is some local typedef or #define
4098 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4099 # known declaration macros
4100 $pl =~ /^\+\s+$declaration_macros/) &&
4101 # for "else if" which can look like "$Ident $Ident"
4102 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4103 # other possible extensions of declaration lines
4104 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4105 # not starting a section or a macro "\" extended line
4106 $pl =~ /(?:\{\s*|\\)$/) &&
4107 # looks like a declaration
4108 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4109 # function pointer declarations
4110 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4111 # foo bar; where foo is some local typedef or #define
4112 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4113 # known declaration macros
4114 $sl =~ /^\+\s+$declaration_macros/ ||
4115 # start of struct or union or enum
4116 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4117 # start or end of block or continuation of declaration
4118 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4119 # bitfield continuation
4120 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4121 # other possible extensions of declaration lines
4122 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4123 if (WARN("LINE_SPACING",
4124 "Missing a blank line after declarations\n" . $hereprev) &&
4126 fix_insert_line($fixlinenr, "\+");
4131 # check for spaces at the beginning of a line.
4133 # 1) within comments
4134 # 2) indented preprocessor commands
4136 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4137 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4138 if (WARN("LEADING_SPACE",
4139 "please, no spaces at the start of a line\n" . $herevet) &&
4141 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4145 # check we are in a valid C source file if not then ignore this hunk
4146 next if ($realfile !~ /\.(h|c)$/);
4148 # check for unusual line ending [ or (
4149 if ($line =~ /^\+.*([\[\(])\s*$/) {
4150 CHK("OPEN_ENDED_LINE",
4151 "Lines should not end with a '$1'\n" . $herecurr);
4154 # check if this appears to be the start function declaration, save the name
4155 if ($sline =~ /^\+\{\s*$/ &&
4156 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4157 $context_function = $1;
4160 # check if this appears to be the end of function declaration
4161 if ($sline =~ /^\+\}\s*$/) {
4162 undef $context_function;
4165 # check indentation of any line with a bare else
4166 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4167 # if the previous line is a break or return and is indented 1 tab more...
4168 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4169 my $tabs = length($1) + 1;
4170 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4171 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4172 defined $lines[$linenr] &&
4173 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4174 WARN("UNNECESSARY_ELSE",
4175 "else is not generally useful after a break or return\n" . $hereprev);
4179 # check indentation of a line with a break;
4180 # if the previous line is a goto, return or break
4181 # and is indented the same # of tabs
4182 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4184 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4185 if (WARN("UNNECESSARY_BREAK",
4186 "break is not useful after a $1\n" . $hereprev) &&
4188 fix_delete_line($fixlinenr, $rawline);
4193 # check for RCS/CVS revision markers
4194 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4196 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4199 # check for old HOTPLUG __dev<foo> section markings
4200 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4201 WARN("HOTPLUG_SECTION",
4202 "Using $1 is unnecessary\n" . $herecurr);
4205 # Check for potential 'bare' types
4206 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4208 #print "LINE<$line>\n";
4209 if ($linenr > $suppress_statement &&
4210 $realcnt && $sline =~ /.\s*\S/) {
4211 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4212 ctx_statement_block($linenr, $realcnt, 0);
4213 $stat =~ s/\n./\n /g;
4214 $cond =~ s/\n./\n /g;
4216 #print "linenr<$linenr> <$stat>\n";
4217 # If this statement has no statement boundaries within
4218 # it there is no point in retrying a statement scan
4219 # until we hit end of it.
4220 my $frag = $stat; $frag =~ s/;+\s*$//;
4221 if ($frag !~ /(?:{|;)/) {
4222 #print "skip<$line_nr_next>\n";
4223 $suppress_statement = $line_nr_next;
4226 # Find the real next line.
4227 $realline_next = $line_nr_next;
4228 if (defined $realline_next &&
4229 (!defined $lines[$realline_next - 1] ||
4230 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4237 # Ignore goto labels.
4238 if ($s =~ /$Ident:\*$/s) {
4240 # Ignore functions being called
4241 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4243 } elsif ($s =~ /^.\s*else\b/s) {
4245 # declarations always start with types
4246 } 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) {
4249 possible($type, "A:" . $s);
4251 # definitions in global scope can only start with types
4252 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4253 possible($1, "B:" . $s);
4256 # any (foo ... *) is a pointer cast, and foo is a type
4257 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4258 possible($1, "C:" . $s);
4261 # Check for any sort of function declaration.
4262 # int foo(something bar, other baz);
4263 # void (*store_gdt)(x86_descr_ptr *);
4264 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4265 my ($name_len) = length($1);
4268 substr($ctx, 0, $name_len + 1, '');
4269 $ctx =~ s/\)[^\)]*$//;
4271 for my $arg (split(/\s*,\s*/, $ctx)) {
4272 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4274 possible($1, "D:" . $s);
4282 # Checks which may be anchored in the context.
4285 # Check for switch () and associated case and default
4286 # statements should be at the same indent.
4287 if ($line=~/\bswitch\s*\(.*\)/) {
4290 my @ctx = ctx_block_outer($linenr, $realcnt);
4292 for my $ctx (@ctx) {
4293 my ($clen, $cindent) = line_stats($ctx);
4294 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4295 $indent != $cindent) {
4296 $err .= "$sep$ctx\n";
4303 ERROR("SWITCH_CASE_INDENT_LEVEL",
4304 "switch and case should be at the same indent\n$hereline$err");
4308 # if/while/etc brace do not go on next line, unless defining a do while loop,
4309 # or if that brace on the next line is for something else
4310 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4311 my $pre_ctx = "$1$2";
4313 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4315 if ($line =~ /^\+\t{6,}/) {
4316 WARN("DEEP_INDENTATION",
4317 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4320 my $ctx_cnt = $realcnt - $#ctx - 1;
4321 my $ctx = join("\n", @ctx);
4323 my $ctx_ln = $linenr;
4324 my $ctx_skip = $realcnt;
4326 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4327 defined $lines[$ctx_ln - 1] &&
4328 $lines[$ctx_ln - 1] =~ /^-/)) {
4329 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4330 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4334 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4335 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4337 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4339 "that open brace { should be on the previous line\n" .
4340 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4342 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4343 $ctx =~ /\)\s*\;\s*$/ &&
4344 defined $lines[$ctx_ln - 1])
4346 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4347 if ($nindent > $indent) {
4348 WARN("TRAILING_SEMICOLON",
4349 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4350 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4355 # Check relative indent for conditionals and blocks.
4356 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4357 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4358 ctx_statement_block($linenr, $realcnt, 0)
4359 if (!defined $stat);
4360 my ($s, $c) = ($stat, $cond);
4362 substr($s, 0, length($c), '');
4364 # remove inline comments
4368 # Find out how long the conditional actually is.
4369 my @newlines = ($c =~ /\n/gs);
4370 my $cond_lines = 1 + $#newlines;
4372 # Make sure we remove the line prefixes as we have
4373 # none on the first line, and are going to readd them
4376 while ($s =~ /\n\s+\\\n/) {
4377 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4380 # We want to check the first line inside the block
4381 # starting at the end of the conditional, so remove:
4382 # 1) any blank line termination
4383 # 2) any opening brace { on end of the line
4385 my $continuation = 0;
4387 $s =~ s/^.*\bdo\b//;
4389 if ($s =~ s/^\s*\\//) {
4392 if ($s =~ s/^\s*?\n//) {
4397 # Also ignore a loop construct at the end of a
4398 # preprocessor statement.
4399 if (($prevline =~ /^.\s*#\s*define\s/ ||
4400 $prevline =~ /\\\s*$/) && $continuation == 0) {
4406 while ($cond_ptr != $cond_lines) {
4407 $cond_ptr = $cond_lines;
4409 # If we see an #else/#elif then the code
4411 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4416 # 1) blank lines, they should be at 0,
4417 # 2) preprocessor lines, and
4419 if ($continuation ||
4421 $s =~ /^\s*#\s*?/ ||
4422 $s =~ /^\s*$Ident\s*:/) {
4423 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4424 if ($s =~ s/^.*?\n//) {
4430 my (undef, $sindent) = line_stats("+" . $s);
4431 my $stat_real = raw_line($linenr, $cond_lines);
4433 # Check if either of these lines are modified, else
4434 # this is not this patch's fault.
4435 if (!defined($stat_real) ||
4436 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4439 if (defined($stat_real) && $cond_lines > 1) {
4440 $stat_real = "[...]\n$stat_real";
4443 #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";
4445 if ($check && $s ne '' &&
4446 (($sindent % $tabsize) != 0 ||
4447 ($sindent < $indent) ||
4448 ($sindent == $indent &&
4449 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4450 ($sindent > $indent + $tabsize))) {
4451 WARN("SUSPECT_CODE_INDENT",
4452 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4456 # Track the 'values' across context and added lines.
4457 my $opline = $line; $opline =~ s/^./ /;
4458 my ($curr_values, $curr_vars) =
4459 annotate_values($opline . "\n", $prev_values);
4460 $curr_values = $prev_values . $curr_values;
4462 my $outline = $opline; $outline =~ s/\t/ /g;
4463 print "$linenr > .$outline\n";
4464 print "$linenr > $curr_values\n";
4465 print "$linenr > $curr_vars\n";
4467 $prev_values = substr($curr_values, -1);
4469 #ignore lines not being added
4470 next if ($line =~ /^[^\+]/);
4472 # check for self assignments used to avoid compiler warnings
4473 # e.g.: int foo = foo, *bar = NULL;
4474 # struct foo bar = *(&(bar));
4475 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4477 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4478 WARN("SELF_ASSIGNMENT",
4479 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4483 # check for dereferences that span multiple lines
4484 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4485 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4486 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4488 $line =~ /^.\s*($Lval)/;
4491 WARN("MULTILINE_DEREFERENCE",
4492 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4495 # check for declarations of signed or unsigned without int
4496 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4499 $var = "" if (!defined $var);
4500 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4504 $pointer = "" if (!defined $pointer);
4506 if (WARN("UNSPECIFIED_INT",
4507 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4509 my $decl = trim($sign) . " int ";
4510 my $comp_pointer = $pointer;
4511 $comp_pointer =~ s/\s//g;
4512 $decl .= $comp_pointer;
4513 $decl = rtrim($decl) if ($var eq "");
4514 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4519 # TEST: allow direct testing of the type matcher.
4521 if ($line =~ /^.\s*$Declare\s*$/) {
4523 "TEST: is type\n" . $herecurr);
4524 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4525 ERROR("TEST_NOT_TYPE",
4526 "TEST: is not type ($1 is)\n". $herecurr);
4530 # TEST: allow direct testing of the attribute matcher.
4532 if ($line =~ /^.\s*$Modifier\s*$/) {
4534 "TEST: is attr\n" . $herecurr);
4535 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4536 ERROR("TEST_NOT_ATTR",
4537 "TEST: is not attr ($1 is)\n". $herecurr);
4542 # check for initialisation to aggregates open brace on the next line
4543 if ($line =~ /^.\s*{/ &&
4544 $prevline =~ /(?:^|[^=])=\s*$/) {
4545 if (ERROR("OPEN_BRACE",
4546 "that open brace { should be on the previous line\n" . $hereprev) &&
4547 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4548 fix_delete_line($fixlinenr - 1, $prevrawline);
4549 fix_delete_line($fixlinenr, $rawline);
4550 my $fixedline = $prevrawline;
4551 $fixedline =~ s/\s*=\s*$/ = {/;
4552 fix_insert_line($fixlinenr, $fixedline);
4554 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4555 fix_insert_line($fixlinenr, $fixedline);
4560 # Checks which are anchored on the added line.
4563 # check for malformed paths in #include statements (uses RAW line)
4564 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4566 if ($path =~ m{//}) {
4567 ERROR("MALFORMED_INCLUDE",
4568 "malformed #include filename\n" . $herecurr);
4570 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4571 ERROR("UAPI_INCLUDE",
4572 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4576 # no C99 // comments
4577 if ($line =~ m{//}) {
4578 if (ERROR("C99_COMMENTS",
4579 "do not use C99 // comments\n" . $herecurr) &&
4581 my $line = $fixed[$fixlinenr];
4582 if ($line =~ /\/\/(.*)$/) {
4583 my $comment = trim($1);
4584 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4588 # Remove C99 comments.
4590 $opline =~ s@//.*@@;
4592 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4593 # the whole statement.
4594 #print "APW <$lines[$realline_next - 1]>\n";
4595 if (defined $realline_next &&
4596 exists $lines[$realline_next - 1] &&
4597 !defined $suppress_export{$realline_next} &&
4598 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4599 # Handle definitions which produce identifiers with
4602 # EXPORT_SYMBOL(something_foo);
4604 $name =~ s/^\s*($Ident).*/$1/;
4605 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4606 $name =~ /^${Ident}_$2/) {
4607 #print "FOO C name<$name>\n";
4608 $suppress_export{$realline_next} = 1;
4610 } elsif ($stat !~ /(?:
4612 ^.DEFINE_$Ident\(\Q$name\E\)|
4613 ^.DECLARE_$Ident\(\Q$name\E\)|
4614 ^.LIST_HEAD\(\Q$name\E\)|
4615 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4616 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4618 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4619 $suppress_export{$realline_next} = 2;
4621 $suppress_export{$realline_next} = 1;
4624 if (!defined $suppress_export{$linenr} &&
4625 $prevline =~ /^.\s*$/ &&
4626 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4627 #print "FOO B <$lines[$linenr - 1]>\n";
4628 $suppress_export{$linenr} = 2;
4630 if (defined $suppress_export{$linenr} &&
4631 $suppress_export{$linenr} == 2) {
4632 WARN("EXPORT_SYMBOL",
4633 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4636 # check for global initialisers.
4637 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4638 !exclude_global_initialisers($realfile)) {
4639 if (ERROR("GLOBAL_INITIALISERS",
4640 "do not initialise globals to $1\n" . $herecurr) &&
4642 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4645 # check for static initialisers.
4646 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4647 if (ERROR("INITIALISED_STATIC",
4648 "do not initialise statics to $1\n" .
4651 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4655 # check for misordered declarations of char/short/int/long with signed/unsigned
4656 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4658 WARN("MISORDERED_TYPE",
4659 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4662 # check for unnecessary <signed> int declarations of short/long/long long
4663 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4664 my $type = trim($1);
4665 next if ($type !~ /\bint\b/);
4666 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4667 my $new_type = $type;
4668 $new_type =~ s/\b\s*int\s*\b/ /;
4669 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4670 $new_type =~ s/^const\s+//;
4671 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4672 $new_type = "const $new_type" if ($type =~ /^const\b/);
4673 $new_type =~ s/\s+/ /g;
4674 $new_type = trim($new_type);
4675 if (WARN("UNNECESSARY_INT",
4676 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4678 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4682 # check for static const char * arrays.
4683 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4684 WARN("STATIC_CONST_CHAR_ARRAY",
4685 "static const char * array should probably be static const char * const\n" .
4689 # check for initialized const char arrays that should be static const
4690 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4691 if (WARN("STATIC_CONST_CHAR_ARRAY",
4692 "const array should probably be static const\n" . $herecurr) &&
4694 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4698 # check for static char foo[] = "bar" declarations.
4699 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4700 WARN("STATIC_CONST_CHAR_ARRAY",
4701 "static char array declaration should probably be static const char\n" .
4705 # check for const <foo> const where <foo> is not a pointer or array type
4706 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4708 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4710 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4711 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4713 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4717 # check for const static or static <non ptr type> const declarations
4718 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4719 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4720 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4721 if (WARN("STATIC_CONST",
4722 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4724 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4725 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4729 # check for non-global char *foo[] = {"bar", ...} declarations.
4730 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4731 WARN("STATIC_CONST_CHAR_ARRAY",
4732 "char * array declaration might be better as static const\n" .
4736 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4737 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4739 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4741 if (WARN("ARRAY_SIZE",
4742 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4744 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4749 # check for function declarations without arguments like "int foo()"
4750 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4751 if (ERROR("FUNCTION_WITHOUT_ARGS",
4752 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4754 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4758 # check for new typedefs, only function parameters and sparse annotations
4760 if ($line =~ /\btypedef\s/ &&
4761 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4762 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4763 $line !~ /\b$typeTypedefs\b/ &&
4764 $line !~ /\b__bitwise\b/) {
4765 WARN("NEW_TYPEDEFS",
4766 "do not add new typedefs\n" . $herecurr);
4769 # * goes on variable not on type
4771 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4773 my ($ident, $from, $to) = ($1, $2, $2);
4775 # Should start with a space.
4776 $to =~ s/^(\S)/ $1/;
4777 # Should not end with a space.
4779 # '*'s should not have spaces between.
4780 while ($to =~ s/\*\s+\*/\*\*/) {
4783 ## print "1: from<$from> to<$to> ident<$ident>\n";
4785 if (ERROR("POINTER_LOCATION",
4786 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4788 my $sub_from = $ident;
4789 my $sub_to = $ident;
4790 $sub_to =~ s/\Q$from\E/$to/;
4791 $fixed[$fixlinenr] =~
4792 s@\Q$sub_from\E@$sub_to@;
4796 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4798 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4800 # Should start with a space.
4801 $to =~ s/^(\S)/ $1/;
4802 # Should not end with a space.
4804 # '*'s should not have spaces between.
4805 while ($to =~ s/\*\s+\*/\*\*/) {
4807 # Modifiers should have spaces.
4808 $to =~ s/(\b$Modifier$)/$1 /;
4810 ## print "2: from<$from> to<$to> ident<$ident>\n";
4811 if ($from ne $to && $ident !~ /^$Modifier$/) {
4812 if (ERROR("POINTER_LOCATION",
4813 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4816 my $sub_from = $match;
4817 my $sub_to = $match;
4818 $sub_to =~ s/\Q$from\E/$to/;
4819 $fixed[$fixlinenr] =~
4820 s@\Q$sub_from\E@$sub_to@;
4825 # do not use BUG() or variants
4826 if ($line =~ /\b(?!AA_|BUILD_|DCCP_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4827 my $msg_level = \&WARN;
4828 $msg_level = \&CHK if ($file);
4829 &{$msg_level}("AVOID_BUG",
4830 "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr);
4833 # avoid LINUX_VERSION_CODE
4834 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4835 WARN("LINUX_VERSION_CODE",
4836 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4839 # check for uses of printk_ratelimit
4840 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4841 WARN("PRINTK_RATELIMITED",
4842 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4845 # printk should use KERN_* levels
4846 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4847 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4848 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4851 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4852 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4856 $modifier = "" if (!defined($modifier));
4857 my $level = lc($orig);
4858 $level = "warn" if ($level eq "warning");
4859 my $level2 = $level;
4860 $level2 = "dbg" if ($level eq "debug");
4861 $level .= $modifier;
4862 $level2 .= $modifier;
4863 WARN("PREFER_PR_LEVEL",
4864 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4867 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4868 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4870 my $level = lc($orig);
4871 $level = "warn" if ($level eq "warning");
4872 $level = "dbg" if ($level eq "debug");
4873 WARN("PREFER_DEV_LEVEL",
4874 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4877 # trace_printk should not be used in production code.
4878 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4879 WARN("TRACE_PRINTK",
4880 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4883 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4884 # number of false positives, but assembly files are not checked, so at
4885 # least the arch entry code will not trigger this warning.
4886 if ($line =~ /\bENOSYS\b/) {
4888 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4891 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4892 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4893 # Similarly to ENOSYS warning a small number of false positives is expected.
4894 if (!$file && $line =~ /\bENOTSUPP\b/) {
4895 if (WARN("ENOTSUPP",
4896 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4898 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4902 # function brace can't be on same line, except for #defines of do while,
4903 # or if closed on same line
4904 if ($perl_version_ok &&
4905 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4906 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4908 if (ERROR("OPEN_BRACE",
4909 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4911 fix_delete_line($fixlinenr, $rawline);
4912 my $fixed_line = $rawline;
4913 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4916 fix_insert_line($fixlinenr, ltrim($line1));
4917 fix_insert_line($fixlinenr, "\+{");
4918 if ($line2 !~ /^\s*$/) {
4919 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4924 # open braces for enum, union and struct go on the same line.
4925 if ($line =~ /^.\s*{/ &&
4926 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4927 if (ERROR("OPEN_BRACE",
4928 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4929 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4930 fix_delete_line($fixlinenr - 1, $prevrawline);
4931 fix_delete_line($fixlinenr, $rawline);
4932 my $fixedline = rtrim($prevrawline) . " {";
4933 fix_insert_line($fixlinenr, $fixedline);
4934 $fixedline = $rawline;
4935 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4936 if ($fixedline !~ /^\+\s*$/) {
4937 fix_insert_line($fixlinenr, $fixedline);
4942 # missing space after union, struct or enum definition
4943 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4945 "missing space after $1 definition\n" . $herecurr) &&
4947 $fixed[$fixlinenr] =~
4948 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4952 # Function pointer declarations
4953 # check spacing between type, funcptr, and args
4954 # canonical declaration is "type (*funcptr)(args...)"
4955 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4957 my $pre_pointer_space = $2;
4958 my $post_pointer_space = $3;
4960 my $post_funcname_space = $5;
4961 my $pre_args_space = $6;
4963 # the $Declare variable will capture all spaces after the type
4964 # so check it for a missing trailing missing space but pointer return types
4965 # don't need a space so don't warn for those.
4966 my $post_declare_space = "";
4967 if ($declare =~ /(\s+)$/) {
4968 $post_declare_space = $1;
4969 $declare = rtrim($declare);
4971 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4973 "missing space after return type\n" . $herecurr);
4974 $post_declare_space = " ";
4977 # unnecessary space "type (*funcptr)(args...)"
4978 # This test is not currently implemented because these declarations are
4980 # int foo(int bar, ...)
4981 # and this is form shouldn't/doesn't generate a checkpatch warning.
4983 # elsif ($declare =~ /\s{2,}$/) {
4985 # "Multiple spaces after return type\n" . $herecurr);
4988 # unnecessary space "type ( *funcptr)(args...)"
4989 if (defined $pre_pointer_space &&
4990 $pre_pointer_space =~ /^\s/) {
4992 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4995 # unnecessary space "type (* funcptr)(args...)"
4996 if (defined $post_pointer_space &&
4997 $post_pointer_space =~ /^\s/) {
4999 "Unnecessary space before function pointer name\n" . $herecurr);
5002 # unnecessary space "type (*funcptr )(args...)"
5003 if (defined $post_funcname_space &&
5004 $post_funcname_space =~ /^\s/) {
5006 "Unnecessary space after function pointer name\n" . $herecurr);
5009 # unnecessary space "type (*funcptr) (args...)"
5010 if (defined $pre_args_space &&
5011 $pre_args_space =~ /^\s/) {
5013 "Unnecessary space before function pointer arguments\n" . $herecurr);
5016 if (show_type("SPACING") && $fix) {
5017 $fixed[$fixlinenr] =~
5018 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5022 # check for spacing round square brackets; allowed:
5023 # 1. with a type on the left -- int [] a;
5024 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5025 # 3. inside a curly brace -- = { [0...10] = 5 }
5026 while ($line =~ /(.*?\s)\[/g) {
5027 my ($where, $prefix) = ($-[1], $1);
5028 if ($prefix !~ /$Type\s+$/ &&
5029 ($where != 0 || $prefix !~ /^.\s+$/) &&
5030 $prefix !~ /[{,:]\s+$/) {
5031 if (ERROR("BRACKET_SPACE",
5032 "space prohibited before open square bracket '['\n" . $herecurr) &&
5034 $fixed[$fixlinenr] =~
5035 s/^(\+.*?)\s+\[/$1\[/;
5040 # check for spaces between functions and their parentheses.
5041 while ($line =~ /($Ident)\s+\(/g) {
5043 my $ctx_before = substr($line, 0, $-[1]);
5044 my $ctx = "$ctx_before$name";
5046 # Ignore those directives where spaces _are_ permitted.
5048 if|for|while|switch|return|case|
5049 volatile|__volatile__|
5050 __attribute__|format|__extension__|
5051 asm|__asm__|scoped_guard)$/x)
5053 # cpp #define statements have non-optional spaces, ie
5054 # if there is a space between the name and the open
5055 # parenthesis it is simply not a parameter group.
5056 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5058 # cpp #elif statement condition may start with a (
5059 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5061 # If this whole things ends with a type its most
5062 # likely a typedef for a function.
5063 } elsif ($ctx =~ /$Type$/) {
5067 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5069 $fixed[$fixlinenr] =~
5070 s/\b$name\s+\(/$name\(/;
5075 # Check operator spacing.
5076 if (!($line=~/\#\s*include/)) {
5077 my $fixed_line = "";
5081 <<=|>>=|<=|>=|==|!=|
5082 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5083 =>|->|<<|>>|<|>|=|!|~|
5084 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5087 my @elements = split(/($ops|;)/, $opline);
5089 ## print("element count: <" . $#elements . ">\n");
5090 ## foreach my $el (@elements) {
5091 ## print("el: <$el>\n");
5094 my @fix_elements = ();
5097 foreach my $el (@elements) {
5098 push(@fix_elements, substr($rawline, $off, length($el)));
5099 $off += length($el);
5104 my $blank = copy_spacing($opline);
5105 my $last_after = -1;
5107 for (my $n = 0; $n < $#elements; $n += 2) {
5109 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5111 ## print("n: <$n> good: <$good>\n");
5113 $off += length($elements[$n]);
5115 # Pick up the preceding and succeeding characters.
5116 my $ca = substr($opline, 0, $off);
5118 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5119 $cc = substr($opline, $off + length($elements[$n + 1]));
5121 my $cb = "$ca$;$cc";
5124 $a = 'V' if ($elements[$n] ne '');
5125 $a = 'W' if ($elements[$n] =~ /\s$/);
5126 $a = 'C' if ($elements[$n] =~ /$;$/);
5127 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5128 $a = 'O' if ($elements[$n] eq '');
5129 $a = 'E' if ($ca =~ /^\s*$/);
5131 my $op = $elements[$n + 1];
5134 if (defined $elements[$n + 2]) {
5135 $c = 'V' if ($elements[$n + 2] ne '');
5136 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5137 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5138 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5139 $c = 'O' if ($elements[$n + 2] eq '');
5140 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5145 my $ctx = "${a}x${c}";
5147 my $at = "(ctx:$ctx)";
5149 my $ptr = substr($blank, 0, $off) . "^";
5150 my $hereptr = "$hereline$ptr\n";
5152 # Pull out the value of this operator.
5153 my $op_type = substr($curr_values, $off + 1, 1);
5155 # Get the full operator variant.
5156 my $opv = $op . substr($curr_vars, $off, 1);
5158 # Ignore operators passed as parameters.
5159 if ($op_type ne 'V' &&
5160 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5163 # } elsif ($op =~ /^$;+$/) {
5165 # ; should have either the end of line or a space or \ after it
5166 } elsif ($op eq ';') {
5167 if ($ctx !~ /.x[WEBC]/ &&
5168 $cc !~ /^\\/ && $cc !~ /^;/) {
5169 if (ERROR("SPACING",
5170 "space required after that '$op' $at\n" . $hereptr)) {
5171 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5177 } elsif ($op eq '//') {
5179 # : when part of a bitfield
5180 } elsif ($opv eq ':B') {
5181 # skip the bitfield test for now
5185 } elsif ($op eq '->') {
5186 if ($ctx =~ /Wx.|.xW/) {
5187 if (ERROR("SPACING",
5188 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5189 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5190 if (defined $fix_elements[$n + 2]) {
5191 $fix_elements[$n + 2] =~ s/^\s+//;
5197 # , must not have a space before and must have a space on the right.
5198 } elsif ($op eq ',') {
5199 my $rtrim_before = 0;
5200 my $space_after = 0;
5201 if ($ctx =~ /Wx./) {
5202 if (ERROR("SPACING",
5203 "space prohibited before that '$op' $at\n" . $hereptr)) {
5208 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5209 if (ERROR("SPACING",
5210 "space required after that '$op' $at\n" . $hereptr)) {
5216 if ($rtrim_before || $space_after) {
5217 if ($rtrim_before) {
5218 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5220 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5227 # '*' as part of a type definition -- reported already.
5228 } elsif ($opv eq '*_') {
5229 #warn "'*' is part of type\n";
5231 # unary operators should have a space before and
5232 # none after. May be left adjacent to another
5233 # unary operator, or a cast
5234 } elsif ($op eq '!' || $op eq '~' ||
5235 $opv eq '*U' || $opv eq '-U' ||
5236 $opv eq '&U' || $opv eq '&&U') {
5237 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5238 if (ERROR("SPACING",
5239 "space required before that '$op' $at\n" . $hereptr)) {
5240 if ($n != $last_after + 2) {
5241 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5246 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5247 # A unary '*' may be const
5249 } elsif ($ctx =~ /.xW/) {
5250 if (ERROR("SPACING",
5251 "space prohibited after that '$op' $at\n" . $hereptr)) {
5252 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5253 if (defined $fix_elements[$n + 2]) {
5254 $fix_elements[$n + 2] =~ s/^\s+//;
5260 # unary ++ and unary -- are allowed no space on one side.
5261 } elsif ($op eq '++' or $op eq '--') {
5262 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5263 if (ERROR("SPACING",
5264 "space required one side of that '$op' $at\n" . $hereptr)) {
5265 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5269 if ($ctx =~ /Wx[BE]/ ||
5270 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5271 if (ERROR("SPACING",
5272 "space prohibited before that '$op' $at\n" . $hereptr)) {
5273 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5277 if ($ctx =~ /ExW/) {
5278 if (ERROR("SPACING",
5279 "space prohibited after that '$op' $at\n" . $hereptr)) {
5280 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5281 if (defined $fix_elements[$n + 2]) {
5282 $fix_elements[$n + 2] =~ s/^\s+//;
5288 # << and >> may either have or not have spaces both sides
5289 } elsif ($op eq '<<' or $op eq '>>' or
5290 $op eq '&' or $op eq '^' or $op eq '|' or
5291 $op eq '+' or $op eq '-' or
5292 $op eq '*' or $op eq '/' or
5296 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5298 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5299 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5300 $fix_elements[$n + 2] =~ s/^\s+//;
5303 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5305 "space preferred before that '$op' $at\n" . $hereptr)) {
5306 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5310 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5311 if (ERROR("SPACING",
5312 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5313 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5314 if (defined $fix_elements[$n + 2]) {
5315 $fix_elements[$n + 2] =~ s/^\s+//;
5321 # A colon needs no spaces before when it is
5322 # terminating a case value or a label.
5323 } elsif ($opv eq ':C' || $opv eq ':L') {
5324 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5325 if (ERROR("SPACING",
5326 "space prohibited before that '$op' $at\n" . $hereptr)) {
5327 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5332 # All the others need spaces both sides.
5333 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5336 # Ignore email addresses <foo@bar>
5338 $cc =~ /^\S+\@\S+>/) ||
5340 $ca =~ /<\S+\@\S+$/))
5345 # for asm volatile statements
5346 # ignore a colon with another
5347 # colon immediately before or after
5349 ($ca =~ /:$/ || $cc =~ /^:/)) {
5353 # messages are ERROR, but ?: are CHK
5355 my $msg_level = \&ERROR;
5356 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5358 if (&{$msg_level}("SPACING",
5359 "spaces required around that '$op' $at\n" . $hereptr)) {
5360 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5361 if (defined $fix_elements[$n + 2]) {
5362 $fix_elements[$n + 2] =~ s/^\s+//;
5368 $off += length($elements[$n + 1]);
5370 ## print("n: <$n> GOOD: <$good>\n");
5372 $fixed_line = $fixed_line . $good;
5375 if (($#elements % 2) == 0) {
5376 $fixed_line = $fixed_line . $fix_elements[$#elements];
5379 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5380 $fixed[$fixlinenr] = $fixed_line;
5386 # check for whitespace before a non-naked semicolon
5387 if ($line =~ /^\+.*\S\s+;\s*$/) {
5389 "space prohibited before semicolon\n" . $herecurr) &&
5391 1 while $fixed[$fixlinenr] =~
5392 s/^(\+.*\S)\s+;/$1;/;
5396 # check for multiple assignments
5397 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5398 CHK("MULTIPLE_ASSIGNMENTS",
5399 "multiple assignments should be avoided\n" . $herecurr);
5402 ## # check for multiple declarations, allowing for a function declaration
5404 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5405 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5407 ## # Remove any bracketed sections to ensure we do not
5408 ## # falsely report the parameters of functions.
5410 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5412 ## if ($ln =~ /,/) {
5413 ## WARN("MULTIPLE_DECLARATION",
5414 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5418 #need space before brace following if, while, etc
5419 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5420 $line =~ /\b(?:else|do)\{/) {
5421 if (ERROR("SPACING",
5422 "space required before the open brace '{'\n" . $herecurr) &&
5424 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5428 ## # check for blank lines before declarations
5429 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5430 ## $prevrawline =~ /^.\s*$/) {
5432 ## "No blank lines before declarations\n" . $hereprev);
5436 # closing brace should have a space following it when it has anything
5438 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5439 if (ERROR("SPACING",
5440 "space required after that close brace '}'\n" . $herecurr) &&
5442 $fixed[$fixlinenr] =~
5443 s/}((?!(?:,|;|\)))\S)/} $1/;
5447 # check spacing on square brackets
5448 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5449 if (ERROR("SPACING",
5450 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5452 $fixed[$fixlinenr] =~
5456 if ($line =~ /\s\]/) {
5457 if (ERROR("SPACING",
5458 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5460 $fixed[$fixlinenr] =~
5465 # check spacing on parentheses
5466 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5467 $line !~ /for\s*\(\s+;/) {
5468 if (ERROR("SPACING",
5469 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5471 $fixed[$fixlinenr] =~
5475 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5476 $line !~ /for\s*\(.*;\s+\)/ &&
5477 $line !~ /:\s+\)/) {
5478 if (ERROR("SPACING",
5479 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5481 $fixed[$fixlinenr] =~
5486 # check unnecessary parentheses around addressof/dereference single $Lvals
5487 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5489 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5491 if (CHK("UNNECESSARY_PARENTHESES",
5492 "Unnecessary parentheses around $var\n" . $herecurr) &&
5494 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5498 # check for unnecessary parentheses around function pointer uses
5499 # ie: (foo->bar)(); should be foo->bar();
5500 # but not "if (foo->bar) (" to avoid some false positives
5501 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5503 if (CHK("UNNECESSARY_PARENTHESES",
5504 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5506 my $var2 = deparenthesize($var);
5508 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5512 # check for unnecessary parentheses around comparisons in if uses
5513 # when !drivers/staging or command-line uses --strict
5514 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5515 $perl_version_ok && defined($stat) &&
5516 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5518 my $test = substr($2, 1, -1);
5520 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5522 # avoid parentheses around potential macro args
5523 next if ($match =~ /^\s*\w+\s*$/);
5524 if (!defined($herectx)) {
5525 $herectx = $here . "\n";
5526 my $cnt = statement_rawlines($if_stat);
5527 for (my $n = 0; $n < $cnt; $n++) {
5528 my $rl = raw_line($linenr, $n);
5529 $herectx .= $rl . "\n";
5530 last if $rl =~ /^[ \+].*\{/;
5533 CHK("UNNECESSARY_PARENTHESES",
5534 "Unnecessary parentheses around '$match'\n" . $herectx);
5538 # check that goto labels aren't indented (allow a single space indentation)
5539 # and ignore bitfield definitions like foo:1
5540 # Strictly, labels can have whitespace after the identifier and before the :
5541 # but this is not allowed here as many ?: uses would appear to be labels
5542 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5543 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5544 $sline !~ /^.\s+default:/) {
5545 if (WARN("INDENTED_LABEL",
5546 "labels should not be indented\n" . $herecurr) &&
5548 $fixed[$fixlinenr] =~
5553 # check if a statement with a comma should be two statements like:
5554 # foo = bar(), /* comma should be semicolon */
5556 if (defined($stat) &&
5557 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5558 my $cnt = statement_rawlines($stat);
5559 my $herectx = get_stat_here($linenr, $cnt, $here);
5560 WARN("SUSPECT_COMMA_SEMICOLON",
5561 "Possible comma where semicolon could be used\n" . $herectx);
5564 # return is not a function
5565 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5567 if ($perl_version_ok &&
5568 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5570 $value = deparenthesize($value);
5571 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5572 ERROR("RETURN_PARENTHESES",
5573 "return is not a function, parentheses are not required\n" . $herecurr);
5575 } elsif ($spacing !~ /\s+/) {
5577 "space required before the open parenthesis '('\n" . $herecurr);
5581 # unnecessary return in a void function
5582 # at end-of-function, with the previous line a single leading tab, then return;
5583 # and the line before that not a goto label target like "out:"
5584 if ($sline =~ /^[ \+]}\s*$/ &&
5585 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5587 $lines[$linenr - 3] =~ /^[ +]/ &&
5588 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5590 "void function return statements are not generally useful\n" . $hereprev);
5593 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5594 if ($perl_version_ok &&
5595 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5596 my $openparens = $1;
5597 my $count = $openparens =~ tr@\(@\(@;
5599 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5600 my $comp = $4; #Not $1 because of $LvalOrFunc
5601 $msg = " - maybe == should be = ?" if ($comp eq "==");
5602 WARN("UNNECESSARY_PARENTHESES",
5603 "Unnecessary parentheses$msg\n" . $herecurr);
5607 # comparisons with a constant or upper case identifier on the left
5608 # avoid cases like "foo + BAR < baz"
5609 # only fix matches surrounded by parentheses to avoid incorrect
5610 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5611 if ($perl_version_ok &&
5612 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5617 my $newcomp = $comp;
5618 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5619 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5620 WARN("CONSTANT_COMPARISON",
5621 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5625 } elsif ($comp eq "<=") {
5627 } elsif ($comp eq ">") {
5629 } elsif ($comp eq ">=") {
5632 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5636 # Return of what appears to be an errno should normally be negative
5637 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5639 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5640 WARN("USE_NEGATIVE_ERRNO",
5641 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5645 # Need a space before open parenthesis after if, while etc
5646 if ($line =~ /\b(if|while|for|switch)\(/) {
5647 if (ERROR("SPACING",
5648 "space required before the open parenthesis '('\n" . $herecurr) &&
5650 $fixed[$fixlinenr] =~
5651 s/\b(if|while|for|switch)\(/$1 \(/;
5655 # Check for illegal assignment in if conditional -- and check for trailing
5656 # statements after the conditional.
5657 if ($line =~ /do\s*(?!{)/) {
5658 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5659 ctx_statement_block($linenr, $realcnt, 0)
5660 if (!defined $stat);
5661 my ($stat_next) = ctx_statement_block($line_nr_next,
5662 $remain_next, $off_next);
5663 $stat_next =~ s/\n./\n /g;
5664 ##print "stat<$stat> stat_next<$stat_next>\n";
5666 if ($stat_next =~ /^\s*while\b/) {
5667 # If the statement carries leading newlines,
5668 # then count those as offsets.
5670 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5672 statement_rawlines($whitespace) - 1;
5674 $suppress_whiletrailers{$line_nr_next +
5678 if (!defined $suppress_whiletrailers{$linenr} &&
5679 defined($stat) && defined($cond) &&
5680 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5681 my ($s, $c) = ($stat, $cond);
5682 my $fixed_assign_in_if = 0;
5684 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5685 if (ERROR("ASSIGN_IN_IF",
5686 "do not use assignment in if condition\n" . $herecurr) &&
5687 $fix && $perl_version_ok) {
5688 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5696 fix_delete_line($fixlinenr, $rawline);
5697 fix_insert_line($fixlinenr, "$space$statement;");
5698 my $newline = "${space}if (";
5699 $newline .= '!' if defined($not);
5700 $newline .= '(' if (defined $not && defined($test) && defined($against));
5701 $newline .= "$assigned";
5702 $newline .= " $test $against" if (defined($test) && defined($against));
5703 $newline .= ')' if (defined $not && defined($test) && defined($against));
5705 $newline .= " {" if (defined($brace));
5706 fix_insert_line($fixlinenr + 1, $newline);
5707 $fixed_assign_in_if = 1;
5712 # Find out what is on the end of the line after the
5714 substr($s, 0, length($c), '');
5716 $s =~ s/$;//g; # Remove any comments
5717 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5718 $c !~ /}\s*while\s*/)
5720 # Find out how long the conditional actually is.
5721 my @newlines = ($c =~ /\n/gs);
5722 my $cond_lines = 1 + $#newlines;
5725 $stat_real = raw_line($linenr, $cond_lines)
5726 . "\n" if ($cond_lines);
5727 if (defined($stat_real) && $cond_lines > 1) {
5728 $stat_real = "[...]\n$stat_real";
5731 if (ERROR("TRAILING_STATEMENTS",
5732 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5733 !$fixed_assign_in_if &&
5735 $fix && $perl_version_ok &&
5736 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5739 my $rest = rtrim($4);
5740 if ($rest =~ /;$/) {
5741 $fixed[$fixlinenr] = "\+$indent$test";
5742 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5748 # Check for bitwise tests written as boolean
5760 WARN("HEXADECIMAL_BOOLEAN_TEST",
5761 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5764 # if and else should not have general statements after it
5765 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5767 $s =~ s/$;//g; # Remove any comments
5768 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5769 ERROR("TRAILING_STATEMENTS",
5770 "trailing statements should be on next line\n" . $herecurr);
5773 # if should not continue a brace
5774 if ($line =~ /}\s*if\b/) {
5775 ERROR("TRAILING_STATEMENTS",
5776 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5779 # case and default should not have general statements after them
5780 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5782 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5786 ERROR("TRAILING_STATEMENTS",
5787 "trailing statements should be on next line\n" . $herecurr);
5790 # Check for }<nl>else {, these must be at the same
5791 # indent level to be relevant to each other.
5792 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5793 $previndent == $indent) {
5794 if (ERROR("ELSE_AFTER_BRACE",
5795 "else should follow close brace '}'\n" . $hereprev) &&
5796 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5797 fix_delete_line($fixlinenr - 1, $prevrawline);
5798 fix_delete_line($fixlinenr, $rawline);
5799 my $fixedline = $prevrawline;
5800 $fixedline =~ s/}\s*$//;
5801 if ($fixedline !~ /^\+\s*$/) {
5802 fix_insert_line($fixlinenr, $fixedline);
5804 $fixedline = $rawline;
5805 $fixedline =~ s/^(.\s*)else/$1} else/;
5806 fix_insert_line($fixlinenr, $fixedline);
5810 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5811 $previndent == $indent) {
5812 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5814 # Find out what is on the end of the line after the
5816 substr($s, 0, length($c), '');
5819 if ($s =~ /^\s*;/) {
5820 if (ERROR("WHILE_AFTER_BRACE",
5821 "while should follow close brace '}'\n" . $hereprev) &&
5822 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5823 fix_delete_line($fixlinenr - 1, $prevrawline);
5824 fix_delete_line($fixlinenr, $rawline);
5825 my $fixedline = $prevrawline;
5826 my $trailing = $rawline;
5827 $trailing =~ s/^\+//;
5828 $trailing = trim($trailing);
5829 $fixedline =~ s/}\s*$/} $trailing/;
5830 fix_insert_line($fixlinenr, $fixedline);
5835 #Specific variable tests
5836 while ($line =~ m{($Constant|$Lval)}g) {
5840 if ($var !~ /^$Constant$/ &&
5841 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5842 #Ignore some autogenerated defines and enum values
5843 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5844 #Ignore Page<foo> variants
5845 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5846 #Ignore ETHTOOL_LINK_MODE_<foo> variants
5847 $var !~ /^ETHTOOL_LINK_MODE_/ &&
5848 #Ignore SI style variants like nS, mV and dB
5849 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5850 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5851 #Ignore some three character SI units explicitly, like MiB and KHz
5852 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5853 while ($var =~ m{\b($Ident)}g) {
5855 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5857 seed_camelcase_includes();
5858 if (!$file && !$camelcase_file_seeded) {
5859 seed_camelcase_file($realfile);
5860 $camelcase_file_seeded = 1;
5863 if (!defined $camelcase{$word}) {
5864 $camelcase{$word} = 1;
5866 "Avoid CamelCase: <$word>\n" . $herecurr);
5872 #no spaces allowed after \ in define
5873 if ($line =~ /\#\s*define.*\\\s+$/) {
5874 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5875 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5877 $fixed[$fixlinenr] =~ s/\s+$//;
5881 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5882 # itself <asm/foo.h> (uses RAW line)
5883 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5885 my $checkfile = "include/linux/$file";
5886 if (-f "$root/$checkfile" &&
5887 $realfile ne $checkfile &&
5888 $1 !~ /$allowed_asm_includes/)
5890 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5891 if ($asminclude > 0) {
5892 if ($realfile =~ m{^arch/}) {
5893 CHK("ARCH_INCLUDE_LINUX",
5894 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5896 WARN("INCLUDE_LINUX",
5897 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5903 # multi-statement macros should be enclosed in a do while loop, grab the
5904 # first statement and ensure its the whole macro if its not enclosed
5905 # in a known good container
5906 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5907 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5910 my ($off, $dstat, $dcond, $rest);
5912 my $has_flow_statement = 0;
5913 my $has_arg_concat = 0;
5914 ($dstat, $dcond, $ln, $cnt, $off) =
5915 ctx_statement_block($linenr, $realcnt, 0);
5917 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5918 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5920 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5921 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5923 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5924 my $define_args = $1;
5925 my $define_stmt = $dstat;
5928 if (defined $define_args && $define_args ne "") {
5929 $define_args = substr($define_args, 1, length($define_args) - 2);
5930 $define_args =~ s/\s*//g;
5931 $define_args =~ s/\\\+?//g;
5932 @def_args = split(",", $define_args);
5936 $dstat =~ s/\\\n.//g;
5937 $dstat =~ s/^\s*//s;
5938 $dstat =~ s/\s*$//s;
5940 # Flatten any parentheses and braces
5941 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5942 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5943 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5947 # Flatten any obvious string concatenation.
5948 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5949 $dstat =~ s/$Ident\s*($String)/$1/)
5953 # Make asm volatile uses seem like a generic function
5954 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5956 my $exceptions = qr{
5969 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5972 my $stmt_cnt = statement_rawlines($ctx);
5973 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5976 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5977 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5978 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5979 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5980 $dstat !~ /$exceptions/ &&
5981 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5982 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5983 $dstat !~ /^case\b/ && # case ...
5984 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5985 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5986 $dstat !~ /^for\s*$Constant$/ && # for (...)
5987 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5988 $dstat !~ /^do\s*{/ && # do {...
5989 $dstat !~ /^\(\{/ && # ({...
5990 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5992 if ($dstat =~ /^\s*if\b/) {
5993 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5994 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5995 } elsif ($dstat =~ /;/) {
5996 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5997 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5999 ERROR("COMPLEX_MACRO",
6000 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
6005 # Make $define_stmt single line, comment-free, etc
6006 my @stmt_array = split('\n', $define_stmt);
6009 foreach my $l (@stmt_array) {
6014 } elsif ($l =~ /^[\+ ]/) {
6015 $define_stmt .= substr($l, 1);
6018 $define_stmt =~ s/$;//g;
6019 $define_stmt =~ s/\s+/ /g;
6020 $define_stmt = trim($define_stmt);
6022 # check if any macro arguments are reused (ignore '...' and 'type')
6023 foreach my $arg (@def_args) {
6024 next if ($arg =~ /\.\.\./);
6025 next if ($arg =~ /^type$/i);
6026 my $tmp_stmt = $define_stmt;
6027 $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;
6028 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6029 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
6030 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6032 CHK("MACRO_ARG_REUSE",
6033 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6035 # check if any macro arguments may have other precedence issues
6036 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6037 ((defined($1) && $1 ne ',') ||
6038 (defined($2) && $2 ne ','))) {
6039 CHK("MACRO_ARG_PRECEDENCE",
6040 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6044 # check for macros with flow control, but without ## concatenation
6045 # ## concatenation is commonly a macro that defines a function so ignore those
6046 if ($has_flow_statement && !$has_arg_concat) {
6047 my $cnt = statement_rawlines($ctx);
6048 my $herectx = get_stat_here($linenr, $cnt, $here);
6050 WARN("MACRO_WITH_FLOW_CONTROL",
6051 "Macros with flow control statements should be avoided\n" . "$herectx");
6054 # check for line continuations outside of #defines, preprocessor #, and asm
6056 } elsif ($realfile =~ m@/vmlinux.lds.h$@) {
6057 $line =~ s/(\w+)/$maybe_linker_symbol{$1}++/ge;
6058 #print "REAL: $realfile\nln: $line\nkeys:", sort keys %maybe_linker_symbol;
6060 if ($prevline !~ /^..*\\$/ &&
6061 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6062 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
6063 $line =~ /^\+.*\\$/) {
6064 WARN("LINE_CONTINUATIONS",
6065 "Avoid unnecessary line continuations\n" . $herecurr);
6069 # do {} while (0) macro tests:
6070 # single-statement macros do not need to be enclosed in do while (0) loop,
6071 # macro should not end with a semicolon
6072 if ($perl_version_ok &&
6073 $realfile !~ m@/vmlinux.lds.h$@ &&
6074 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6077 my ($off, $dstat, $dcond, $rest);
6079 ($dstat, $dcond, $ln, $cnt, $off) =
6080 ctx_statement_block($linenr, $realcnt, 0);
6083 $dstat =~ s/\\\n.//g;
6086 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6091 my $cnt = statement_rawlines($ctx);
6092 my $herectx = get_stat_here($linenr, $cnt, $here);
6094 if (($stmts =~ tr/;/;/) == 1 &&
6095 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6096 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6097 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6099 if (defined $semis && $semis ne "") {
6100 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6101 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6103 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6105 my $cnt = statement_rawlines($ctx);
6106 my $herectx = get_stat_here($linenr, $cnt, $here);
6108 WARN("TRAILING_SEMICOLON",
6109 "macros should not use a trailing semicolon\n" . "$herectx");
6113 # check for redundant bracing round if etc
6114 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6115 my ($level, $endln, @chunks) =
6116 ctx_statement_full($linenr, $realcnt, 1);
6117 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6118 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6119 if ($#chunks > 0 && $level == 0) {
6123 my $herectx = $here . "\n";
6124 my $ln = $linenr - 1;
6125 for my $chunk (@chunks) {
6126 my ($cond, $block) = @{$chunk};
6128 # If the condition carries leading newlines, then count those as offsets.
6129 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6130 my $offset = statement_rawlines($whitespace) - 1;
6132 $allowed[$allow] = 0;
6133 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6135 # We have looked at and allowed this specific line.
6136 $suppress_ifbraces{$ln + $offset} = 1;
6138 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6139 $ln += statement_rawlines($block) - 1;
6141 substr($block, 0, length($cond), '');
6143 $seen++ if ($block =~ /^\s*{/);
6145 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6146 if (statement_lines($cond) > 1) {
6147 #print "APW: ALLOWED: cond<$cond>\n";
6148 $allowed[$allow] = 1;
6150 if ($block =~/\b(?:if|for|while)\b/) {
6151 #print "APW: ALLOWED: block<$block>\n";
6152 $allowed[$allow] = 1;
6154 if (statement_block_size($block) > 1) {
6155 #print "APW: ALLOWED: lines block<$block>\n";
6156 $allowed[$allow] = 1;
6161 my $sum_allowed = 0;
6162 foreach (@allowed) {
6165 if ($sum_allowed == 0) {
6167 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6168 } elsif ($sum_allowed != $allow &&
6171 "braces {} should be used on all arms of this statement\n" . $herectx);
6176 if (!defined $suppress_ifbraces{$linenr - 1} &&
6177 $line =~ /\b(if|while|for|else)\b/) {
6180 # Check the pre-context.
6181 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6182 #print "APW: ALLOWED: pre<$1>\n";
6186 my ($level, $endln, @chunks) =
6187 ctx_statement_full($linenr, $realcnt, $-[0]);
6189 # Check the condition.
6190 my ($cond, $block) = @{$chunks[0]};
6191 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6192 if (defined $cond) {
6193 substr($block, 0, length($cond), '');
6195 if (statement_lines($cond) > 1) {
6196 #print "APW: ALLOWED: cond<$cond>\n";
6199 if ($block =~/\b(?:if|for|while)\b/) {
6200 #print "APW: ALLOWED: block<$block>\n";
6203 if (statement_block_size($block) > 1) {
6204 #print "APW: ALLOWED: lines block<$block>\n";
6207 # Check the post-context.
6208 if (defined $chunks[1]) {
6209 my ($cond, $block) = @{$chunks[1]};
6210 if (defined $cond) {
6211 substr($block, 0, length($cond), '');
6213 if ($block =~ /^\s*\{/) {
6214 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6218 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6219 my $cnt = statement_rawlines($block);
6220 my $herectx = get_stat_here($linenr, $cnt, $here);
6223 "braces {} are not necessary for single statement blocks\n" . $herectx);
6227 # check for single line unbalanced braces
6228 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6229 $sline =~ /^.\s*else\s*\{\s*$/) {
6230 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6233 # check for unnecessary blank lines around braces
6234 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6236 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6237 $fix && $prevrawline =~ /^\+/) {
6238 fix_delete_line($fixlinenr - 1, $prevrawline);
6241 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6243 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6245 fix_delete_line($fixlinenr, $rawline);
6249 # no volatiles please
6250 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6251 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6253 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6256 # Check for user-visible strings broken across lines, which breaks the ability
6257 # to grep for the string. Make exceptions when the previous string ends in a
6258 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6259 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6260 if ($line =~ /^\+\s*$String/ &&
6261 $prevline =~ /"\s*$/ &&
6262 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6263 if (WARN("SPLIT_STRING",
6264 "quoted string split across lines\n" . $hereprev) &&
6266 $prevrawline =~ /^\+.*"\s*$/ &&
6267 $last_coalesced_string_linenr != $linenr - 1) {
6268 my $extracted_string = get_quoted_string($line, $rawline);
6269 my $comma_close = "";
6270 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6274 fix_delete_line($fixlinenr - 1, $prevrawline);
6275 fix_delete_line($fixlinenr, $rawline);
6276 my $fixedline = $prevrawline;
6277 $fixedline =~ s/"\s*$//;
6278 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6279 fix_insert_line($fixlinenr - 1, $fixedline);
6280 $fixedline = $rawline;
6281 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6282 if ($fixedline !~ /\+\s*$/) {
6283 fix_insert_line($fixlinenr, $fixedline);
6285 $last_coalesced_string_linenr = $linenr;
6289 # check for missing a space in a string concatenation
6290 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6291 WARN('MISSING_SPACE',
6292 "break quoted strings at a space character\n" . $hereprev);
6295 # check for an embedded function name in a string when the function is known
6296 # This does not work very well for -f --file checking as it depends on patch
6297 # context providing the function name or a single line form for in-file
6298 # function declarations
6299 if ($line =~ /^\+.*$String/ &&
6300 defined($context_function) &&
6301 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6302 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6303 WARN("EMBEDDED_FUNCTION_NAME",
6304 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6307 # check for unnecessary function tracing like uses
6308 # This does not use $logFunctions because there are many instances like
6309 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6310 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6311 if (WARN("TRACING_LOGGING",
6312 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6314 fix_delete_line($fixlinenr, $rawline);
6318 # check for spaces before a quoted newline
6319 if ($rawline =~ /^.*\".*\s\\n/) {
6320 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6321 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6323 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6328 # concatenated string without spaces between elements
6329 if ($line =~ /$String[A-Z_]/ ||
6330 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6331 if (CHK("CONCATENATED_STRING",
6332 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6334 while ($line =~ /($String)/g) {
6335 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6336 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6337 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6342 # uncoalesced string fragments
6343 if ($line =~ /$String\s*[Lu]?"/) {
6344 if (WARN("STRING_FRAGMENTS",
6345 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6347 while ($line =~ /($String)(?=\s*")/g) {
6348 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6349 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6354 # check for non-standard and hex prefixed decimal printf formats
6355 my $show_L = 1; #don't show the same defect twice
6357 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6358 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6359 $string =~ s/%%/__/g;
6361 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6363 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6367 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6369 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6372 # check for 0x<decimal>
6373 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6374 ERROR("PRINTF_0XDECIMAL",
6375 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6379 # check for line continuations in quoted strings with odd counts of "
6380 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6381 WARN("LINE_CONTINUATIONS",
6382 "Avoid line continuations in quoted strings\n" . $herecurr);
6386 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6388 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6392 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6394 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6397 # check for needless "if (<foo>) fn(<foo>)" uses
6398 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6399 my $tested = quotemeta($1);
6400 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6401 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6403 if (WARN('NEEDLESS_IF',
6404 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6407 my $leading_tabs = "";
6408 my $new_leading_tabs = "";
6409 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6414 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6415 $new_leading_tabs = $1;
6416 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6423 fix_delete_line($fixlinenr - 1, $prevrawline);
6424 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6430 # check for soon-to-be-deprecated single-argument k[v]free_rcu() API
6431 if ($line =~ /\bk[v]?free_rcu\s*\([^(]+\)/) {
6432 if ($line =~ /\bk[v]?free_rcu\s*\([^,]+\)/) {
6433 ERROR("DEPRECATED_API",
6434 "Single-argument k[v]free_rcu() API is deprecated, please pass rcu_head object or call k[v]free_rcu_mightsleep()." . $herecurr);
6439 # check for unnecessary "Out of Memory" messages
6440 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6441 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6442 (defined $1 || defined $3) &&
6445 my $testline = $lines[$linenr - 3];
6447 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6448 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6450 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6451 $s !~ /\b__GFP_NOWARN\b/ ) {
6453 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6457 # check for logging functions with KERN_<LEVEL>
6458 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6459 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6461 if (WARN("UNNECESSARY_KERN_LEVEL",
6462 "Possible unnecessary $level\n" . $herecurr) &&
6464 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6468 # check for logging continuations
6469 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6470 WARN("LOGGING_CONTINUATION",
6471 "Avoid logging continuation uses where feasible\n" . $herecurr);
6474 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6475 if (defined $stat &&
6476 $line =~ /\b$logFunctions\s*\(/ &&
6477 index($stat, '"') >= 0) {
6478 my $lc = $stat =~ tr@\n@@;
6479 $lc = $lc + $linenr;
6480 my $stat_real = get_stat_real($linenr, $lc);
6481 pos($stat_real) = index($stat_real, '"');
6482 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6485 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6486 if (WARN("UNNECESSARY_MODIFIER",
6487 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6488 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6491 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6496 # check for mask then right shift without a parentheses
6497 if ($perl_version_ok &&
6498 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6499 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6500 WARN("MASK_THEN_SHIFT",
6501 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6504 # check for pointer comparisons to NULL
6505 if ($perl_version_ok) {
6506 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6509 $equal = "" if ($4 eq "!=");
6510 if (CHK("COMPARISON_TO_NULL",
6511 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6513 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6518 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6519 if ($line =~ /(\b$InitAttribute\b)/) {
6521 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6524 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6525 ERROR("MISPLACED_INIT",
6526 "$attr should be placed after $var\n" . $herecurr)) ||
6527 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6528 WARN("MISPLACED_INIT",
6529 "$attr should be placed after $var\n" . $herecurr))) &&
6531 $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;
6536 # check for $InitAttributeData (ie: __initdata) with const
6537 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6539 $attr =~ /($InitAttributePrefix)(.*)/;
6540 my $attr_prefix = $1;
6542 if (ERROR("INIT_ATTRIBUTE",
6543 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6545 $fixed[$fixlinenr] =~
6546 s/$InitAttributeData/${attr_prefix}initconst/;
6550 # check for $InitAttributeConst (ie: __initconst) without const
6551 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6553 if (ERROR("INIT_ATTRIBUTE",
6554 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6556 my $lead = $fixed[$fixlinenr] =~
6557 /(^\+\s*(?:static\s+))/;
6559 $lead = "$lead " if ($lead !~ /^\+$/);
6560 $lead = "${lead}const ";
6561 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6565 # check for __read_mostly with const non-pointer (should just be const)
6566 if ($line =~ /\b__read_mostly\b/ &&
6567 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6568 if (ERROR("CONST_READ_MOSTLY",
6569 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6571 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6575 # don't use __constant_<foo> functions outside of include/uapi/
6576 if ($realfile !~ m@^include/uapi/@ &&
6577 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6578 my $constant_func = $1;
6579 my $func = $constant_func;
6580 $func =~ s/^__constant_//;
6581 if (WARN("CONSTANT_CONVERSION",
6582 "$constant_func should be $func\n" . $herecurr) &&
6584 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6588 # prefer usleep_range over udelay
6589 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6591 # ignore udelay's < 10, however
6592 if (! ($delay < 10) ) {
6594 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6596 if ($delay > 2000) {
6598 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6602 # warn about unexpectedly long msleep's
6603 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6606 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6610 # check for comparisons of jiffies
6611 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6612 WARN("JIFFIES_COMPARISON",
6613 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6616 # check for comparisons of get_jiffies_64()
6617 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6618 WARN("JIFFIES_COMPARISON",
6619 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6622 # warn about #ifdefs in C files
6623 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6624 # print "#ifdef in C files should be avoided\n";
6625 # print "$herecurr";
6629 # warn about spacing in #ifdefs
6630 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6631 if (ERROR("SPACING",
6632 "exactly one space required after that #$1\n" . $herecurr) &&
6634 $fixed[$fixlinenr] =~
6635 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6640 # check for spinlock_t definitions without a comment.
6641 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6642 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6644 if (!ctx_has_comment($first_line, $linenr)) {
6645 CHK("UNCOMMENTED_DEFINITION",
6646 "$1 definition without comment\n" . $herecurr);
6649 # check for memory barriers without a comment.
6656 my $barrier_stems = qr{
6664 my $all_barriers = qr{
6666 smp_(?:$barrier_stems)|
6667 virt_(?:$barrier_stems)
6670 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6671 if (!ctx_has_comment($first_line, $linenr)) {
6672 WARN("MEMORY_BARRIER",
6673 "memory barrier without comment\n" . $herecurr);
6677 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6679 if ($realfile !~ m@^include/asm-generic/@ &&
6680 $realfile !~ m@/barrier\.h$@ &&
6681 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6682 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6683 WARN("MEMORY_BARRIER",
6684 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6687 # check for waitqueue_active without a comment.
6688 if ($line =~ /\bwaitqueue_active\s*\(/) {
6689 if (!ctx_has_comment($first_line, $linenr)) {
6690 WARN("WAITQUEUE_ACTIVE",
6691 "waitqueue_active without comment\n" . $herecurr);
6695 # check for data_race without a comment.
6696 if ($line =~ /\bdata_race\s*\(/) {
6697 if (!ctx_has_comment($first_line, $linenr)) {
6699 "data_race without comment\n" . $herecurr);
6703 # check of hardware specific defines
6704 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6706 "architecture specific defines should be avoided\n" . $herecurr);
6709 # check that the storage class is not after a type
6710 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6711 WARN("STORAGE_CLASS",
6712 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6714 # Check that the storage class is at the beginning of a declaration
6715 if ($line =~ /\b$Storage\b/ &&
6716 $line !~ /^.\s*$Storage/ &&
6717 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6718 $1 !~ /[\,\)]\s*$/) {
6719 WARN("STORAGE_CLASS",
6720 "storage class should be at the beginning of the declaration\n" . $herecurr);
6723 # check the location of the inline attribute, that it is between
6724 # storage class and type.
6725 if ($line =~ /\b$Type\s+$Inline\b/ ||
6726 $line =~ /\b$Inline\s+$Storage\b/) {
6727 ERROR("INLINE_LOCATION",
6728 "inline keyword should sit between storage class and type\n" . $herecurr);
6731 # Check for __inline__ and __inline, prefer inline
6732 if ($realfile !~ m@\binclude/uapi/@ &&
6733 $line =~ /\b(__inline__|__inline)\b/) {
6735 "plain inline is preferred over $1\n" . $herecurr) &&
6737 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6742 # Check for compiler attributes
6743 if ($realfile !~ m@\binclude/uapi/@ &&
6744 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6746 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6749 "alias" => "__alias",
6750 "aligned" => "__aligned",
6751 "always_inline" => "__always_inline",
6752 "assume_aligned" => "__assume_aligned",
6754 "const" => "__attribute_const__",
6756 "designated_init" => "__designated_init",
6757 "externally_visible" => "__visible",
6758 "format" => "printf|scanf",
6759 "gnu_inline" => "__gnu_inline",
6760 "malloc" => "__malloc",
6762 "no_caller_saved_registers" => "__no_caller_saved_registers",
6763 "noclone" => "__noclone",
6764 "noinline" => "noinline",
6765 "nonstring" => "__nonstring",
6766 "noreturn" => "__noreturn",
6767 "packed" => "__packed",
6769 "section" => "__section",
6774 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6777 $params = $2 if defined($2);
6778 my $curr_attr = $orig_attr;
6779 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6780 if (exists($attr_list{$curr_attr})) {
6781 my $new = $attr_list{$curr_attr};
6782 if ($curr_attr eq "format" && $params) {
6783 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6786 $new = "$new$params";
6788 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6789 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6791 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6792 $fixed[$fixlinenr] =~ s/$remove//;
6793 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6794 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6795 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6800 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6801 if ($attr =~ /^_*unused/) {
6802 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6803 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6807 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6808 if ($perl_version_ok &&
6809 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6810 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6811 $line =~ /\b__weak\b/)) {
6812 ERROR("WEAK_DECLARATION",
6813 "Using weak declarations can have unintended link defects\n" . $herecurr);
6816 # check for c99 types like uint8_t used outside of uapi/ and tools/
6817 if ($realfile !~ m@\binclude/uapi/@ &&
6818 $realfile !~ m@\btools/@ &&
6819 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6821 if ($type =~ /\b($typeC99Typedefs)\b/) {
6823 my $kernel_type = 'u';
6824 $kernel_type = 's' if ($type =~ /^_*[si]/);
6827 if (CHK("PREFER_KERNEL_TYPES",
6828 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6830 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6835 # check for cast of C90 native int or longer types constants
6836 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6840 my $newconst = $const;
6841 $newconst =~ s/${Int_type}$//;
6842 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6843 if ($cast =~ /\blong\s+long\b/) {
6845 } elsif ($cast =~ /\blong\b/) {
6848 if (WARN("TYPECAST_INT_CONSTANT",
6849 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6851 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6855 # check for sizeof(&)
6856 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6857 WARN("SIZEOF_ADDRESS",
6858 "sizeof(& should be avoided\n" . $herecurr);
6861 # check for sizeof without parenthesis
6862 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6863 if (WARN("SIZEOF_PARENTHESIS",
6864 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6866 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6870 # check for struct spinlock declarations
6871 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6872 WARN("USE_SPINLOCK_T",
6873 "struct spinlock should be spinlock_t\n" . $herecurr);
6876 # check for seq_printf uses that could be seq_puts
6877 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6878 my $fmt = get_quoted_string($line, $rawline);
6881 if (WARN("PREFER_SEQ_PUTS",
6882 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6884 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6889 # check for vsprintf extension %p<foo> misuses
6890 if ($perl_version_ok &&
6892 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6893 $1 !~ /^_*volatile_*$/) {
6896 my $lc = $stat =~ tr@\n@@;
6897 $lc = $lc + $linenr;
6898 for (my $count = $linenr; $count <= $lc; $count++) {
6902 my $bad_specifier = "";
6903 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6906 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6910 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6911 ($extension eq "f" &&
6912 defined $qualifier && $qualifier !~ /^w/) ||
6913 ($extension eq "4" &&
6914 defined $qualifier && $qualifier !~ /^cc/)) {
6915 $bad_specifier = $specifier;
6918 if ($extension eq "x" && !defined($stat_real)) {
6919 if (!defined($stat_real)) {
6920 $stat_real = get_stat_real($linenr, $lc);
6922 WARN("VSPRINTF_SPECIFIER_PX",
6923 "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");
6926 if ($bad_specifier ne "") {
6927 my $stat_real = get_stat_real($linenr, $lc);
6928 my $msg_level = \&WARN;
6929 my $ext_type = "Invalid";
6931 if ($bad_specifier =~ /p[Ff]/) {
6932 $use = " - use %pS instead";
6933 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6934 } elsif ($bad_specifier =~ /pA/) {
6935 $use = " - '%pA' is only intended to be used from Rust code";
6936 $msg_level = \&ERROR;
6939 &{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6940 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6945 # Check for misused memsets
6946 if ($perl_version_ok &&
6948 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6954 if ($ms_size =~ /^(0x|)0$/i) {
6956 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6957 } elsif ($ms_size =~ /^(0x|)1$/i) {
6959 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6963 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6964 # if ($perl_version_ok &&
6966 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6967 # if (WARN("PREFER_ETHER_ADDR_COPY",
6968 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6970 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6974 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6975 # if ($perl_version_ok &&
6977 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6978 # WARN("PREFER_ETHER_ADDR_EQUAL",
6979 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6982 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6983 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6984 # if ($perl_version_ok &&
6986 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6990 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6991 # if (WARN("PREFER_ETH_ZERO_ADDR",
6992 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6994 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6996 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6997 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6998 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
7000 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
7005 # strcpy uses that should likely be strscpy
7006 if ($line =~ /\bstrcpy\s*\(/) {
7008 "Prefer strscpy over strcpy - see: https://github.com/KSPP/linux/issues/88\n" . $herecurr);
7011 # strlcpy uses that should likely be strscpy
7012 if ($line =~ /\bstrlcpy\s*\(/) {
7014 "Prefer strscpy over strlcpy - see: https://github.com/KSPP/linux/issues/89\n" . $herecurr);
7017 # strncpy uses that should likely be strscpy or strscpy_pad
7018 if ($line =~ /\bstrncpy\s*\(/) {
7020 "Prefer strscpy, strscpy_pad, or __nonstring over strncpy - see: https://github.com/KSPP/linux/issues/90\n" . $herecurr);
7023 # typecasts on min/max could be min_t/max_t
7024 if ($perl_version_ok &&
7026 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7027 if (defined $2 || defined $7) {
7029 my $cast1 = deparenthesize($2);
7031 my $cast2 = deparenthesize($7);
7035 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7036 $cast = "$cast1 or $cast2";
7037 } elsif ($cast1 ne "") {
7043 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7047 # check usleep_range arguments
7048 if ($perl_version_ok &&
7050 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7054 WARN("USLEEP_RANGE",
7055 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7056 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7058 WARN("USLEEP_RANGE",
7059 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7063 # check for naked sscanf
7064 if ($perl_version_ok &&
7066 $line =~ /\bsscanf\b/ &&
7067 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7068 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7069 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7070 my $lc = $stat =~ tr@\n@@;
7071 $lc = $lc + $linenr;
7072 my $stat_real = get_stat_real($linenr, $lc);
7073 WARN("NAKED_SSCANF",
7074 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7077 # check for simple sscanf that should be kstrto<foo>
7078 if ($perl_version_ok &&
7080 $line =~ /\bsscanf\b/) {
7081 my $lc = $stat =~ tr@\n@@;
7082 $lc = $lc + $linenr;
7083 my $stat_real = get_stat_real($linenr, $lc);
7084 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7086 my $count = $format =~ tr@%@%@;
7088 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7089 WARN("SSCANF_TO_KSTRTO",
7090 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7095 # check for new externs in .h files.
7096 if ($realfile =~ /\.h$/ &&
7097 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7098 if (CHK("AVOID_EXTERNS",
7099 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
7101 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7105 # check for new externs in .c files.
7106 if ($realfile =~ /\.c$/ && defined $stat &&
7107 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7109 my $function_name = $1;
7110 my $paren_space = $2;
7113 if (defined $cond) {
7114 substr($s, 0, length($cond), '');
7118 WARN("AVOID_EXTERNS",
7119 "externs should be avoided in .c files\n" . $herecurr);
7122 if ($paren_space =~ /\n/) {
7123 WARN("FUNCTION_ARGUMENTS",
7124 "arguments for function declarations should follow identifier\n" . $herecurr);
7127 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7128 $stat =~ /^\+extern struct\s+(\w+)\s+(\w+)\[\];/)
7130 my ($st_type, $st_name) = ($1, $2);
7132 for my $s (keys %maybe_linker_symbol) {
7133 #print "Linker symbol? $st_name : $s\n";
7134 goto LIKELY_LINKER_SYMBOL
7135 if $st_name =~ /$s/;
7137 WARN("AVOID_EXTERNS",
7138 "found a file-scoped extern type:$st_type name:$st_name in .c file\n"
7139 . "is this a linker symbol ?\n" . $herecurr);
7140 LIKELY_LINKER_SYMBOL:
7142 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7143 $stat =~ /^.\s*extern\s+/)
7145 WARN("AVOID_EXTERNS",
7146 "externs should be avoided in .c files\n" . $herecurr);
7149 # check for function declarations that have arguments without identifier names
7150 if (defined $stat &&
7151 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7153 my $args = trim($1);
7154 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7156 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7157 WARN("FUNCTION_ARGUMENTS",
7158 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7163 # check for function definitions
7164 if ($perl_version_ok &&
7166 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7167 $context_function = $1;
7169 # check for multiline function definition with misplaced open brace
7171 my $cnt = statement_rawlines($stat);
7172 my $herectx = $here . "\n";
7173 for (my $n = 0; $n < $cnt; $n++) {
7174 my $rl = raw_line($linenr, $n);
7175 $herectx .= $rl . "\n";
7176 $ok = 1 if ($rl =~ /^[ \+]\{/);
7177 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7178 last if $rl =~ /^[ \+].*\{/;
7182 "open brace '{' following function definitions go on the next line\n" . $herectx);
7186 # checks for new __setup's
7187 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7190 if (!grep(/$name/, @setup_docs)) {
7191 CHK("UNDOCUMENTED_SETUP",
7192 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7196 # check for pointless casting of alloc functions
7197 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7198 WARN("UNNECESSARY_CASTS",
7199 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7203 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7204 if ($perl_version_ok &&
7205 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7206 CHK("ALLOC_SIZEOF_STRUCT",
7207 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7210 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7211 if ($perl_version_ok &&
7213 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7217 my $newfunc = "kmalloc_array";
7218 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7219 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7220 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7223 if ($a1 =~ /^sizeof\s*\S/) {
7227 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7228 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7229 my $cnt = statement_rawlines($stat);
7230 my $herectx = get_stat_here($linenr, $cnt, $here);
7232 if (WARN("ALLOC_WITH_MULTIPLY",
7233 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7236 $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;
7241 # check for krealloc arg reuse
7242 if ($perl_version_ok &&
7243 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7245 WARN("KREALLOC_ARG_REUSE",
7246 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7249 # check for alloc argument mismatch
7250 if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
7251 WARN("ALLOC_ARRAY_ARGS",
7252 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7255 # check for multiple semicolons
7256 if ($line =~ /;\s*;\s*$/) {
7257 if (WARN("ONE_SEMICOLON",
7258 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7260 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7264 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7265 if ($realfile !~ m@^include/uapi/@ &&
7266 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7268 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7269 if (CHK("BIT_MACRO",
7270 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7272 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7276 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7277 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7278 WARN("IS_ENABLED_CONFIG",
7279 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7282 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7283 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7285 if (WARN("PREFER_IS_ENABLED",
7286 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7288 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7292 # check for /* fallthrough */ like comment, prefer fallthrough;
7293 my @fallthroughs = (
7296 'lint -fallthrough[ \t]*',
7297 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7298 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7299 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7300 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7302 if ($raw_comment ne '') {
7303 foreach my $ft (@fallthroughs) {
7304 if ($raw_comment =~ /$ft/) {
7305 my $msg_level = \&WARN;
7306 $msg_level = \&CHK if ($file);
7307 &{$msg_level}("PREFER_FALLTHROUGH",
7308 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7314 # check for switch/default statements without a break;
7315 if ($perl_version_ok &&
7317 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7318 my $cnt = statement_rawlines($stat);
7319 my $herectx = get_stat_here($linenr, $cnt, $here);
7321 WARN("DEFAULT_NO_BREAK",
7322 "switch default: should use break\n" . $herectx);
7325 # check for gcc specific __FUNCTION__
7326 if ($line =~ /\b__FUNCTION__\b/) {
7327 if (WARN("USE_FUNC",
7328 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7330 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7334 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7335 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7337 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7340 # check for use of yield()
7341 if ($line =~ /\byield\s*\(\s*\)/) {
7343 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7346 # check for comparisons against true and false
7347 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7355 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7357 my $type = lc($otype);
7358 if ($type =~ /^(?:true|false)$/) {
7359 if (("$test" eq "==" && "$type" eq "true") ||
7360 ("$test" eq "!=" && "$type" eq "false")) {
7364 CHK("BOOL_COMPARISON",
7365 "Using comparison to $otype is error prone\n" . $herecurr);
7367 ## maybe suggesting a correct construct would better
7368 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7373 # check for semaphores initialized locked
7374 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7375 WARN("CONSIDER_COMPLETION",
7376 "consider using a completion\n" . $herecurr);
7379 # recommend kstrto* over simple_strto* and strict_strto*
7380 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7381 WARN("CONSIDER_KSTRTO",
7382 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7385 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7386 if ($line =~ /^.\s*__initcall\s*\(/) {
7387 WARN("USE_DEVICE_INITCALL",
7388 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7391 # check for spin_is_locked(), suggest lockdep instead
7392 if ($line =~ /\bspin_is_locked\(/) {
7394 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7397 # check for deprecated apis
7398 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7399 my $deprecated_api = $1;
7400 my $new_api = $deprecated_apis{$deprecated_api};
7401 WARN("DEPRECATED_API",
7402 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7405 # check for various structs that are normally const (ops, kgdb, device_tree)
7406 # and avoid what seem like struct definitions 'struct foo {'
7407 if (defined($const_structs) &&
7408 $line !~ /\bconst\b/ &&
7409 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7410 WARN("CONST_STRUCT",
7411 "struct $1 should normally be const\n" . $herecurr);
7414 # use of NR_CPUS is usually wrong
7415 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7416 # ignore designated initializers using NR_CPUS
7417 if ($line =~ /\bNR_CPUS\b/ &&
7418 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7419 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7420 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7421 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7422 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7423 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7426 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7429 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7430 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7431 ERROR("DEFINE_ARCH_HAS",
7432 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7435 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7436 if ($perl_version_ok &&
7437 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7438 WARN("LIKELY_MISUSE",
7439 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7442 # return sysfs_emit(foo, fmt, ...) fmt without newline
7443 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7444 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7445 my $offset = $+[6] - 1;
7446 if (WARN("SYSFS_EMIT",
7447 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7449 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7453 # check for array definition/declarations that should use flexible arrays instead
7454 if ($sline =~ /^[\+ ]\s*\}(?:\s*__packed)?\s*;\s*$/ &&
7455 $prevline =~ /^\+\s*(?:\}(?:\s*__packed\s*)?|$Type)\s*$Ident\s*\[\s*(0|1)\s*\]\s*;\s*$/) {
7456 if (ERROR("FLEXIBLE_ARRAY",
7457 "Use C99 flexible arrays - see https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays\n" . $hereprev) &&
7458 $1 == '0' && $fix) {
7459 $fixed[$fixlinenr - 1] =~ s/\[\s*0\s*\]/[]/;
7463 # nested likely/unlikely calls
7464 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7465 WARN("LIKELY_MISUSE",
7466 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7469 # whine mightly about in_atomic
7470 if ($line =~ /\bin_atomic\s*\(/) {
7471 if ($realfile =~ m@^drivers/@) {
7473 "do not use in_atomic in drivers\n" . $herecurr);
7474 } elsif ($realfile !~ m@^kernel/@) {
7476 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7480 # Complain about RCU Tasks Trace used outside of BPF (and of course, RCU).
7481 our $rcu_trace_funcs = qr{(?x:
7482 rcu_read_lock_trace |
7483 rcu_read_lock_trace_held |
7484 rcu_read_unlock_trace |
7485 call_rcu_tasks_trace |
7486 synchronize_rcu_tasks_trace |
7487 rcu_barrier_tasks_trace |
7488 rcu_request_urgent_qs_task
7490 our $rcu_trace_paths = qr{(?x:
7497 if ($line =~ /\b($rcu_trace_funcs)\s*\(/) {
7498 if ($realfile !~ m{^$rcu_trace_paths}) {
7499 WARN("RCU_TASKS_TRACE",
7500 "use of RCU tasks trace is incorrect outside BPF or core RCU code\n" . $herecurr);
7504 # check for lockdep_set_novalidate_class
7505 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7506 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7507 if ($realfile !~ m@^kernel/lockdep@ &&
7508 $realfile !~ m@^include/linux/lockdep@ &&
7509 $realfile !~ m@^drivers/base/core@) {
7511 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7515 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7516 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7517 WARN("EXPORTED_WORLD_WRITABLE",
7518 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7521 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7522 # and whether or not function naming is typical and if
7523 # DEVICE_ATTR permissions uses are unusual too
7524 if ($perl_version_ok &&
7526 $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*\)/) {
7531 my $octal_perms = perms_to_octal($perms);
7532 if ($show =~ /^${var}_show$/ &&
7533 $store =~ /^${var}_store$/ &&
7534 $octal_perms eq "0644") {
7535 if (WARN("DEVICE_ATTR_RW",
7536 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7538 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7540 } elsif ($show =~ /^${var}_show$/ &&
7541 $store =~ /^NULL$/ &&
7542 $octal_perms eq "0444") {
7543 if (WARN("DEVICE_ATTR_RO",
7544 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7546 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7548 } elsif ($show =~ /^NULL$/ &&
7549 $store =~ /^${var}_store$/ &&
7550 $octal_perms eq "0200") {
7551 if (WARN("DEVICE_ATTR_WO",
7552 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7554 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7556 } elsif ($octal_perms eq "0644" ||
7557 $octal_perms eq "0444" ||
7558 $octal_perms eq "0200") {
7559 my $newshow = "$show";
7560 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7561 my $newstore = $store;
7562 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7564 if ($show ne $newshow) {
7565 $rename .= " '$show' to '$newshow'";
7567 if ($store ne $newstore) {
7568 $rename .= " '$store' to '$newstore'";
7570 WARN("DEVICE_ATTR_FUNCTIONS",
7571 "Consider renaming function(s)$rename\n" . $herecurr);
7573 WARN("DEVICE_ATTR_PERMS",
7574 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7578 # Mode permission misuses where it seems decimal should be octal
7579 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7580 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7581 # specific definition of not visible in sysfs.
7582 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7583 # use the default permissions
7584 if ($perl_version_ok &&
7586 $line =~ /$mode_perms_search/) {
7587 foreach my $entry (@mode_permission_funcs) {
7588 my $func = $entry->[0];
7589 my $arg_pos = $entry->[1];
7591 my $lc = $stat =~ tr@\n@@;
7592 $lc = $lc + $linenr;
7593 my $stat_real = get_stat_real($linenr, $lc);
7598 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7600 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7601 if ($stat =~ /$test/) {
7603 $val = $6 if ($skip_args ne "");
7604 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7605 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7606 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7607 ERROR("NON_OCTAL_PERMISSIONS",
7608 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7610 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7611 ERROR("EXPORTED_WORLD_WRITABLE",
7612 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7618 # check for uses of S_<PERMS> that could be octal for readability
7619 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7621 my $octal = perms_to_octal($oval);
7622 if (WARN("SYMBOLIC_PERMS",
7623 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7625 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7629 # validate content of MODULE_LICENSE against list from include/linux/module.h
7630 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7631 my $extracted_string = get_quoted_string($line, $rawline);
7632 my $valid_licenses = qr{
7635 GPL\ and\ additional\ rights|
7641 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7642 WARN("MODULE_LICENSE",
7643 "unknown module license " . $extracted_string . "\n" . $herecurr);
7645 if (!$file && $extracted_string eq '"GPL v2"') {
7646 if (WARN("MODULE_LICENSE",
7647 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7649 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7654 # check for sysctl duplicate constants
7655 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7656 WARN("DUPLICATED_SYSCTL_CONST",
7657 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7661 # If we have no input at all, then there is nothing to report on
7662 # so just keep quiet.
7663 if ($#rawlines == -1) {
7667 # In mailback mode only produce a report in the negative, for
7668 # things that appear to be patches.
7669 if ($mailback && ($clean == 1 || !$is_patch)) {
7673 # This is not a patch, and we are in 'no-patch' mode so
7675 if (!$chk_patch && !$is_patch) {
7679 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7680 ERROR("NOT_UNIFIED_DIFF",
7681 "Does not appear to be a unified-diff format patch\n");
7683 if ($is_patch && $has_commit_log && $chk_signoff) {
7684 if ($signoff == 0) {
7685 ERROR("MISSING_SIGN_OFF",
7686 "Missing Signed-off-by: line(s)\n");
7687 } elsif ($authorsignoff != 1) {
7688 # authorsignoff values:
7689 # 0 -> missing sign off
7690 # 1 -> sign off identical
7691 # 2 -> names and addresses match, comments mismatch
7692 # 3 -> addresses match, names different
7693 # 4 -> names match, addresses different
7694 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7696 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7698 if ($authorsignoff == 0) {
7699 ERROR("NO_AUTHOR_SIGN_OFF",
7700 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7701 } elsif ($authorsignoff == 2) {
7702 CHK("FROM_SIGN_OFF_MISMATCH",
7703 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7704 } elsif ($authorsignoff == 3) {
7705 WARN("FROM_SIGN_OFF_MISMATCH",
7706 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7707 } elsif ($authorsignoff == 4) {
7708 WARN("FROM_SIGN_OFF_MISMATCH",
7709 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7710 } elsif ($authorsignoff == 5) {
7711 WARN("FROM_SIGN_OFF_MISMATCH",
7712 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7717 print report_dump();
7718 if ($summary && !($clean == 1 && $quiet == 1)) {
7719 print "$filename " if ($summary_file);
7720 print "total: $cnt_error errors, $cnt_warn warnings, " .
7721 (($check)? "$cnt_chk checks, " : "") .
7722 "$cnt_lines lines checked\n";
7726 # If there were any defects found and not already fixing them
7727 if (!$clean and !$fix) {
7730 NOTE: For some of the reported defects, checkpatch may be able to
7731 mechanically convert to the typical style using --fix or --fix-inplace.
7734 # If there were whitespace errors which cleanpatch can fix
7735 # then suggest that.
7736 if ($rpt_cleaners) {
7740 NOTE: Whitespace errors detected.
7741 You may wish to use scripts/cleanpatch or scripts/cleanfile
7746 if ($clean == 0 && $fix &&
7747 ("@rawlines" ne "@fixed" ||
7748 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7749 my $newfile = $filename;
7750 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7754 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7756 open($f, '>', $newfile)
7757 or die "$P: Can't open $newfile for write\n";
7758 foreach my $fixed_line (@fixed) {
7761 if ($linecount > 3) {
7762 $fixed_line =~ s/^\+//;
7763 print $f $fixed_line . "\n";
7766 print $f $fixed_line . "\n";
7774 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7776 Do _NOT_ trust the results written to this file.
7777 Do _NOT_ submit these changes without inspecting them for correctness.
7779 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7780 No warranties, expressed or implied...
7788 print "$vname has no obvious style problems and is ready for submission.\n";
7790 print "$vname has style problems, please review.\n";