2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
25 # ATTENTION: easily track modification to this script for OpenOCD.
26 # When possible, don't modify the existing code, don't change its indentation,
27 # but remove it enclosing it within:
33 # Mark every addition within comments
34 # # OpenOCD specific: Begin[: additional comment]
35 # # OpenOCD specific: End
40 my %verbose_messages = ();
41 my %verbose_emitted = ();
62 my $gitroot = $ENV{'GIT_DIR'};
63 $gitroot = ".git" if !defined($gitroot);
71 my $configuration_file = ".checkpatch.conf";
72 my $max_line_length = 100;
73 my $ignore_perl_version = 0;
74 my $minimum_perl_version = 5.10.0;
75 my $min_conf_desc_length = 4;
76 my $spelling_file = "$D/spelling.txt";
78 my $codespellfile = "/usr/share/codespell/dictionary.txt";
79 my $user_codespellfile = "";
80 my $conststructsfile = "$D/const_structs.checkpatch";
82 my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
84 # OpenOCD Specific: Begin
85 my $docsfile = "$D/../../doc/checkpatch.rst";
86 # OpenOCD Specific: End
89 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
90 # git output parsing needs US English output, so first set backtick child process LANGUAGE
91 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
93 my ${CONFIG_} = "CONFIG_";
99 Usage: $P [OPTION]... [FILE]...
104 -v, --verbose verbose mode
105 --no-tree run without an OpenOCD tree
106 --no-signoff do not check for 'Signed-off-by' line
107 --patch treat FILE as patchfile (default)
108 --emacs emacs compile window format
109 --terse one line per report
110 --showfile emit diffed file position, not input file position
111 -g, --git treat FILE as a single commit or git revision range
112 single git commit with:
116 multiple git commits with:
120 git merges are ignored
121 -f, --file treat FILE as regular source file
122 --subjective, --strict enable more subjective tests
123 --list-types list the possible message types
124 --types TYPE(,TYPE2...) show only these comma separated message types
125 --ignore TYPE(,TYPE2...) ignore various comma separated message types
126 --show-types show the specific message type in the output
127 --max-line-length=n set the maximum line length, (default $max_line_length)
128 if exceeded, warn on patches
129 requires --strict for use with --file
130 --min-conf-desc-length=n set the min description length, if shorter, warn
131 --tab-size=n set the number of spaces for tab (default $tabsize)
132 --root=PATH PATH to the OpenOCD tree root
133 --no-summary suppress the per-file summary
134 --mailback only produce a report in case of warnings/errors
135 --summary-file include the filename in summary
136 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
137 'values', 'possible', 'type', and 'attr' (default
139 --test-only=WORD report only warnings/errors containing WORD
141 --fix EXPERIMENTAL - may create horrible results
142 If correctable single-line errors exist, create
143 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
144 with potential errors corrected to the preferred
146 --fix-inplace EXPERIMENTAL - may create horrible results
147 Is the same as --fix, but overwrites the input
148 file. It's your fault if there's no backup or git
149 --ignore-perl-version override checking of perl version. expect
151 --codespell Use the codespell dictionary for spelling/typos
152 (default:$codespellfile)
153 --codespellfile Use this codespell dictionary
154 --typedefsfile Read additional types from this file
155 --color[=WHEN] Use colors 'always', 'never', or only when output
156 is a terminal ('auto'). Default is 'auto'.
157 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
159 -h, --help, --version display this help and exit
161 When FILE is - read standard input.
169 return grep { !$seen{$_}++ } @_;
179 open(my $script, '<', abs_path($P)) or
180 die "$P: Can't read '$P' $!\n";
182 my $text = <$script>;
186 # Also catch when type or level is passed through a variable
187 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
189 if (exists($types{$2})) {
190 $types{$2} .= ",$1" if ($types{$2} ne $1);
195 $types{$2} = "UNDETERMINED";
199 print("#\tMessage type\n\n");
201 print(" ( Color coding: ");
202 print(RED . "ERROR" . RESET);
204 print(YELLOW . "WARNING" . RESET);
206 print(GREEN . "CHECK" . RESET);
208 print("Multiple levels / Undetermined");
212 foreach my $type (sort keys %types) {
213 my $orig_type = $type;
215 my $level = $types{$type};
216 if ($level eq "ERROR") {
217 $type = RED . $type . RESET;
218 } elsif ($level eq "WARN") {
219 $type = YELLOW . $type . RESET;
220 } elsif ($level eq "CHK") {
221 $type = GREEN . $type . RESET;
224 print(++$count . "\t" . $type . "\n");
225 if ($verbose && exists($verbose_messages{$orig_type})) {
226 my $message = $verbose_messages{$orig_type};
227 $message =~ s/\n/\n\t/g;
228 print("\t" . $message . "\n\n");
235 my $conf = which_conf($configuration_file);
238 open(my $conffile, '<', "$conf")
239 or warn "$P: Can't find a readable $configuration_file file $!\n";
241 while (<$conffile>) {
244 $line =~ s/\s*\n?$//g;
248 next if ($line =~ m/^\s*#/);
249 next if ($line =~ m/^\s*$/);
251 my @words = split(" ", $line);
252 foreach my $word (@words) {
253 last if ($word =~ m/^#/);
254 push (@conf_args, $word);
258 unshift(@ARGV, @conf_args) if @conf_args;
262 open(my $docs, '<', "$docsfile")
263 or warn "$P: Can't read the documentation file $docsfile $!\n";
274 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
276 $verbose_messages{$type} = trim($desc);
282 if ($line =~ /^(?:\s{4,}|$)/) {
287 $verbose_messages{$type} = trim($desc);
296 $verbose_messages{$type} = trim($desc);
301 # Perl's Getopt::Long allows options to take optional arguments after a space.
302 # Prevent --color by itself from consuming other arguments
304 if ($_ eq "--color" || $_ eq "-color") {
305 $_ = "--color=$color";
310 'q|quiet+' => \$quiet,
311 'v|verbose!' => \$verbose,
313 'signoff!' => \$chk_signoff,
314 'patch!' => \$chk_patch,
317 'showfile!' => \$showfile,
320 'subjective!' => \$check,
321 'strict!' => \$check,
322 'ignore=s' => \@ignore,
324 'show-types!' => \$show_types,
325 'list-types!' => \$list_types,
326 'max-line-length=i' => \$max_line_length,
327 'min-conf-desc-length=i' => \$min_conf_desc_length,
328 'tab-size=i' => \$tabsize,
330 'summary!' => \$summary,
331 'mailback!' => \$mailback,
332 'summary-file!' => \$summary_file,
334 'fix-inplace!' => \$fix_inplace,
335 'ignore-perl-version!' => \$ignore_perl_version,
336 'debug=s' => \%debug,
337 'test-only=s' => \$tst_only,
338 'codespell!' => \$codespell,
339 'codespellfile=s' => \$user_codespellfile,
340 'typedefsfile=s' => \$typedefsfile,
341 'color=s' => \$color,
342 'no-color' => \$color, #keep old behaviors of -nocolor
343 'nocolor' => \$color, #keep old behaviors of -nocolor
344 'kconfig-prefix=s' => \${CONFIG_},
349 if ($user_codespellfile) {
350 # Use the user provided codespell file unconditionally
351 $codespellfile = $user_codespellfile;
352 } elsif (!(-f $codespellfile)) {
353 # If /usr/share/codespell/dictionary.txt is not present, try to find it
354 # under codespell's install directory: <codespell_root>/data/dictionary.txt
355 if (($codespell || $help) && which("python3") ne "") {
356 my $python_codespell_dict = << "EOF";
360 codespell_dir = op.dirname(codespell_lib.__file__)
361 codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
362 print(codespell_file, end='')
365 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
366 $codespellfile = $codespell_dict if (-f $codespell_dict);
370 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
371 # $help is 2 if invalid option is passed - exitcode: 1
372 help($help - 1) if ($help);
374 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
375 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
377 if ($color =~ /^[01]$/) {
379 } elsif ($color =~ /^always$/i) {
381 } elsif ($color =~ /^never$/i) {
383 } elsif ($color =~ /^auto$/i) {
384 $color = (-t STDOUT);
386 die "$P: Invalid color mode: $color\n";
389 load_docs() if ($verbose);
390 list_types(0) if ($list_types);
392 $fix = 1 if ($fix_inplace);
393 $check_orig = $check;
397 my $perl_version_ok = 1;
398 if ($^V && $^V lt $minimum_perl_version) {
399 $perl_version_ok = 0;
400 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
401 exit(1) if (!$ignore_perl_version);
404 #if no filenames are given, push '-' to read patch from stdin
409 # skip TAB size 1 to avoid additional checks on $tabsize - 1
410 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
412 sub hash_save_array_words {
413 my ($hashRef, $arrayRef) = @_;
415 my @array = split(/,/, join(',', @$arrayRef));
416 foreach my $word (@array) {
417 $word =~ s/\s*\n?$//g;
420 $word =~ tr/[a-z]/[A-Z]/;
422 next if ($word =~ m/^\s*#/);
423 next if ($word =~ m/^\s*$/);
429 sub hash_show_words {
430 my ($hashRef, $prefix) = @_;
432 if (keys %$hashRef) {
433 print "\nNOTE: $prefix message types:";
434 foreach my $word (sort keys %$hashRef) {
441 hash_save_array_words(\%ignore_type, \@ignore);
442 hash_save_array_words(\%use_type, \@use);
445 my $dbg_possible = 0;
448 for my $key (keys %debug) {
450 eval "\${dbg_$key} = '$debug{$key}';";
454 my $rpt_cleaners = 0;
463 if (!top_of_kernel_tree($root)) {
464 die "$P: $root: --root does not point at a valid tree\n";
467 if (top_of_kernel_tree('.')) {
469 # OpenOCD specific: Begin: replace s"/scripts/"/tools/scripts/"
470 } elsif ($0 =~ m@(.*)/tools/scripts/[^/]*$@ &&
471 top_of_kernel_tree($1)) {
474 # OpenOCD specific: End
477 if (!defined $root) {
478 print "Must be run from the top-level dir. of an OpenOCD tree\n";
483 my $emitted_corrupt = 0;
486 [A-Za-z_][A-Za-z\d_]*
487 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
489 our $Storage = qr{extern|static|asmlinkage};
503 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
504 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
505 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
506 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
507 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
509 # Notes to $Attribute:
510 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
533 ____cacheline_aligned|
534 ____cacheline_aligned_in_smp|
535 ____cacheline_internodealigned_in_smp|
537 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
540 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
541 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
542 our $Lval = qr{$Ident(?:$Member)*};
544 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
545 our $Binary = qr{(?i)0b[01]+$Int_type?};
546 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
547 our $Int = qr{[0-9]+$Int_type?};
548 our $Octal = qr{0[0-7]+$Int_type?};
549 our $String = qr{(?:\b[Lu])?"[X\t]*"};
550 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
551 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
552 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
553 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
554 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
555 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
556 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
557 our $Arithmetic = qr{\+|-|\*|\/|%};
561 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
564 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
568 our $NonptrTypeMisordered;
569 our $NonptrTypeWithAttr;
573 our $DeclareMisordered;
575 our $NON_ASCII_UTF8 = qr{
576 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
577 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
578 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
579 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
580 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
581 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
582 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
586 [\x09\x0A\x0D\x20-\x7E] # ASCII
590 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
591 our $typeOtherOSTypedefs = qr{(?x:
592 u_(?:char|short|int|long) | # bsd
593 u(?:nchar|short|int|long) # sysv
595 our $typeKernelTypedefs = qr{(?x:
596 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
599 our $typeTypedefs = qr{(?x:
601 $typeOtherOSTypedefs\b|
602 $typeKernelTypedefs\b
605 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
608 our $logFunctions = qr{(?x:
609 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
610 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
612 WARN(?:_RATELIMIT|_ONCE|)|
615 seq_vprintf|seq_printf|seq_puts
618 # OpenOCD specific: Begin: list log functions
619 our $logFunctions = qr{(?x:
620 LOG_(?:TARGET_|)(?:DEBUG_IO|DEBUG|INFO|WARNING|ERROR|USER|USER_N|OUTPUT)
622 # OpenOCD specific: End
624 our $allocFunctions = qr{(?x:
626 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
629 (?:\w+)?alloc_skb(?:_ip_align)? |
630 # dev_alloc_skb/netdev_alloc_skb, et al
634 our $signature_tags = qr{(?xi:
646 our $tracing_logging_tags = qr{(?xi:
670 sub edit_distance_min {
672 my $len = scalar @arr;
673 if ((scalar @arr) < 1) {
674 # if underflow, return
678 for my $i (0 .. ($len-1)) {
679 if ($arr[$i] < $min) {
686 sub get_edit_distance {
687 my ($str1, $str2) = @_;
692 my $len1 = length($str1);
693 my $len2 = length($str2);
694 # two dimensional array storing minimum edit distance
696 for my $i (0 .. $len1) {
697 for my $j (0 .. $len2) {
699 $distance[$i][$j] = $j;
701 $distance[$i][$j] = $i;
702 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
703 $distance[$i][$j] = $distance[$i - 1][$j - 1];
705 my $dist1 = $distance[$i][$j - 1]; #insert distance
706 my $dist2 = $distance[$i - 1][$j]; # remove
707 my $dist3 = $distance[$i - 1][$j - 1]; #replace
708 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
712 return $distance[$len1][$len2];
715 sub find_standard_signature {
717 my @standard_signature_tags = (
718 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
719 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
721 foreach my $signature (@standard_signature_tags) {
722 return $signature if (get_edit_distance($sign_off, $signature) <= 2);
728 our @typeListMisordered = (
729 qr{char\s+(?:un)?signed},
730 qr{int\s+(?:(?:un)?signed\s+)?short\s},
731 qr{int\s+short(?:\s+(?:un)?signed)},
732 qr{short\s+int(?:\s+(?:un)?signed)},
733 qr{(?:un)?signed\s+int\s+short},
734 qr{short\s+(?:un)?signed},
735 qr{long\s+int\s+(?:un)?signed},
736 qr{int\s+long\s+(?:un)?signed},
737 qr{long\s+(?:un)?signed\s+int},
738 qr{int\s+(?:un)?signed\s+long},
739 qr{int\s+(?:un)?signed},
740 qr{int\s+long\s+long\s+(?:un)?signed},
741 qr{long\s+long\s+int\s+(?:un)?signed},
742 qr{long\s+long\s+(?:un)?signed\s+int},
743 qr{long\s+long\s+(?:un)?signed},
744 qr{long\s+(?:un)?signed},
749 qr{(?:(?:un)?signed\s+)?char},
750 qr{(?:(?:un)?signed\s+)?short\s+int},
751 qr{(?:(?:un)?signed\s+)?short},
752 qr{(?:(?:un)?signed\s+)?int},
753 qr{(?:(?:un)?signed\s+)?long\s+int},
754 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
755 qr{(?:(?:un)?signed\s+)?long\s+long},
756 qr{(?:(?:un)?signed\s+)?long},
765 qr{${Ident}_handler},
766 qr{${Ident}_handler_fn},
770 our $C90_int_types = qr{(?x:
771 long\s+long\s+int\s+(?:un)?signed|
772 long\s+long\s+(?:un)?signed\s+int|
773 long\s+long\s+(?:un)?signed|
774 (?:(?:un)?signed\s+)?long\s+long\s+int|
775 (?:(?:un)?signed\s+)?long\s+long|
776 int\s+long\s+long\s+(?:un)?signed|
777 int\s+(?:(?:un)?signed\s+)?long\s+long|
779 long\s+int\s+(?:un)?signed|
780 long\s+(?:un)?signed\s+int|
781 long\s+(?:un)?signed|
782 (?:(?:un)?signed\s+)?long\s+int|
783 (?:(?:un)?signed\s+)?long|
784 int\s+long\s+(?:un)?signed|
785 int\s+(?:(?:un)?signed\s+)?long|
788 (?:(?:un)?signed\s+)?int
791 our @typeListFile = ();
792 our @typeListWithAttr = (
794 qr{struct\s+$InitAttribute\s+$Ident},
795 qr{union\s+$InitAttribute\s+$Ident},
798 our @modifierList = (
801 our @modifierListFile = ();
803 our @mode_permission_funcs = (
805 ["module_param_(?:array|named|string)", 4],
806 ["module_param_array_named", 5],
807 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
808 ["proc_create(?:_data|)", 2],
809 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
810 ["IIO_DEV_ATTR_[A-Z_]+", 1],
811 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
812 ["SENSOR_TEMPLATE(?:_2|)", 3],
816 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
818 #Create a search pattern for all these functions to speed up a loop below
819 our $mode_perms_search = "";
820 foreach my $entry (@mode_permission_funcs) {
821 $mode_perms_search .= '|' if ($mode_perms_search ne "");
822 $mode_perms_search .= $entry->[0];
824 $mode_perms_search = "(?:${mode_perms_search})";
826 our %deprecated_apis = (
827 "synchronize_rcu_bh" => "synchronize_rcu",
828 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
829 "call_rcu_bh" => "call_rcu",
830 "rcu_barrier_bh" => "rcu_barrier",
831 "synchronize_sched" => "synchronize_rcu",
832 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
833 "call_rcu_sched" => "call_rcu",
834 "rcu_barrier_sched" => "rcu_barrier",
835 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
836 "cond_synchronize_sched" => "cond_synchronize_rcu",
839 #Create a search pattern for all these strings to speed up a loop below
840 our $deprecated_apis_search = "";
841 foreach my $entry (keys %deprecated_apis) {
842 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
843 $deprecated_apis_search .= $entry;
845 $deprecated_apis_search = "(?:${deprecated_apis_search})";
847 our $mode_perms_world_writable = qr{
855 our %mode_permission_string_types = (
874 #Create a search pattern for all these strings to speed up a loop below
875 our $mode_perms_string_search = "";
876 foreach my $entry (keys %mode_permission_string_types) {
877 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
878 $mode_perms_string_search .= $entry;
880 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
881 our $multi_mode_perms_string_search = qr{
882 ${single_mode_perms_string_search}
883 (?:\s*\|\s*${single_mode_perms_string_search})*
889 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
896 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
897 $curpos = pos($string);
900 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
902 $to |= $mode_permission_string_types{$match};
903 $val .= '\s*\|\s*' if ($val ne "");
907 $oval =~ s/^\s*\|\s*//;
908 $oval =~ s/\s*\|\s*$//;
909 return sprintf("%04o", $to);
912 our $allowed_asm_includes = qr{(?x:
918 # memory.h: ARM has a custom one
920 # Load common spelling mistakes and build regular expression list.
924 if (open(my $spelling, '<', $spelling_file)) {
925 while (<$spelling>) {
928 $line =~ s/\s*\n?$//g;
931 next if ($line =~ m/^\s*#/);
932 next if ($line =~ m/^\s*$/);
934 my ($suspect, $fix) = split(/\|\|/, $line);
936 $spelling_fix{$suspect} = $fix;
940 warn "No typos will be found - file '$spelling_file': $!\n";
944 if (open(my $spelling, '<', $codespellfile)) {
945 while (<$spelling>) {
948 $line =~ s/\s*\n?$//g;
951 next if ($line =~ m/^\s*#/);
952 next if ($line =~ m/^\s*$/);
953 next if ($line =~ m/, disabled/i);
957 my ($suspect, $fix) = split(/->/, $line);
959 $spelling_fix{$suspect} = $fix;
963 warn "No codespell typos will be found - file '$codespellfile': $!\n";
967 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
970 my ($wordsRef, $file) = @_;
972 if (open(my $words, '<', $file)) {
976 $line =~ s/\s*\n?$//g;
979 next if ($line =~ m/^\s*#/);
980 next if ($line =~ m/^\s*$/);
982 print("$file: '$line' invalid - ignored\n");
986 $$wordsRef .= '|' if (defined $$wordsRef);
996 # OpenOCD specific: Begin: Load list of allowed CamelCase symbols
997 if (show_type("CAMELCASE")) {
998 my $allowed_camelcase_file = "$root/tools/scripts/camelcase.txt";
999 if (open(my $words, '<', $allowed_camelcase_file)) {
1003 $line =~ s/\s*\n?$//g;
1006 next if ($line =~ m/^\s*#/);
1007 next if ($line =~ m/^\s*$/);
1008 if ($line =~ /\s/) {
1009 print("$allowed_camelcase_file: '$line' invalid - ignored\n");
1013 $camelcase{$line} = 1;
1015 close($allowed_camelcase_file);
1017 warn "No camelcase symbols to ignore - file '$allowed_camelcase_file': $!\n";
1020 # OpenOCD specific: End
1023 if (show_type("CONST_STRUCT")) {
1024 read_words(\$const_structs, $conststructsfile)
1025 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1028 if (defined($typedefsfile)) {
1029 my $typeOtherTypedefs;
1030 read_words(\$typeOtherTypedefs, $typedefsfile)
1031 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
1032 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1036 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1037 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1038 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
1039 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1040 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1042 (?:$typeTypedefs\b)|
1046 (?:$Modifier\s+|const\s+)*
1048 (?:typeof|__typeof__)\s*\([^\)]*\)|
1049 (?:$typeTypedefs\b)|
1052 (?:\s+$Modifier|\s+const)*
1054 $NonptrTypeMisordered = qr{
1055 (?:$Modifier\s+|const\s+)*
1059 (?:\s+$Modifier|\s+const)*
1061 $NonptrTypeWithAttr = qr{
1062 (?:$Modifier\s+|const\s+)*
1064 (?:typeof|__typeof__)\s*\([^\)]*\)|
1065 (?:$typeTypedefs\b)|
1066 (?:${allWithAttr}\b)
1068 (?:\s+$Modifier|\s+const)*
1072 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1073 (?:\s+$Inline|\s+$Modifier)*
1075 $TypeMisordered = qr{
1076 $NonptrTypeMisordered
1077 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1078 (?:\s+$Inline|\s+$Modifier)*
1080 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1081 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1085 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1087 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1088 # requires at least perl version v5.10.0
1089 # Any use must be runtime checked with $^V
1091 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1092 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1093 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1095 our $declaration_macros = qr{(?x:
1096 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1097 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1098 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1099 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1102 our %allow_repeated_words = (
1109 sub deparenthesize {
1111 return "" if (!defined($string));
1113 while ($string =~ /^\s*\(.*\)\s*$/) {
1114 $string =~ s@^\s*\(\s*@@;
1115 $string =~ s@\s*\)\s*$@@;
1118 $string =~ s@\s+@ @g;
1123 sub seed_camelcase_file {
1126 return if (!(-f $file));
1130 open(my $include_file, '<', "$file")
1131 or warn "$P: Can't read '$file' $!\n";
1132 my $text = <$include_file>;
1133 close($include_file);
1135 my @lines = split('\n', $text);
1137 foreach my $line (@lines) {
1139 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1140 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1142 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1144 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1148 # OpenOCD Specific: Begin: extend to camel[0-9_]*CASE
1149 next if ($line !~ /(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])/);
1150 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)/) {
1152 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)\s*[\(\[,;]/) {
1154 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)\s*[;\{]/) {
1157 # OpenOCD Specific: End
1161 our %maintained_status = ();
1163 sub is_maintained_obsolete {
1164 my ($filename) = @_;
1166 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1168 if (!exists($maintained_status{$filename})) {
1169 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1172 return $maintained_status{$filename} =~ /obsolete/i;
1175 sub is_SPDX_License_valid {
1178 # OpenOCD specific: Begin: replace s"scripts"tools/scripts"
1179 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/tools/scripts/spdxcheck.py") || !(-e "$gitroot"));
1181 my $root_path = abs_path($root);
1182 my $status = `cd "$root_path"; echo "$license" | tools/scripts/spdxcheck.py -`;
1183 # OpenOCD specific: End
1184 return 0 if ($status ne "");
1188 my $camelcase_seeded = 0;
1189 sub seed_camelcase_includes {
1190 return if ($camelcase_seeded);
1193 my $camelcase_cache = "";
1194 my @include_files = ();
1196 $camelcase_seeded = 1;
1198 if (-e "$gitroot") {
1199 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1200 chomp $git_last_include_commit;
1201 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1203 my $last_mod_date = 0;
1204 $files = `find $root/include -name "*.h"`;
1205 @include_files = split('\n', $files);
1206 foreach my $file (@include_files) {
1207 my $date = POSIX::strftime("%Y%m%d%H%M",
1208 localtime((stat $file)[9]));
1209 $last_mod_date = $date if ($last_mod_date < $date);
1211 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1214 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1215 open(my $camelcase_file, '<', "$camelcase_cache")
1216 or warn "$P: Can't read '$camelcase_cache' $!\n";
1217 while (<$camelcase_file>) {
1221 close($camelcase_file);
1226 if (-e "$gitroot") {
1227 $files = `${git_command} ls-files "include/*.h"`;
1228 @include_files = split('\n', $files);
1231 foreach my $file (@include_files) {
1232 seed_camelcase_file($file);
1235 if ($camelcase_cache ne "") {
1236 unlink glob ".checkpatch-camelcase.*";
1237 open(my $camelcase_file, '>', "$camelcase_cache")
1238 or warn "$P: Can't write '$camelcase_cache' $!\n";
1239 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1240 print $camelcase_file ("$_\n");
1242 close($camelcase_file);
1246 sub git_is_single_file {
1247 my ($filename) = @_;
1249 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1251 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1252 my $count = $output =~ tr/\n//;
1253 return $count eq 1 && $output =~ m{^${filename}$};
1256 sub git_commit_info {
1257 my ($commit, $id, $desc) = @_;
1259 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1261 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1262 $output =~ s/^\s*//gm;
1263 my @lines = split("\n", $output);
1265 return ($id, $desc) if ($#lines < 0);
1267 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1268 # Maybe one day convert this block of bash into something that returns
1269 # all matching commit ids, but it's very slow...
1271 # echo "checking commits $1..."
1272 # git rev-list --remotes | grep -i "^$1" |
1273 # while read line ; do
1274 # git log --format='%H %s' -1 $line |
1275 # echo "commit $(cut -c 1-12,41-)"
1277 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1278 $lines[0] =~ /^fatal: bad object $commit/) {
1281 $id = substr($lines[0], 0, 12);
1282 $desc = substr($lines[0], 41);
1285 return ($id, $desc);
1288 $chk_signoff = 0 if ($file);
1293 my @fixed_inserted = ();
1294 my @fixed_deleted = ();
1297 # If input is git commits, extract all commits from the commit expressions.
1298 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1299 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1303 foreach my $commit_expr (@ARGV) {
1305 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1306 $git_range = "-$2 $1";
1307 } elsif ($commit_expr =~ m/\.\./) {
1308 $git_range = "$commit_expr";
1310 $git_range = "-1 $commit_expr";
1312 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1313 foreach my $line (split(/\n/, $lines)) {
1314 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1315 next if (!defined($1) || !defined($2));
1318 unshift(@commits, $sha1);
1319 $git_commits{$sha1} = $subject;
1322 die "$P: no git commits after extraction!\n" if (@commits == 0);
1327 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1328 for my $filename (@ARGV) {
1330 my $is_git_file = git_is_single_file($filename);
1331 my $oldfile = $file;
1332 $file = 1 if ($is_git_file);
1334 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1335 die "$P: $filename: git format-patch failed - $!\n";
1337 open($FILE, '-|', "diff -u /dev/null $filename") ||
1338 die "$P: $filename: diff failed - $!\n";
1339 } elsif ($filename eq '-') {
1340 open($FILE, '<&STDIN');
1342 open($FILE, '<', "$filename") ||
1343 die "$P: $filename: open failed - $!\n";
1345 if ($filename eq '-') {
1346 $vname = 'Your patch';
1348 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1354 push(@rawlines, $_);
1355 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1359 if ($#ARGV > 0 && $quiet == 0) {
1360 print '-' x length($vname) . "\n";
1362 print '-' x length($vname) . "\n";
1365 if (!process($filename)) {
1371 @fixed_inserted = ();
1372 @fixed_deleted = ();
1374 @modifierListFile = ();
1377 $file = $oldfile if ($is_git_file);
1381 hash_show_words(\%use_type, "Used");
1382 hash_show_words(\%ignore_type, "Ignored");
1384 if (!$perl_version_ok) {
1387 NOTE: perl $^V is not modern enough to detect all possible issues.
1388 An upgrade to at least perl $minimum_perl_version is suggested.
1395 NOTE: If any of the errors are false positives, please report
1396 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1399 # OpenOCD specific: Begin
1402 NOTE: If any of the errors are false positives, please report
1403 them to the openocd-devel mailing list or prepare a patch
1404 and send it to Gerrit for review.
1406 # OpenOCD specific: End
1412 sub top_of_kernel_tree {
1417 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1418 "README", "Documentation", "arch", "include", "drivers",
1419 "fs", "init", "ipc", "kernel", "lib", "scripts",
1422 # OpenOCD specific: Begin
1424 "AUTHORS", "BUGS", "COPYING", "HACKING", "Makefile.am",
1425 "README", "contrib", "doc", "src", "tcl", "testing", "tools",
1427 # OpenOCD specific: End
1429 foreach my $check (@tree_check) {
1430 if (! -e $root . '/' . $check) {
1438 my ($formatted_email) = @_;
1442 my $name_comment = "";
1446 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1449 $comment = $3 if defined $3;
1450 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1452 $comment = $2 if defined $2;
1453 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1455 $comment = $2 if defined $2;
1456 $formatted_email =~ s/\Q$address\E.*$//;
1457 $name = $formatted_email;
1458 $name = trim($name);
1459 $name =~ s/^\"|\"$//g;
1460 # If there's a name left after stripping spaces and
1461 # leading quotes, and the address doesn't have both
1462 # leading and trailing angle brackets, the address
1464 # "joe smith joe@smith.com" bad
1465 # "joe smith <joe@smith.com" bad
1466 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1471 # OpenOCD specific: Begin: handle jenkins as valid email
1472 } elsif ($formatted_email eq "jenkins") {
1473 $address = "jenkins";
1474 # OpenOCD specific: End
1477 # Extract comments from names excluding quoted parts
1478 # "John D. (Doe)" - Do not extract
1479 if ($name =~ s/\"(.+)\"//) {
1482 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1483 $name_comment .= trim($1);
1485 $name =~ s/^[ \"]+|[ \"]+$//g;
1486 $name = trim("$quoted $name");
1488 $address = trim($address);
1489 $address =~ s/^\<|\>$//g;
1490 $comment = trim($comment);
1492 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1493 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1494 $name = "\"$name\"";
1497 return ($name, $name_comment, $address, $comment);
1501 my ($name, $name_comment, $address, $comment) = @_;
1503 my $formatted_email;
1505 $name =~ s/^[ \"]+|[ \"]+$//g;
1506 $address = trim($address);
1507 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1509 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1510 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1511 $name = "\"$name\"";
1514 $name_comment = trim($name_comment);
1515 $name_comment = " $name_comment" if ($name_comment ne "");
1516 $comment = trim($comment);
1517 $comment = " $comment" if ($comment ne "");
1519 if ("$name" eq "") {
1520 $formatted_email = "$address";
1522 $formatted_email = "$name$name_comment <$address>";
1524 $formatted_email .= "$comment";
1525 return $formatted_email;
1528 sub reformat_email {
1531 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1532 return format_email($email_name, $name_comment, $email_address, $comment);
1535 sub same_email_addresses {
1536 my ($email1, $email2) = @_;
1538 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1539 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1541 return $email1_name eq $email2_name &&
1542 $email1_address eq $email2_address &&
1543 $name1_comment eq $name2_comment &&
1544 $comment1 eq $comment2;
1550 foreach my $path (split(/:/, $ENV{PATH})) {
1551 if (-e "$path/$bin") {
1552 return "$path/$bin";
1562 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1563 if (-e "$path/$conf") {
1564 return "$path/$conf";
1576 for my $c (split(//, $str)) {
1580 for (; ($n % $tabsize) != 0; $n++) {
1592 (my $res = shift) =~ tr/\t/ /c;
1599 # Drop the diff line leader and expand tabs
1601 $line = expand_tabs($line);
1603 # Pick the indent from the front of the line.
1604 my ($white) = ($line =~ /^(\s*)/);
1606 return (length($line), length($white));
1609 my $sanitise_quote = '';
1611 sub sanitise_line_reset {
1612 my ($in_comment) = @_;
1615 $sanitise_quote = '*/';
1617 $sanitise_quote = '';
1630 # Always copy over the diff marker.
1631 $res = substr($line, 0, 1);
1633 for ($off = 1; $off < length($line); $off++) {
1634 $c = substr($line, $off, 1);
1636 # Comments we are whacking completely including the begin
1637 # and end, all to $;.
1638 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1639 $sanitise_quote = '*/';
1641 substr($res, $off, 2, "$;$;");
1645 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1646 $sanitise_quote = '';
1647 substr($res, $off, 2, "$;$;");
1651 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1652 $sanitise_quote = '//';
1654 substr($res, $off, 2, $sanitise_quote);
1659 # A \ in a string means ignore the next character.
1660 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1662 substr($res, $off, 2, 'XX');
1667 if ($c eq "'" || $c eq '"') {
1668 if ($sanitise_quote eq '') {
1669 $sanitise_quote = $c;
1671 substr($res, $off, 1, $c);
1673 } elsif ($sanitise_quote eq $c) {
1674 $sanitise_quote = '';
1678 #print "c<$c> SQ<$sanitise_quote>\n";
1679 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1680 substr($res, $off, 1, $;);
1681 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1682 substr($res, $off, 1, $;);
1683 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1684 substr($res, $off, 1, 'X');
1686 substr($res, $off, 1, $c);
1690 if ($sanitise_quote eq '//') {
1691 $sanitise_quote = '';
1694 # The pathname on a #include may be surrounded by '<' and '>'.
1695 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1696 my $clean = 'X' x length($1);
1697 $res =~ s@\<.*\>@<$clean>@;
1699 # The whole of a #error is a string.
1700 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1701 my $clean = 'X' x length($1);
1702 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1705 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1707 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1713 sub get_quoted_string {
1714 my ($line, $rawline) = @_;
1716 return "" if (!defined($line) || !defined($rawline));
1717 return "" if ($line !~ m/($String)/g);
1718 return substr($rawline, $-[0], $+[0] - $-[0]);
1721 sub ctx_statement_block {
1722 my ($linenr, $remain, $off) = @_;
1723 my $line = $linenr - 1;
1726 my $coff = $off - 1;
1740 @stack = (['', 0]) if ($#stack == -1);
1742 #warn "CSB: blk<$blk> remain<$remain>\n";
1743 # If we are about to drop off the end, pull in more
1746 for (; $remain > 0; $line++) {
1747 last if (!defined $lines[$line]);
1748 next if ($lines[$line] =~ /^-/);
1751 $blk .= $lines[$line] . "\n";
1752 $len = length($blk);
1756 # Bail if there is no further context.
1757 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1761 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1767 $c = substr($blk, $off, 1);
1768 $remainder = substr($blk, $off);
1770 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1772 # Handle nested #if/#else.
1773 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1774 push(@stack, [ $type, $level ]);
1775 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1776 ($type, $level) = @{$stack[$#stack - 1]};
1777 } elsif ($remainder =~ /^#\s*endif\b/) {
1778 ($type, $level) = @{pop(@stack)};
1781 # Statement ends at the ';' or a close '}' at the
1783 if ($level == 0 && $c eq ';') {
1787 # An else is really a conditional as long as its not else if
1788 if ($level == 0 && $coff_set == 0 &&
1789 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1790 $remainder =~ /^(else)(?:\s|{)/ &&
1791 $remainder !~ /^else\s+if\b/) {
1792 $coff = $off + length($1) - 1;
1794 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1795 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1798 if (($type eq '' || $type eq '(') && $c eq '(') {
1802 if ($type eq '(' && $c eq ')') {
1804 $type = ($level != 0)? '(' : '';
1806 if ($level == 0 && $coff < $soff) {
1809 #warn "CSB: mark coff<$coff>\n";
1812 if (($type eq '' || $type eq '{') && $c eq '{') {
1816 if ($type eq '{' && $c eq '}') {
1818 $type = ($level != 0)? '{' : '';
1821 if (substr($blk, $off + 1, 1) eq ';') {
1827 # Preprocessor commands end at the newline unless escaped.
1828 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1836 # We are truly at the end, so shuffle to the next line.
1843 my $statement = substr($blk, $soff, $off - $soff + 1);
1844 my $condition = substr($blk, $soff, $coff - $soff + 1);
1846 #warn "STATEMENT<$statement>\n";
1847 #warn "CONDITION<$condition>\n";
1849 #print "coff<$coff> soff<$off> loff<$loff>\n";
1851 return ($statement, $condition,
1852 $line, $remain + 1, $off - $loff + 1, $level);
1855 sub statement_lines {
1858 # Strip the diff line prefixes and rip blank lines at start and end.
1859 $stmt =~ s/(^|\n)./$1/g;
1863 my @stmt_lines = ($stmt =~ /\n/g);
1865 return $#stmt_lines + 2;
1868 sub statement_rawlines {
1871 my @stmt_lines = ($stmt =~ /\n/g);
1873 return $#stmt_lines + 2;
1876 sub statement_block_size {
1879 $stmt =~ s/(^|\n)./$1/g;
1885 my @stmt_lines = ($stmt =~ /\n/g);
1886 my @stmt_statements = ($stmt =~ /;/g);
1888 my $stmt_lines = $#stmt_lines + 2;
1889 my $stmt_statements = $#stmt_statements + 1;
1891 if ($stmt_lines > $stmt_statements) {
1894 return $stmt_statements;
1898 sub ctx_statement_full {
1899 my ($linenr, $remain, $off) = @_;
1900 my ($statement, $condition, $level);
1904 # Grab the first conditional/block pair.
1905 ($statement, $condition, $linenr, $remain, $off, $level) =
1906 ctx_statement_block($linenr, $remain, $off);
1907 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1908 push(@chunks, [ $condition, $statement ]);
1909 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1910 return ($level, $linenr, @chunks);
1913 # Pull in the following conditional/block pairs and see if they
1914 # could continue the statement.
1916 ($statement, $condition, $linenr, $remain, $off, $level) =
1917 ctx_statement_block($linenr, $remain, $off);
1918 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1919 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1921 push(@chunks, [ $condition, $statement ]);
1924 return ($level, $linenr, @chunks);
1928 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1930 my $start = $linenr - 1;
1937 my @stack = ($level);
1938 for ($line = $start; $remain > 0; $line++) {
1939 next if ($rawlines[$line] =~ /^-/);
1942 $blk .= $rawlines[$line];
1944 # Handle nested #if/#else.
1945 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1946 push(@stack, $level);
1947 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1948 $level = $stack[$#stack - 1];
1949 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1950 $level = pop(@stack);
1953 foreach my $c (split(//, $lines[$line])) {
1954 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1960 if ($c eq $close && $level > 0) {
1962 last if ($level == 0);
1963 } elsif ($c eq $open) {
1968 if (!$outer || $level <= 1) {
1969 push(@res, $rawlines[$line]);
1972 last if ($level == 0);
1975 return ($level, @res);
1977 sub ctx_block_outer {
1978 my ($linenr, $remain) = @_;
1980 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1984 my ($linenr, $remain) = @_;
1986 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1990 my ($linenr, $remain, $off) = @_;
1992 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1995 sub ctx_block_level {
1996 my ($linenr, $remain) = @_;
1998 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
2000 sub ctx_statement_level {
2001 my ($linenr, $remain, $off) = @_;
2003 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
2006 sub ctx_locate_comment {
2007 my ($first_line, $end_line) = @_;
2009 # If c99 comment on the current line, or the line before or after
2010 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
2011 return $current_comment if (defined $current_comment);
2012 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
2013 return $current_comment if (defined $current_comment);
2014 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
2015 return $current_comment if (defined $current_comment);
2017 # Catch a comment on the end of the line itself.
2018 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
2019 return $current_comment if (defined $current_comment);
2021 # Look through the context and try and figure out if there is a
2024 $current_comment = '';
2025 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
2026 my $line = $rawlines[$linenr - 1];
2028 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
2031 if ($line =~ m@/\*@) {
2034 if (!$in_comment && $current_comment ne '') {
2035 $current_comment = '';
2037 $current_comment .= $line . "\n" if ($in_comment);
2038 if ($line =~ m@\*/@) {
2043 chomp($current_comment);
2044 return($current_comment);
2046 sub ctx_has_comment {
2047 my ($first_line, $end_line) = @_;
2048 my $cmt = ctx_locate_comment($first_line, $end_line);
2050 ##print "LINE: $rawlines[$end_line - 1 ]\n";
2051 ##print "CMMT: $cmt\n";
2053 return ($cmt ne '');
2057 my ($linenr, $cnt) = @_;
2059 my $offset = $linenr - 1;
2064 $line = $rawlines[$offset++];
2065 next if (defined($line) && $line =~ /^-/);
2073 my ($linenr, $lc) = @_;
2075 my $stat_real = raw_line($linenr, 0);
2076 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2077 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2084 my ($linenr, $cnt, $here) = @_;
2086 my $herectx = $here . "\n";
2087 for (my $n = 0; $n < $cnt; $n++) {
2088 $herectx .= raw_line($linenr, $n) . "\n";
2099 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2102 $coded = sprintf("^%c", unpack('C', $2) + 64);
2111 my $av_preprocessor = 0;
2116 sub annotate_reset {
2117 $av_preprocessor = 0;
2119 @av_paren_type = ('E');
2120 $av_pend_colon = 'O';
2123 sub annotate_values {
2124 my ($stream, $type) = @_;
2127 my $var = '_' x length($stream);
2130 print "$stream\n" if ($dbg_values > 1);
2132 while (length($cur)) {
2133 @av_paren_type = ('E') if ($#av_paren_type < 0);
2134 print " <" . join('', @av_paren_type) .
2135 "> <$type> <$av_pending>" if ($dbg_values > 1);
2136 if ($cur =~ /^(\s+)/o) {
2137 print "WS($1)\n" if ($dbg_values > 1);
2138 if ($1 =~ /\n/ && $av_preprocessor) {
2139 $type = pop(@av_paren_type);
2140 $av_preprocessor = 0;
2143 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2144 print "CAST($1)\n" if ($dbg_values > 1);
2145 push(@av_paren_type, $type);
2148 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2149 print "DECLARE($1)\n" if ($dbg_values > 1);
2152 } elsif ($cur =~ /^($Modifier)\s*/) {
2153 print "MODIFIER($1)\n" if ($dbg_values > 1);
2156 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2157 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2158 $av_preprocessor = 1;
2159 push(@av_paren_type, $type);
2165 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2166 print "UNDEF($1)\n" if ($dbg_values > 1);
2167 $av_preprocessor = 1;
2168 push(@av_paren_type, $type);
2170 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2171 print "PRE_START($1)\n" if ($dbg_values > 1);
2172 $av_preprocessor = 1;
2174 push(@av_paren_type, $type);
2175 push(@av_paren_type, $type);
2178 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2179 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2180 $av_preprocessor = 1;
2182 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2186 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2187 print "PRE_END($1)\n" if ($dbg_values > 1);
2189 $av_preprocessor = 1;
2191 # Assume all arms of the conditional end as this
2192 # one does, and continue as if the #endif was not here.
2193 pop(@av_paren_type);
2194 push(@av_paren_type, $type);
2197 } elsif ($cur =~ /^(\\\n)/o) {
2198 print "PRECONT($1)\n" if ($dbg_values > 1);
2200 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2201 print "ATTR($1)\n" if ($dbg_values > 1);
2202 $av_pending = $type;
2205 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2206 print "SIZEOF($1)\n" if ($dbg_values > 1);
2212 } elsif ($cur =~ /^(if|while|for)\b/o) {
2213 print "COND($1)\n" if ($dbg_values > 1);
2217 } elsif ($cur =~/^(case)/o) {
2218 print "CASE($1)\n" if ($dbg_values > 1);
2219 $av_pend_colon = 'C';
2222 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2223 print "KEYWORD($1)\n" if ($dbg_values > 1);
2226 } elsif ($cur =~ /^(\()/o) {
2227 print "PAREN('$1')\n" if ($dbg_values > 1);
2228 push(@av_paren_type, $av_pending);
2232 } elsif ($cur =~ /^(\))/o) {
2233 my $new_type = pop(@av_paren_type);
2234 if ($new_type ne '_') {
2236 print "PAREN('$1') -> $type\n"
2237 if ($dbg_values > 1);
2239 print "PAREN('$1')\n" if ($dbg_values > 1);
2242 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2243 print "FUNC($1)\n" if ($dbg_values > 1);
2247 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2248 if (defined $2 && $type eq 'C' || $type eq 'T') {
2249 $av_pend_colon = 'B';
2250 } elsif ($type eq 'E') {
2251 $av_pend_colon = 'L';
2253 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2256 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2257 print "IDENT($1)\n" if ($dbg_values > 1);
2260 } elsif ($cur =~ /^($Assignment)/o) {
2261 print "ASSIGN($1)\n" if ($dbg_values > 1);
2264 } elsif ($cur =~/^(;|{|})/) {
2265 print "END($1)\n" if ($dbg_values > 1);
2267 $av_pend_colon = 'O';
2269 } elsif ($cur =~/^(,)/) {
2270 print "COMMA($1)\n" if ($dbg_values > 1);
2273 } elsif ($cur =~ /^(\?)/o) {
2274 print "QUESTION($1)\n" if ($dbg_values > 1);
2277 } elsif ($cur =~ /^(:)/o) {
2278 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2280 substr($var, length($res), 1, $av_pend_colon);
2281 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2286 $av_pend_colon = 'O';
2288 } elsif ($cur =~ /^(\[)/o) {
2289 print "CLOSE($1)\n" if ($dbg_values > 1);
2292 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2295 print "OPV($1)\n" if ($dbg_values > 1);
2302 substr($var, length($res), 1, $variant);
2305 } elsif ($cur =~ /^($Operators)/o) {
2306 print "OP($1)\n" if ($dbg_values > 1);
2307 if ($1 ne '++' && $1 ne '--') {
2311 } elsif ($cur =~ /(^.)/o) {
2312 print "C($1)\n" if ($dbg_values > 1);
2315 $cur = substr($cur, length($1));
2316 $res .= $type x length($1);
2320 return ($res, $var);
2324 my ($possible, $line) = @_;
2325 my $notPermitted = qr{(?:
2342 ^(?:typedef|struct|enum)\b
2344 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2345 if ($possible !~ $notPermitted) {
2346 # Check for modifiers.
2347 $possible =~ s/\s*$Storage\s*//g;
2348 $possible =~ s/\s*$Sparse\s*//g;
2349 if ($possible =~ /^\s*$/) {
2351 } elsif ($possible =~ /\s/) {
2352 $possible =~ s/\s*$Type\s*//g;
2353 for my $modifier (split(' ', $possible)) {
2354 if ($modifier !~ $notPermitted) {
2355 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2356 push(@modifierListFile, $modifier);
2361 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2362 push(@typeListFile, $possible);
2366 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2375 $type =~ tr/[a-z]/[A-Z]/;
2377 return defined $use_type{$type} if (scalar keys %use_type > 0);
2379 return !defined $ignore_type{$type};
2383 my ($level, $type, $msg) = @_;
2385 if (!show_type($type) ||
2386 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2391 if ($level eq 'ERROR') {
2393 } elsif ($level eq 'WARNING') {
2399 $output .= $prefix . $level . ':';
2401 $output .= BLUE if ($color);
2402 $output .= "$type:";
2404 $output .= RESET if ($color);
2405 $output .= ' ' . $msg . "\n";
2408 my @lines = split("\n", $output, -1);
2409 splice(@lines, 1, 1);
2410 $output = join("\n", @lines);
2414 $output = (split('\n', $output))[0] . "\n";
2417 if ($verbose && exists($verbose_messages{$type}) &&
2418 !exists($verbose_emitted{$type})) {
2419 $output .= $verbose_messages{$type} . "\n\n";
2420 $verbose_emitted{$type} = 1;
2423 push(our @report, $output);
2432 sub fixup_current_range {
2433 my ($lineRef, $offset, $length) = @_;
2435 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2438 my $no = $o + $offset;
2439 my $nl = $l + $length;
2440 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2444 sub fix_inserted_deleted_lines {
2445 my ($linesRef, $insertedRef, $deletedRef) = @_;
2447 my $range_last_linenr = 0;
2448 my $delta_offset = 0;
2453 my $next_insert = 0;
2454 my $next_delete = 0;
2458 my $inserted = @{$insertedRef}[$next_insert++];
2459 my $deleted = @{$deletedRef}[$next_delete++];
2461 foreach my $old_line (@{$linesRef}) {
2463 my $line = $old_line; #don't modify the array
2464 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2466 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2467 $range_last_linenr = $new_linenr;
2468 fixup_current_range(\$line, $delta_offset, 0);
2471 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2472 $deleted = @{$deletedRef}[$next_delete++];
2474 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2477 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2478 push(@lines, ${$inserted}{'LINE'});
2479 $inserted = @{$insertedRef}[$next_insert++];
2481 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2485 push(@lines, $line);
2495 sub fix_insert_line {
2496 my ($linenr, $line) = @_;
2502 push(@fixed_inserted, $inserted);
2505 sub fix_delete_line {
2506 my ($linenr, $line) = @_;
2513 push(@fixed_deleted, $deleted);
2517 my ($type, $msg) = @_;
2519 if (report("ERROR", $type, $msg)) {
2527 my ($type, $msg) = @_;
2529 if (report("WARNING", $type, $msg)) {
2537 my ($type, $msg) = @_;
2539 if ($check && report("CHECK", $type, $msg)) {
2547 sub check_absolute_file {
2548 my ($absolute, $herecurr) = @_;
2549 my $file = $absolute;
2551 ##print "absolute<$absolute>\n";
2553 # See if any suffix of this path is a path within the tree.
2554 while ($file =~ s@^[^/]*/@@) {
2555 if (-f "$root/$file") {
2556 ##print "file<$file>\n";
2564 # It is, so see if the prefix is acceptable.
2565 my $prefix = $absolute;
2566 substr($prefix, -length($file)) = '';
2568 ##print "prefix<$prefix>\n";
2569 if ($prefix ne ".../") {
2570 WARN("USE_RELATIVE_PATH",
2571 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2578 $string =~ s/^\s+|\s+$//g;
2586 $string =~ s/^\s+//;
2594 $string =~ s/\s+$//;
2599 sub string_find_replace {
2600 my ($string, $find, $replace) = @_;
2602 $string =~ s/$find/$replace/g;
2610 my $source_indent = $tabsize;
2611 my $max_spaces_before_tab = $source_indent - 1;
2612 my $spaces_to_tab = " " x $source_indent;
2614 #convert leading spaces to tabs
2615 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2616 #Remove spaces before a tab
2617 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2622 sub pos_last_openparen {
2627 my $opens = $line =~ tr/\(/\(/;
2628 my $closes = $line =~ tr/\)/\)/;
2630 my $last_openparen = 0;
2632 if (($opens == 0) || ($closes >= $opens)) {
2636 my $len = length($line);
2638 for ($pos = 0; $pos < $len; $pos++) {
2639 my $string = substr($line, $pos);
2640 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2641 $pos += length($1) - 1;
2642 } elsif (substr($line, $pos, 1) eq '(') {
2643 $last_openparen = $pos;
2644 } elsif (index($string, '(') == -1) {
2649 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2652 sub get_raw_comment {
2653 my ($line, $rawline) = @_;
2656 for my $i (0 .. (length($line) - 1)) {
2657 if (substr($line, $i, 1) eq "$;") {
2658 $comment .= substr($rawline, $i, 1);
2665 sub exclude_global_initialisers {
2666 my ($realfile) = @_;
2668 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2669 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2670 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2671 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2675 my $filename = shift;
2681 my $stashrawline="";
2691 my $authorsignoff = 0;
2692 my $author_sob = '';
2694 my $is_binding_patch = -1;
2695 my $in_header_lines = $file ? 0 : 1;
2696 my $in_commit_log = 0; #Scanning lines before patch
2697 my $has_patch_separator = 0; #Found a --- line
2698 my $has_commit_log = 0; #Encountered lines before patch
2699 my $commit_log_lines = 0; #Number of commit log lines
2700 my $commit_log_possible_stack_dump = 0;
2701 my $commit_log_long_line = 0;
2702 my $commit_log_has_diff = 0;
2703 my $reported_maintainer_file = 0;
2704 my $non_utf8_charset = 0;
2706 my $last_git_commit_id_linenr = -1;
2708 my $last_blank_line = 0;
2709 my $last_coalesced_string_linenr = -1;
2717 # Trace the real file/line as we go.
2722 my $context_function; #undef'd unless there's a known function
2724 my $comment_edge = 0;
2728 my $prev_values = 'E';
2731 my %suppress_ifbraces;
2732 my %suppress_whiletrailers;
2733 my %suppress_export;
2734 my $suppress_statement = 0;
2736 my %signatures = ();
2738 # Pre-scan the patch sanitizing the lines.
2739 # Pre-scan the patch looking for any __setup documentation.
2741 my @setup_docs = ();
2744 my $camelcase_file_seeded = 0;
2746 my $checklicenseline = 1;
2748 sanitise_line_reset();
2750 foreach my $rawline (@rawlines) {
2754 push(@fixed, $rawline) if ($fix);
2756 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2758 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2763 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2772 # Guestimate if this is a continuing comment. Run
2773 # the context looking for a comment "edge". If this
2774 # edge is a close comment then we must be in a comment
2778 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2779 next if (defined $rawlines[$ln - 1] &&
2780 $rawlines[$ln - 1] =~ /^-/);
2782 #print "RAW<$rawlines[$ln - 1]>\n";
2783 last if (!defined $rawlines[$ln - 1]);
2784 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2785 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2790 if (defined $edge && $edge eq '*/') {
2794 # Guestimate if this is a continuing comment. If this
2795 # is the start of a diff block and this line starts
2796 # ' *' then it is very likely a comment.
2797 if (!defined $edge &&
2798 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2803 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2804 sanitise_line_reset($in_comment);
2806 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2807 # Standardise the strings and chars within the input to
2808 # simplify matching -- only bother with positive lines.
2809 $line = sanitise_line($rawline);
2811 push(@lines, $line);
2814 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2819 #print "==>$rawline\n";
2820 #print "-->$line\n";
2822 if ($setup_docs && $line =~ /^\+/) {
2823 push(@setup_docs, $line);
2832 foreach my $line (@lines) {
2835 my $sline = $line; #copy of $line
2836 $sline =~ s/$;/ /g; #with comments as spaces
2838 my $rawline = $rawlines[$linenr - 1];
2839 my $raw_comment = get_raw_comment($line, $rawline);
2841 # check if it's a mode change, rename or start of a patch
2842 if (!$in_commit_log &&
2843 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2844 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2845 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2849 #extract the line range in the file after the patch is applied
2850 if (!$in_commit_log &&
2851 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2854 $first_line = $linenr + 1;
2864 %suppress_ifbraces = ();
2865 %suppress_whiletrailers = ();
2866 %suppress_export = ();
2867 $suppress_statement = 0;
2868 if ($context =~ /\b(\w+)\s*\(/) {
2869 $context_function = $1;
2871 undef $context_function;
2875 # track the line number as we move through the hunk, note that
2876 # new versions of GNU diff omit the leading space on completely
2877 # blank context lines so we need to count that too.
2878 } elsif ($line =~ /^( |\+|$)/) {
2880 $realcnt-- if ($realcnt != 0);
2882 # Measure the line length and indent.
2883 ($length, $indent) = line_stats($rawline);
2885 # Track the previous line.
2886 ($prevline, $stashline) = ($stashline, $line);
2887 ($previndent, $stashindent) = ($stashindent, $indent);
2888 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2890 #warn "line<$line>\n";
2892 } elsif ($realcnt == 1) {
2896 my $hunk_line = ($realcnt != 0);
2898 $here = "#$linenr: " if (!$file);
2899 $here = "#$realline: " if ($file);
2902 # extract the filename as it passes
2903 if ($line =~ /^diff --git.*?(\S+)$/) {
2905 $realfile =~ s@^([^/]*)/@@ if (!$file);
2908 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2910 $realfile =~ s@^([^/]*)/@@ if (!$file);
2914 if (!$file && $tree && $p1_prefix ne '' &&
2915 -e "$root/$p1_prefix") {
2916 WARN("PATCH_PREFIX",
2917 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2920 if ($realfile =~ m@^include/asm/@) {
2921 ERROR("MODIFIED_INCLUDE_ASM",
2922 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2927 #make up the handle for any error we report on this line
2929 $prefix = "$realfile:$realline: "
2932 $prefix = "$filename:$realline: ";
2934 $prefix = "$filename:$linenr: ";
2939 if (is_maintained_obsolete($realfile)) {
2941 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2943 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2946 $check = $check_orig;
2948 $checklicenseline = 1;
2950 if ($realfile !~ /^MAINTAINERS/) {
2951 my $last_binding_patch = $is_binding_patch;
2953 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2955 if (($last_binding_patch != -1) &&
2956 ($last_binding_patch ^ $is_binding_patch)) {
2957 WARN("DT_SPLIT_BINDING_PATCH",
2958 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2965 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2967 my $hereline = "$here\n$rawline\n";
2968 my $herecurr = "$here\n$rawline\n";
2969 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2971 $cnt_lines++ if ($realcnt != 0);
2973 # Verify the existence of a commit log if appropriate
2974 # 2 is used because a $signature is counted in $commit_log_lines
2975 if ($in_commit_log) {
2976 if ($line !~ /^\s*$/) {
2977 $commit_log_lines++; #could be a $signature
2979 } elsif ($has_commit_log && $commit_log_lines < 2) {
2980 WARN("COMMIT_MESSAGE",
2981 "Missing commit description - Add an appropriate one\n");
2982 $commit_log_lines = 2; #warn only once
2985 # Check if the commit log has what seems like a diff which can confuse patch
2986 if ($in_commit_log && !$commit_log_has_diff &&
2987 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2988 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2989 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2990 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2991 ERROR("DIFF_IN_COMMIT_MSG",
2992 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2993 $commit_log_has_diff = 1;
2996 # Check for incorrect file permissions
2997 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2998 my $permhere = $here . "FILE: $realfile\n";
2999 if ($realfile !~ m@scripts/@ &&
3000 $realfile !~ /\.(py|pl|awk|sh)$/) {
3001 ERROR("EXECUTE_PERMISSIONS",
3002 "do not set execute permissions for source files\n" . $permhere);
3006 # Check the patch for a From:
3007 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
3009 my $curline = $linenr;
3010 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
3013 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
3015 $author = reformat_email($author);
3018 # Check the patch for a signoff:
3019 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
3022 if ($author ne '' && $authorsignoff != 1) {
3023 if (same_email_addresses($1, $author)) {
3027 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
3028 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
3030 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
3033 } elsif (lc $email_address eq lc $author_address) {
3036 } elsif ($email_name eq $author_name) {
3040 my $address1 = $email_address;
3041 my $address2 = $author_address;
3043 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
3046 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
3049 if ($address1 eq $address2) {
3057 # OpenOCD specific: Begin: Extend list of checkpatch tests to ignore
3058 if ($in_commit_log && $line =~ /^\s*Checkpatch-ignore:\s*(.*)/) {
3059 my @array = split(/[\s,]+/, $1);
3060 hash_save_array_words(\%ignore_type, \@array);
3062 # OpenOCD specific: End
3064 # Check for patch separator
3065 if ($line =~ /^---$/) {
3066 $has_patch_separator = 1;
3070 # Check if MAINTAINERS is being updated. If so, there's probably no need to
3071 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
3072 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3073 $reported_maintainer_file = 1;
3076 # Check signature styles
3077 if (!$in_header_lines &&
3078 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3079 my $space_before = $1;
3081 my $space_after = $3;
3083 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3085 if ($sign_off !~ /$signature_tags/) {
3086 my $suggested_signature = find_standard_signature($sign_off);
3087 if ($suggested_signature eq "") {
3088 WARN("BAD_SIGN_OFF",
3089 "Non-standard signature: $sign_off\n" . $herecurr);
3091 if (WARN("BAD_SIGN_OFF",
3092 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3094 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3098 if (defined $space_before && $space_before ne "") {
3099 if (WARN("BAD_SIGN_OFF",
3100 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3102 $fixed[$fixlinenr] =
3103 "$ucfirst_sign_off $email";
3106 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3107 if (WARN("BAD_SIGN_OFF",
3108 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3110 $fixed[$fixlinenr] =
3111 "$ucfirst_sign_off $email";
3115 if (!defined $space_after || $space_after ne " ") {
3116 if (WARN("BAD_SIGN_OFF",
3117 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3119 $fixed[$fixlinenr] =
3120 "$ucfirst_sign_off $email";
3124 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3125 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3126 if ($suggested_email eq "") {
3127 ERROR("BAD_SIGN_OFF",
3128 "Unrecognized email address: '$email'\n" . $herecurr);
3130 my $dequoted = $suggested_email;
3131 $dequoted =~ s/^"//;
3132 $dequoted =~ s/" </ </;
3133 # Don't force email to have quotes
3134 # Allow just an angle bracketed address
3135 if (!same_email_addresses($email, $suggested_email)) {
3136 if (WARN("BAD_SIGN_OFF",
3137 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3139 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3143 # Address part shouldn't have comments
3144 my $stripped_address = $email_address;
3145 $stripped_address =~ s/\([^\(\)]*\)//g;
3146 if ($email_address ne $stripped_address) {
3147 if (WARN("BAD_SIGN_OFF",
3148 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3150 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3154 # Only one name comment should be allowed
3155 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3156 if ($comment_count > 1) {
3157 WARN("BAD_SIGN_OFF",
3158 "Use a single name comment in email: '$email'\n" . $herecurr);
3162 # stable@vger.kernel.org or stable@kernel.org shouldn't
3163 # have an email name. In addition comments should strictly
3165 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3166 if (($comment ne "" && $comment !~ /^#.+/) ||
3167 ($email_name ne "")) {
3168 my $cur_name = $email_name;
3169 my $new_comment = $comment;
3170 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3172 # Remove brackets enclosing comment text
3173 # and # from start of comments to get comment text
3174 $new_comment =~ s/^\((.*)\)$/$1/;
3175 $new_comment =~ s/^\[(.*)\]$/$1/;
3176 $new_comment =~ s/^[\s\#]+|\s+$//g;
3178 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3179 $new_comment = " # $new_comment" if ($new_comment ne "");
3180 my $new_email = "$email_address$new_comment";
3182 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3183 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3185 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3188 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3189 my $new_comment = $comment;
3191 # Extract comment text from within brackets or
3192 # c89 style /*...*/ comments
3193 $new_comment =~ s/^\[(.*)\]$/$1/;
3194 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3196 $new_comment = trim($new_comment);
3197 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3198 $new_comment = "($new_comment)" if ($new_comment ne "");
3199 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3201 if (WARN("BAD_SIGN_OFF",
3202 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3204 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3209 # Check for duplicate signatures
3210 my $sig_nospace = $line;
3211 $sig_nospace =~ s/\s//g;
3212 $sig_nospace = lc($sig_nospace);
3213 if (defined $signatures{$sig_nospace}) {
3214 WARN("BAD_SIGN_OFF",
3215 "Duplicate signature\n" . $herecurr);
3217 $signatures{$sig_nospace} = 1;
3220 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3221 if ($sign_off =~ /^co-developed-by:$/i) {
3222 if ($email eq $author) {
3223 WARN("BAD_SIGN_OFF",
3224 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3226 if (!defined $lines[$linenr]) {
3227 WARN("BAD_SIGN_OFF",
3228 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3229 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3230 WARN("BAD_SIGN_OFF",
3231 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3232 } elsif ($1 ne $email) {
3233 WARN("BAD_SIGN_OFF",
3234 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3239 # Check email subject for common tools that don't need to be mentioned
3240 if ($in_header_lines &&
3241 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3242 WARN("EMAIL_SUBJECT",
3243 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3246 # Check for Gerrit Change-Ids not in any patch context
3247 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3248 if (ERROR("GERRIT_CHANGE_ID",
3249 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3251 fix_delete_line($fixlinenr, $rawline);
3255 # Check if the commit log is in a possible stack dump
3256 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3257 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3258 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3260 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3261 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3262 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3263 # stack dump address styles
3264 $commit_log_possible_stack_dump = 1;
3267 # Check for line lengths > 75 in commit log, warn once
3268 if ($in_commit_log && !$commit_log_long_line &&
3269 length($line) > 75 &&
3270 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3271 # file delta changes
3272 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3274 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3275 # A Fixes: or Link: line or signature tag line
3276 $commit_log_possible_stack_dump)) {
3277 WARN("COMMIT_LOG_LONG_LINE",
3278 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3279 $commit_log_long_line = 1;
3282 # Reset possible stack dump if a blank line is found
3283 if ($in_commit_log && $commit_log_possible_stack_dump &&
3285 $commit_log_possible_stack_dump = 0;
3288 # Check for lines starting with a #
3289 if ($in_commit_log && $line =~ /^#/) {
3290 if (WARN("COMMIT_COMMENT_SYMBOL",
3291 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3293 $fixed[$fixlinenr] =~ s/^/ /;
3297 # Check for git id commit length and improperly formed commit descriptions
3298 # A correctly formed commit description is:
3299 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3300 # with the commit subject '("' prefix and '")' suffix
3301 # This is a fairly compilicated block as it tests for what appears to be
3302 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3303 # possible SHA-1 matches.
3304 # A commit match can span multiple lines so this block attempts to find a
3305 # complete typical commit on a maximum of 3 lines
3306 if ($perl_version_ok &&
3307 $in_commit_log && !$commit_log_possible_stack_dump &&
3308 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3309 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3310 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3311 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3312 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3313 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3314 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3315 my $init_char = "c";
3316 my $orig_commit = "";
3321 my $id = '0123456789ab';
3322 my $orig_desc = "commit description";
3323 my $description = "";
3324 my $herectx = $herecurr;
3329 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3330 for (my $n = 0; $n < 2; $n++) {
3331 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3334 # Always strip leading/trailing parens then double quotes if existing
3335 $orig_desc = substr($orig_desc, 1, -1);
3336 if ($orig_desc =~ /^".*"$/) {
3337 $orig_desc = substr($orig_desc, 1, -1);
3342 last if ($#lines < $linenr + $n);
3343 $input .= " " . trim($rawlines[$linenr + $n]);
3344 $herectx .= "$rawlines[$linenr + $n]\n";
3346 $herectx = $herecurr if (!$has_parens);
3349 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3351 $orig_commit = lc($2);
3352 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3353 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3354 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3355 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3356 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3357 $orig_commit = lc($1);
3360 ($id, $description) = git_commit_info($orig_commit,
3364 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3365 $last_git_commit_id_linenr != $linenr - 1) {
3366 ERROR("GIT_COMMIT_ID",
3367 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3369 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3370 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3373 # Check for added, moved or deleted files
3374 if (!$reported_maintainer_file && !$in_commit_log &&
3375 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3376 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3377 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3378 (defined($1) || defined($2))))) {
3380 $reported_maintainer_file = 1;
3381 WARN("FILE_PATH_CHANGES",
3382 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3385 # Check for adding new DT bindings not in schema format
3386 if (!$in_commit_log &&
3387 ($line =~ /^new file mode\s*\d+\s*$/) &&
3388 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3389 WARN("DT_SCHEMA_BINDING_PATCH",
3390 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3393 # Check for wrappage within a valid hunk of the file
3394 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3395 ERROR("CORRUPTED_PATCH",
3396 "patch seems to be corrupt (line wrapped?)\n" .
3397 $herecurr) if (!$emitted_corrupt++);
3400 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3401 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3402 $rawline !~ m/^$UTF8*$/) {
3403 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3405 my $blank = copy_spacing($rawline);
3406 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3407 my $hereptr = "$hereline$ptr\n";
3410 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3413 # Check if it's the start of a commit log
3414 # (not a header line and we haven't seen the patch filename)
3415 if ($in_header_lines && $realfile =~ /^$/ &&
3416 !($rawline =~ /^\s+(?:\S|$)/ ||
3417 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3418 $in_header_lines = 0;
3420 $has_commit_log = 1;
3423 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3424 # declined it, i.e defined some charset where it is missing.
3425 if ($in_header_lines &&
3426 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3428 $non_utf8_charset = 1;
3431 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3432 $rawline =~ /$NON_ASCII_UTF8/) {
3433 WARN("UTF8_BEFORE_PATCH",
3434 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3437 # Check for absolute kernel paths in commit message
3438 if ($tree && $in_commit_log) {
3439 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3442 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3443 check_absolute_file($1, $herecurr)) {
3446 check_absolute_file($file, $herecurr);
3451 # Check for various typo / spelling mistakes
3452 if (defined($misspellings) &&
3453 # OpenOCD specific: Begin: don't check spelling on spelling_file
3454 index($spelling_file, $realfile) + length($realfile) != length($spelling_file) &&
3455 # OpenOCD specific: End
3456 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3457 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3459 my $blank = copy_spacing($rawline);
3460 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3461 my $hereptr = "$hereline$ptr\n";
3462 my $typo_fix = $spelling_fix{lc($typo)};
3463 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3464 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3465 my $msg_level = \&WARN;
3466 $msg_level = \&CHK if ($file);
3467 if (&{$msg_level}("TYPO_SPELLING",
3468 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3470 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3475 # check for invalid commit id
3476 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3479 ($id, $description) = git_commit_info($2, undef, undef);
3480 if (!defined($id)) {
3481 WARN("UNKNOWN_COMMIT_ID",
3482 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3486 # check for repeated words separated by a single space
3487 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3488 if (($rawline =~ /^\+/ || $in_commit_log) &&
3489 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3490 pos($rawline) = 1 if (!$in_commit_log);
3491 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3495 my $start_pos = $-[1];
3496 my $end_pos = $+[2];
3497 if ($first =~ /(?:struct|union|enum)/) {
3498 pos($rawline) += length($first) + length($second) + 1;
3502 next if (lc($first) ne lc($second));
3503 next if ($first eq 'long');
3505 # check for character before and after the word matches
3506 my $start_char = '';
3508 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3509 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3511 next if ($start_char =~ /^\S$/);
3512 next if (index(" \t.,;?!", $end_char) == -1);
3514 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3515 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3516 next if (!exists($allow_repeated_words{lc($first)}));
3519 if (WARN("REPEATED_WORD",
3520 "Possible repeated word: '$first'\n" . $herecurr) &&
3522 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3526 # if it's a repeated word on consecutive lines in a comment block
3527 if ($prevline =~ /$;+\s*$/ &&
3528 $prevrawline =~ /($word_pattern)\s*$/) {
3530 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3531 if (WARN("REPEATED_WORD",
3532 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3534 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3540 # ignore non-hunk lines and lines being removed
3541 next if (!$hunk_line || $line =~ /^-/);
3543 #trailing whitespace
3544 if ($line =~ /^\+.*\015/) {
3545 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3546 if (ERROR("DOS_LINE_ENDINGS",
3547 "DOS line endings\n" . $herevet) &&
3549 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3551 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3552 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3553 if (ERROR("TRAILING_WHITESPACE",
3554 "trailing whitespace\n" . $herevet) &&
3556 $fixed[$fixlinenr] =~ s/\s+$//;
3562 # Check for FSF mailing addresses.
3563 if ($rawline =~ /\bwrite to the Free/i ||
3564 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3565 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3566 $rawline =~ /\b51\s+Franklin\s+St/i) {
3567 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3568 my $msg_level = \&ERROR;
3569 $msg_level = \&CHK if ($file);
3570 &{$msg_level}("FSF_MAILING_ADDRESS",
3571 "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. OpenOCD already includes a copy of the GPL.\n" . $herevet)
3574 # check for Kconfig help text having a real description
3575 # Only applies when adding the entry originally, after that we do not have
3576 # sufficient context to determine whether it is indeed long enough.
3577 if ($realfile =~ /Kconfig/ &&
3578 # 'choice' is usually the last thing on the line (though
3579 # Kconfig supports named choices), so use a word boundary
3580 # (\b) rather than a whitespace character (\s)
3581 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3585 my $help_length = 0;
3586 while (defined $lines[$ln]) {
3587 my $f = $lines[$ln++];
3589 next if ($f =~ /^-/);
3590 last if ($f !~ /^[\+ ]/); # !patch context
3592 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3596 if ($f =~ /^\+\s*help\s*$/) {
3601 $f =~ s/^.//; # strip patch context [+ ]
3602 $f =~ s/#.*//; # strip # directives
3603 $f =~ s/^\s+//; # strip leading blanks
3604 next if ($f =~ /^$/); # skip blank lines
3606 # At the end of this Kconfig block:
3607 # This only checks context lines in the patch
3608 # and so hopefully shouldn't trigger false
3609 # positives, even though some of these are
3610 # common words in help texts
3611 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3612 if|endif|menu|endmenu|source)\b/x) {
3615 $help_length++ if ($has_help);
3618 $help_length < $min_conf_desc_length) {
3619 my $stat_real = get_stat_real($linenr, $ln - 1);
3620 WARN("CONFIG_DESCRIPTION",
3621 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3625 # check MAINTAINERS entries
3626 if ($realfile =~ /^MAINTAINERS$/) {
3627 # check MAINTAINERS entries for the right form
3628 if ($rawline =~ /^\+[A-Z]:/ &&
3629 $rawline !~ /^\+[A-Z]:\t\S/) {
3630 if (WARN("MAINTAINERS_STYLE",
3631 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3633 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3636 # check MAINTAINERS entries for the right ordering too
3637 my $preferred_order = 'MRLSWQBCPTFXNK';
3638 if ($rawline =~ /^\+[A-Z]:/ &&
3639 $prevrawline =~ /^[\+ ][A-Z]:/) {
3640 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3643 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3646 my $curindex = index($preferred_order, $cur);
3647 my $previndex = index($preferred_order, $prev);
3648 if ($curindex < 0) {
3649 WARN("MAINTAINERS_STYLE",
3650 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3652 if ($previndex >= 0 && $curindex < $previndex) {
3653 WARN("MAINTAINERS_STYLE",
3654 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3655 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3656 ($prev eq 'X' && $cur eq 'X')) &&
3657 ($prevval cmp $curval) > 0) {
3658 WARN("MAINTAINERS_STYLE",
3659 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3665 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3666 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3669 'EXTRA_AFLAGS' => 'asflags-y',
3670 'EXTRA_CFLAGS' => 'ccflags-y',
3671 'EXTRA_CPPFLAGS' => 'cppflags-y',
3672 'EXTRA_LDFLAGS' => 'ldflags-y',
3675 WARN("DEPRECATED_VARIABLE",
3676 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3679 # check for DT compatible documentation
3680 if (defined $root &&
3681 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3682 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3684 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3686 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3687 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3689 foreach my $compat (@compats) {
3690 my $compat2 = $compat;
3691 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3692 my $compat3 = $compat;
3693 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3694 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3696 WARN("UNDOCUMENTED_DT_STRING",
3697 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3700 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3702 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3704 WARN("UNDOCUMENTED_DT_STRING",
3705 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3710 # check for using SPDX license tag at beginning of files
3711 if ($realline == $checklicenseline) {
3712 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3713 $checklicenseline = 2;
3714 } elsif ($rawline =~ /^\+/) {
3716 if ($realfile =~ /\.(h|s|S)$/) {
3718 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3720 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3722 } elsif ($realfile =~ /\.rst$/) {
3724 # OpenOCD specific: Begin
3725 } elsif ($realfile =~ /\.(am|cfg|tcl)$/) {
3727 # OpenOCD specific: End
3730 # check SPDX comment style for .[chsS] files
3731 if ($realfile =~ /\.[chsS]$/ &&
3732 $rawline =~ /SPDX-License-Identifier:/ &&
3733 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3734 WARN("SPDX_LICENSE_TAG",
3735 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3738 if ($comment !~ /^$/ &&
3739 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3740 WARN("SPDX_LICENSE_TAG",
3741 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3742 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3743 my $spdx_license = $1;
3744 if (!is_SPDX_License_valid($spdx_license)) {
3745 WARN("SPDX_LICENSE_TAG",
3746 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3748 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3749 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3750 my $msg_level = \&WARN;
3751 $msg_level = \&CHK if ($file);
3752 if (&{$msg_level}("SPDX_LICENSE_TAG",
3754 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3756 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3763 # check for embedded filenames
3764 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3765 WARN("EMBEDDED_FILENAME",
3766 "It's generally not useful to have the filename in the file\n" . $herecurr);
3769 # check we are in a valid source file if not then ignore this hunk
3770 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3772 # check for using SPDX-License-Identifier on the wrong line number
3773 if ($realline != $checklicenseline &&
3774 $rawline =~ /\bSPDX-License-Identifier:/ &&
3775 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3776 WARN("SPDX_LICENSE_TAG",
3777 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3780 # line length limit (with some exclusions)
3782 # There are a few types of lines that may extend beyond $max_line_length:
3783 # logging functions like pr_info that end in a string
3784 # lines with a single string
3785 # #defines that are a single string
3786 # lines with an RFC3986 like URL
3788 # There are 3 different line length message types:
3789 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3790 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3791 # LONG_LINE all other lines longer than $max_line_length
3793 # if LONG_LINE is ignored, the other 2 types are also ignored
3796 if ($line =~ /^\+/ && $length > $max_line_length) {
3797 my $msg_type = "LONG_LINE";
3799 # Check the allowed long line types first
3801 # logging functions that end in a string that starts
3802 # before $max_line_length
3803 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3804 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3807 # lines with only strings (w/ possible termination)
3808 # #defines with only strings
3809 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3810 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3813 # More special cases
3814 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3815 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3818 # URL ($rawline is used in case the URL is in a comment)
3819 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3822 # Otherwise set the alternate message types
3824 # a comment starts before $max_line_length
3825 } elsif ($line =~ /($;[\s$;]*)$/ &&
3826 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3827 $msg_type = "LONG_LINE_COMMENT"
3829 # a quoted string starts before $max_line_length
3830 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3831 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3832 $msg_type = "LONG_LINE_STRING"
3835 if ($msg_type ne "" &&
3836 (show_type("LONG_LINE") || show_type($msg_type))) {
3837 my $msg_level = \&WARN;
3838 $msg_level = \&CHK if ($file);
3839 &{$msg_level}($msg_type,
3840 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3844 # check for adding lines without a newline.
3845 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3846 if (WARN("MISSING_EOF_NEWLINE",
3847 "adding a line without newline at end of file\n" . $herecurr) &&
3849 fix_delete_line($fixlinenr+1, "No newline at end of file");
3853 # check for .L prefix local symbols in .S files
3854 if ($realfile =~ /\.S$/ &&
3855 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3856 WARN("AVOID_L_PREFIX",
3857 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/asm-annotations.rst\n" . $herecurr);
3860 # check we are in a valid source file C or perl if not then ignore this hunk
3861 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3863 # at the beginning of a line any tabs must come first and anything
3864 # more than $tabsize must use tabs.
3865 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3866 $rawline =~ /^\+\s* \s*/) {
3867 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3869 if (ERROR("CODE_INDENT",
3870 "code indent should use tabs where possible\n" . $herevet) &&
3872 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3876 # check for space before tabs.
3877 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3878 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3879 if (WARN("SPACE_BEFORE_TAB",
3880 "please, no space before tabs\n" . $herevet) &&
3882 while ($fixed[$fixlinenr] =~
3883 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3884 while ($fixed[$fixlinenr] =~
3885 s/(^\+.*) +\t/$1\t/) {}
3889 # check for assignments on the start of a line
3890 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3892 if (CHK("ASSIGNMENT_CONTINUATIONS",
3893 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3894 $fix && $prevrawline =~ /^\+/) {
3895 # add assignment operator to the previous line, remove from current line
3896 $fixed[$fixlinenr - 1] .= " $operator";
3897 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3901 # check for && or || at the start of a line
3902 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3904 if (CHK("LOGICAL_CONTINUATIONS",
3905 "Logical continuations should be on the previous line\n" . $hereprev) &&
3906 $fix && $prevrawline =~ /^\+/) {
3907 # insert logical operator at last non-comment, non-whitepsace char on previous line
3908 $prevline =~ /[\s$;]*$/;
3909 my $line_end = substr($prevrawline, $-[0]);
3910 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3911 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3915 # check indentation starts on a tab stop
3916 if ($perl_version_ok &&
3917 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3918 my $indent = length($1);
3919 if ($indent % $tabsize) {
3921 "Statements should start on a tabstop\n" . $herecurr) &&
3923 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3928 # check multi-line statement indentation matches previous line
3929 if ($perl_version_ok &&
3930 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3931 $prevline =~ /^\+(\t*)(.*)$/;
3935 my $pos = pos_last_openparen($rest);
3937 $line =~ /^(\+| )([ \t]*)/;
3940 my $goodtabindent = $oldindent .
3941 "\t" x ($pos / $tabsize) .
3942 " " x ($pos % $tabsize);
3943 my $goodspaceindent = $oldindent . " " x $pos;
3945 if ($newindent ne $goodtabindent &&
3946 $newindent ne $goodspaceindent) {
3948 if (CHK("PARENTHESIS_ALIGNMENT",
3949 "Alignment should match open parenthesis\n" . $hereprev) &&
3950 $fix && $line =~ /^\+/) {
3951 $fixed[$fixlinenr] =~
3952 s/^\+[ \t]*/\+$goodtabindent/;
3958 # check for space after cast like "(int) foo" or "(struct foo) bar"
3959 # avoid checking a few false positives:
3960 # "sizeof(<type>)" or "__alignof__(<type>)"
3961 # function pointer declarations like "(*foo)(int) = bar;"
3962 # structure definitions like "(struct foo) { 0 };"
3963 # multiline macros that define functions
3964 # known attributes or the __attribute__ keyword
3965 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3966 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3968 "No space is necessary after a cast\n" . $herecurr) &&
3970 $fixed[$fixlinenr] =~
3971 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3975 # Block comment styles
3976 # Networking with an initial /*
3977 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3978 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3979 $rawline =~ /^\+[ \t]*\*/ &&
3980 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3981 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3982 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3985 # Block comments use * on subsequent lines
3986 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3987 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3988 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3989 $rawline =~ /^\+/ && #line is new
3990 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3991 WARN("BLOCK_COMMENT_STYLE",
3992 "Block comments use * on subsequent lines\n" . $hereprev);
3995 # Block comments use */ on trailing lines
3996 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3997 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3998 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3999 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
4000 WARN("BLOCK_COMMENT_STYLE",
4001 "Block comments use a trailing */ on a separate line\n" . $herecurr);
4004 # Block comment * alignment
4005 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4006 $line =~ /^\+[ \t]*$;/ && #leading comment
4007 $rawline =~ /^\+[ \t]*\*/ && #leading *
4008 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
4009 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
4010 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4012 $prevrawline =~ m@^\+([ \t]*/?)\*@;
4014 $oldindent = expand_tabs($1);
4016 $prevrawline =~ m@^\+(.*/?)\*@;
4017 $oldindent = expand_tabs($1);
4019 $rawline =~ m@^\+([ \t]*)\*@;
4021 $newindent = expand_tabs($newindent);
4022 if (length($oldindent) ne length($newindent)) {
4023 WARN("BLOCK_COMMENT_STYLE",
4024 "Block comments should align the * on each line\n" . $hereprev);
4028 # check for missing blank lines after struct/union declarations
4029 # with exceptions for various attributes and macros
4030 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4032 !($line =~ /^\+\s*$/ ||
4033 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
4034 $line =~ /^\+\s*MODULE_/i ||
4035 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4036 $line =~ /^\+[a-z_]*init/ ||
4037 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4038 $line =~ /^\+\s*DECLARE/ ||
4039 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4040 $line =~ /^\+\s*__setup/)) {
4041 if (CHK("LINE_SPACING",
4042 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4044 fix_insert_line($fixlinenr, "\+");
4048 # check for multiple consecutive blank lines
4049 if ($prevline =~ /^[\+ ]\s*$/ &&
4050 $line =~ /^\+\s*$/ &&
4051 $last_blank_line != ($linenr - 1)) {
4052 if (CHK("LINE_SPACING",
4053 "Please don't use multiple blank lines\n" . $hereprev) &&
4055 fix_delete_line($fixlinenr, $rawline);
4058 $last_blank_line = $linenr;
4061 # check for missing blank lines after declarations
4062 # (declarations must have the same indentation and not be at the start of line)
4063 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4067 # remove $Attribute/$Sparse uses to simplify comparisons
4068 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4069 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4070 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4071 # function pointer declarations
4072 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4073 # foo bar; where foo is some local typedef or #define
4074 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4075 # known declaration macros
4076 $pl =~ /^\+\s+$declaration_macros/) &&
4077 # for "else if" which can look like "$Ident $Ident"
4078 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4079 # other possible extensions of declaration lines
4080 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4081 # not starting a section or a macro "\" extended line
4082 $pl =~ /(?:\{\s*|\\)$/) &&
4083 # looks like a declaration
4084 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4085 # function pointer declarations
4086 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4087 # foo bar; where foo is some local typedef or #define
4088 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4089 # known declaration macros
4090 $sl =~ /^\+\s+$declaration_macros/ ||
4091 # start of struct or union or enum
4092 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4093 # start or end of block or continuation of declaration
4094 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4095 # bitfield continuation
4096 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4097 # other possible extensions of declaration lines
4098 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4099 if (WARN("LINE_SPACING",
4100 "Missing a blank line after declarations\n" . $hereprev) &&
4102 fix_insert_line($fixlinenr, "\+");
4107 # check for spaces at the beginning of a line.
4109 # 1) within comments
4110 # 2) indented preprocessor commands
4112 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4113 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4114 if (WARN("LEADING_SPACE",
4115 "please, no spaces at the start of a line\n" . $herevet) &&
4117 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4121 # check we are in a valid C source file if not then ignore this hunk
4122 next if ($realfile !~ /\.(h|c)$/);
4124 # check for unusual line ending [ or (
4125 if ($line =~ /^\+.*([\[\(])\s*$/) {
4126 CHK("OPEN_ENDED_LINE",
4127 "Lines should not end with a '$1'\n" . $herecurr);
4130 # check if this appears to be the start function declaration, save the name
4131 if ($sline =~ /^\+\{\s*$/ &&
4132 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4133 $context_function = $1;
4136 # check if this appears to be the end of function declaration
4137 if ($sline =~ /^\+\}\s*$/) {
4138 undef $context_function;
4141 # check indentation of any line with a bare else
4142 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4143 # if the previous line is a break or return and is indented 1 tab more...
4144 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4145 my $tabs = length($1) + 1;
4146 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4147 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4148 defined $lines[$linenr] &&
4149 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4150 WARN("UNNECESSARY_ELSE",
4151 "else is not generally useful after a break or return\n" . $hereprev);
4155 # check indentation of a line with a break;
4156 # if the previous line is a goto, return or break
4157 # and is indented the same # of tabs
4158 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4160 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4161 if (WARN("UNNECESSARY_BREAK",
4162 "break is not useful after a $1\n" . $hereprev) &&
4164 fix_delete_line($fixlinenr, $rawline);
4169 # check for RCS/CVS revision markers
4170 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4172 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4175 # check for old HOTPLUG __dev<foo> section markings
4176 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4177 WARN("HOTPLUG_SECTION",
4178 "Using $1 is unnecessary\n" . $herecurr);
4181 # Check for potential 'bare' types
4182 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4184 #print "LINE<$line>\n";
4185 if ($linenr > $suppress_statement &&
4186 $realcnt && $sline =~ /.\s*\S/) {
4187 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4188 ctx_statement_block($linenr, $realcnt, 0);
4189 $stat =~ s/\n./\n /g;
4190 $cond =~ s/\n./\n /g;
4192 #print "linenr<$linenr> <$stat>\n";
4193 # If this statement has no statement boundaries within
4194 # it there is no point in retrying a statement scan
4195 # until we hit end of it.
4196 my $frag = $stat; $frag =~ s/;+\s*$//;
4197 if ($frag !~ /(?:{|;)/) {
4198 #print "skip<$line_nr_next>\n";
4199 $suppress_statement = $line_nr_next;
4202 # Find the real next line.
4203 $realline_next = $line_nr_next;
4204 if (defined $realline_next &&
4205 (!defined $lines[$realline_next - 1] ||
4206 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4213 # Ignore goto labels.
4214 if ($s =~ /$Ident:\*$/s) {
4216 # Ignore functions being called
4217 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4219 } elsif ($s =~ /^.\s*else\b/s) {
4221 # declarations always start with types
4222 } 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) {
4225 possible($type, "A:" . $s);
4227 # definitions in global scope can only start with types
4228 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4229 possible($1, "B:" . $s);
4232 # any (foo ... *) is a pointer cast, and foo is a type
4233 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4234 possible($1, "C:" . $s);
4237 # Check for any sort of function declaration.
4238 # int foo(something bar, other baz);
4239 # void (*store_gdt)(x86_descr_ptr *);
4240 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4241 my ($name_len) = length($1);
4244 substr($ctx, 0, $name_len + 1, '');
4245 $ctx =~ s/\)[^\)]*$//;
4247 for my $arg (split(/\s*,\s*/, $ctx)) {
4248 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4250 possible($1, "D:" . $s);
4258 # Checks which may be anchored in the context.
4261 # Check for switch () and associated case and default
4262 # statements should be at the same indent.
4263 if ($line=~/\bswitch\s*\(.*\)/) {
4266 my @ctx = ctx_block_outer($linenr, $realcnt);
4268 for my $ctx (@ctx) {
4269 my ($clen, $cindent) = line_stats($ctx);
4270 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4271 $indent != $cindent) {
4272 $err .= "$sep$ctx\n";
4279 ERROR("SWITCH_CASE_INDENT_LEVEL",
4280 "switch and case should be at the same indent\n$hereline$err");
4284 # if/while/etc brace do not go on next line, unless defining a do while loop,
4285 # or if that brace on the next line is for something else
4286 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4287 my $pre_ctx = "$1$2";
4289 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4291 # OpenOCD specific: Begin: replace s/6/10/
4292 if ($line =~ /^\+\t{10,}/) {
4293 # OpenOCD specific: End
4294 WARN("DEEP_INDENTATION",
4295 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4298 my $ctx_cnt = $realcnt - $#ctx - 1;
4299 my $ctx = join("\n", @ctx);
4301 my $ctx_ln = $linenr;
4302 my $ctx_skip = $realcnt;
4304 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4305 defined $lines[$ctx_ln - 1] &&
4306 $lines[$ctx_ln - 1] =~ /^-/)) {
4307 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4308 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4312 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4313 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4315 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4317 "that open brace { should be on the previous line\n" .
4318 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4320 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4321 $ctx =~ /\)\s*\;\s*$/ &&
4322 defined $lines[$ctx_ln - 1])
4324 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4325 if ($nindent > $indent) {
4326 WARN("TRAILING_SEMICOLON",
4327 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4328 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4333 # Check relative indent for conditionals and blocks.
4334 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4335 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4336 ctx_statement_block($linenr, $realcnt, 0)
4337 if (!defined $stat);
4338 my ($s, $c) = ($stat, $cond);
4340 substr($s, 0, length($c), '');
4342 # remove inline comments
4346 # Find out how long the conditional actually is.
4347 my @newlines = ($c =~ /\n/gs);
4348 my $cond_lines = 1 + $#newlines;
4350 # Make sure we remove the line prefixes as we have
4351 # none on the first line, and are going to readd them
4354 while ($s =~ /\n\s+\\\n/) {
4355 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4358 # We want to check the first line inside the block
4359 # starting at the end of the conditional, so remove:
4360 # 1) any blank line termination
4361 # 2) any opening brace { on end of the line
4363 my $continuation = 0;
4365 $s =~ s/^.*\bdo\b//;
4367 if ($s =~ s/^\s*\\//) {
4370 if ($s =~ s/^\s*?\n//) {
4375 # Also ignore a loop construct at the end of a
4376 # preprocessor statement.
4377 if (($prevline =~ /^.\s*#\s*define\s/ ||
4378 $prevline =~ /\\\s*$/) && $continuation == 0) {
4384 while ($cond_ptr != $cond_lines) {
4385 $cond_ptr = $cond_lines;
4387 # If we see an #else/#elif then the code
4389 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4394 # 1) blank lines, they should be at 0,
4395 # 2) preprocessor lines, and
4397 if ($continuation ||
4399 $s =~ /^\s*#\s*?/ ||
4400 $s =~ /^\s*$Ident\s*:/) {
4401 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4402 if ($s =~ s/^.*?\n//) {
4408 my (undef, $sindent) = line_stats("+" . $s);
4409 my $stat_real = raw_line($linenr, $cond_lines);
4411 # Check if either of these lines are modified, else
4412 # this is not this patch's fault.
4413 if (!defined($stat_real) ||
4414 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4417 if (defined($stat_real) && $cond_lines > 1) {
4418 $stat_real = "[...]\n$stat_real";
4421 #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";
4423 if ($check && $s ne '' &&
4424 (($sindent % $tabsize) != 0 ||
4425 ($sindent < $indent) ||
4426 ($sindent == $indent &&
4427 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4428 ($sindent > $indent + $tabsize))) {
4429 WARN("SUSPECT_CODE_INDENT",
4430 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4434 # Track the 'values' across context and added lines.
4435 my $opline = $line; $opline =~ s/^./ /;
4436 my ($curr_values, $curr_vars) =
4437 annotate_values($opline . "\n", $prev_values);
4438 $curr_values = $prev_values . $curr_values;
4440 my $outline = $opline; $outline =~ s/\t/ /g;
4441 print "$linenr > .$outline\n";
4442 print "$linenr > $curr_values\n";
4443 print "$linenr > $curr_vars\n";
4445 $prev_values = substr($curr_values, -1);
4447 #ignore lines not being added
4448 next if ($line =~ /^[^\+]/);
4450 # check for self assignments used to avoid compiler warnings
4451 # e.g.: int foo = foo, *bar = NULL;
4452 # struct foo bar = *(&(bar));
4453 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4455 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4456 WARN("SELF_ASSIGNMENT",
4457 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4461 # check for dereferences that span multiple lines
4462 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4463 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4464 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4466 $line =~ /^.\s*($Lval)/;
4469 WARN("MULTILINE_DEREFERENCE",
4470 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4473 # check for declarations of signed or unsigned without int
4474 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4477 $var = "" if (!defined $var);
4478 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4482 $pointer = "" if (!defined $pointer);
4484 if (WARN("UNSPECIFIED_INT",
4485 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4487 my $decl = trim($sign) . " int ";
4488 my $comp_pointer = $pointer;
4489 $comp_pointer =~ s/\s//g;
4490 $decl .= $comp_pointer;
4491 $decl = rtrim($decl) if ($var eq "");
4492 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4497 # TEST: allow direct testing of the type matcher.
4499 if ($line =~ /^.\s*$Declare\s*$/) {
4501 "TEST: is type\n" . $herecurr);
4502 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4503 ERROR("TEST_NOT_TYPE",
4504 "TEST: is not type ($1 is)\n". $herecurr);
4508 # TEST: allow direct testing of the attribute matcher.
4510 if ($line =~ /^.\s*$Modifier\s*$/) {
4512 "TEST: is attr\n" . $herecurr);
4513 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4514 ERROR("TEST_NOT_ATTR",
4515 "TEST: is not attr ($1 is)\n". $herecurr);
4520 # check for initialisation to aggregates open brace on the next line
4521 if ($line =~ /^.\s*{/ &&
4522 $prevline =~ /(?:^|[^=])=\s*$/) {
4523 if (ERROR("OPEN_BRACE",
4524 "that open brace { should be on the previous line\n" . $hereprev) &&
4525 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4526 fix_delete_line($fixlinenr - 1, $prevrawline);
4527 fix_delete_line($fixlinenr, $rawline);
4528 my $fixedline = $prevrawline;
4529 $fixedline =~ s/\s*=\s*$/ = {/;
4530 fix_insert_line($fixlinenr, $fixedline);
4532 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4533 fix_insert_line($fixlinenr, $fixedline);
4538 # Checks which are anchored on the added line.
4541 # check for malformed paths in #include statements (uses RAW line)
4542 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4544 if ($path =~ m{//}) {
4545 ERROR("MALFORMED_INCLUDE",
4546 "malformed #include filename\n" . $herecurr);
4548 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4549 ERROR("UAPI_INCLUDE",
4550 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4554 # no C99 // comments
4555 if ($line =~ m{//}) {
4556 if (ERROR("C99_COMMENTS",
4557 "do not use C99 // comments\n" . $herecurr) &&
4559 my $line = $fixed[$fixlinenr];
4560 if ($line =~ /\/\/(.*)$/) {
4561 my $comment = trim($1);
4562 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4566 # Remove C99 comments.
4568 $opline =~ s@//.*@@;
4570 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4571 # the whole statement.
4572 #print "APW <$lines[$realline_next - 1]>\n";
4573 if (defined $realline_next &&
4574 exists $lines[$realline_next - 1] &&
4575 !defined $suppress_export{$realline_next} &&
4576 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4577 # Handle definitions which produce identifiers with
4580 # EXPORT_SYMBOL(something_foo);
4582 $name =~ s/^\s*($Ident).*/$1/;
4583 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4584 $name =~ /^${Ident}_$2/) {
4585 #print "FOO C name<$name>\n";
4586 $suppress_export{$realline_next} = 1;
4588 } elsif ($stat !~ /(?:
4590 ^.DEFINE_$Ident\(\Q$name\E\)|
4591 ^.DECLARE_$Ident\(\Q$name\E\)|
4592 ^.LIST_HEAD\(\Q$name\E\)|
4593 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4594 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4596 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4597 $suppress_export{$realline_next} = 2;
4599 $suppress_export{$realline_next} = 1;
4602 if (!defined $suppress_export{$linenr} &&
4603 $prevline =~ /^.\s*$/ &&
4604 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4605 #print "FOO B <$lines[$linenr - 1]>\n";
4606 $suppress_export{$linenr} = 2;
4608 if (defined $suppress_export{$linenr} &&
4609 $suppress_export{$linenr} == 2) {
4610 WARN("EXPORT_SYMBOL",
4611 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4614 # check for global initialisers.
4615 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4616 !exclude_global_initialisers($realfile)) {
4617 if (ERROR("GLOBAL_INITIALISERS",
4618 "do not initialise globals to $1\n" . $herecurr) &&
4620 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4623 # check for static initialisers.
4624 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4625 if (ERROR("INITIALISED_STATIC",
4626 "do not initialise statics to $1\n" .
4629 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4633 # check for misordered declarations of char/short/int/long with signed/unsigned
4634 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4636 WARN("MISORDERED_TYPE",
4637 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4640 # check for unnecessary <signed> int declarations of short/long/long long
4641 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4642 my $type = trim($1);
4643 next if ($type !~ /\bint\b/);
4644 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4645 my $new_type = $type;
4646 $new_type =~ s/\b\s*int\s*\b/ /;
4647 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4648 $new_type =~ s/^const\s+//;
4649 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4650 $new_type = "const $new_type" if ($type =~ /^const\b/);
4651 $new_type =~ s/\s+/ /g;
4652 $new_type = trim($new_type);
4653 if (WARN("UNNECESSARY_INT",
4654 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4656 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4660 # check for static const char * arrays.
4661 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4662 WARN("STATIC_CONST_CHAR_ARRAY",
4663 "static const char * array should probably be static const char * const\n" .
4667 # check for initialized const char arrays that should be static const
4668 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4669 if (WARN("STATIC_CONST_CHAR_ARRAY",
4670 "const array should probably be static const\n" . $herecurr) &&
4672 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4676 # check for static char foo[] = "bar" declarations.
4677 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4678 WARN("STATIC_CONST_CHAR_ARRAY",
4679 "static char array declaration should probably be static const char\n" .
4683 # check for const <foo> const where <foo> is not a pointer or array type
4684 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4686 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4688 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4689 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4691 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4695 # check for const static or static <non ptr type> const declarations
4696 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4697 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4698 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4699 if (WARN("STATIC_CONST",
4700 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4702 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4703 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4707 # check for non-global char *foo[] = {"bar", ...} declarations.
4708 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4709 WARN("STATIC_CONST_CHAR_ARRAY",
4710 "char * array declaration might be better as static const\n" .
4714 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4715 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4717 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4719 if (WARN("ARRAY_SIZE",
4720 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4722 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4727 # check for function declarations without arguments like "int foo()"
4728 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4729 if (ERROR("FUNCTION_WITHOUT_ARGS",
4730 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4732 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4736 # check for new typedefs, only function parameters and sparse annotations
4738 if ($line =~ /\btypedef\s/ &&
4739 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4740 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4741 $line !~ /\b$typeTypedefs\b/ &&
4742 $line !~ /\b__bitwise\b/) {
4743 WARN("NEW_TYPEDEFS",
4744 "do not add new typedefs\n" . $herecurr);
4747 # * goes on variable not on type
4749 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4751 my ($ident, $from, $to) = ($1, $2, $2);
4753 # Should start with a space.
4754 $to =~ s/^(\S)/ $1/;
4755 # Should not end with a space.
4757 # '*'s should not have spaces between.
4758 while ($to =~ s/\*\s+\*/\*\*/) {
4761 ## print "1: from<$from> to<$to> ident<$ident>\n";
4763 if (ERROR("POINTER_LOCATION",
4764 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4766 my $sub_from = $ident;
4767 my $sub_to = $ident;
4768 $sub_to =~ s/\Q$from\E/$to/;
4769 $fixed[$fixlinenr] =~
4770 s@\Q$sub_from\E@$sub_to@;
4774 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4776 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4778 # Should start with a space.
4779 $to =~ s/^(\S)/ $1/;
4780 # Should not end with a space.
4782 # '*'s should not have spaces between.
4783 while ($to =~ s/\*\s+\*/\*\*/) {
4785 # Modifiers should have spaces.
4786 $to =~ s/(\b$Modifier$)/$1 /;
4788 ## print "2: from<$from> to<$to> ident<$ident>\n";
4789 if ($from ne $to && $ident !~ /^$Modifier$/) {
4790 if (ERROR("POINTER_LOCATION",
4791 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4794 my $sub_from = $match;
4795 my $sub_to = $match;
4796 $sub_to =~ s/\Q$from\E/$to/;
4797 $fixed[$fixlinenr] =~
4798 s@\Q$sub_from\E@$sub_to@;
4803 # avoid BUG() or BUG_ON()
4804 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4805 my $msg_level = \&WARN;
4806 $msg_level = \&CHK if ($file);
4807 &{$msg_level}("AVOID_BUG",
4808 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4811 # avoid LINUX_VERSION_CODE
4812 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4813 WARN("LINUX_VERSION_CODE",
4814 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4817 # check for uses of printk_ratelimit
4818 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4819 WARN("PRINTK_RATELIMITED",
4820 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4823 # printk should use KERN_* levels
4824 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4825 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4826 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4829 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4830 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4834 $modifier = "" if (!defined($modifier));
4835 my $level = lc($orig);
4836 $level = "warn" if ($level eq "warning");
4837 my $level2 = $level;
4838 $level2 = "dbg" if ($level eq "debug");
4839 $level .= $modifier;
4840 $level2 .= $modifier;
4841 WARN("PREFER_PR_LEVEL",
4842 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4845 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4846 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4848 my $level = lc($orig);
4849 $level = "warn" if ($level eq "warning");
4850 $level = "dbg" if ($level eq "debug");
4851 WARN("PREFER_DEV_LEVEL",
4852 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4855 # trace_printk should not be used in production code.
4856 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4857 WARN("TRACE_PRINTK",
4858 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4861 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4862 # number of false positives, but assembly files are not checked, so at
4863 # least the arch entry code will not trigger this warning.
4864 if ($line =~ /\bENOSYS\b/) {
4866 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4869 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4870 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4871 # Similarly to ENOSYS warning a small number of false positives is expected.
4872 if (!$file && $line =~ /\bENOTSUPP\b/) {
4873 if (WARN("ENOTSUPP",
4874 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4876 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4880 # function brace can't be on same line, except for #defines of do while,
4881 # or if closed on same line
4882 if ($perl_version_ok &&
4883 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4884 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4886 if (ERROR("OPEN_BRACE",
4887 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4889 fix_delete_line($fixlinenr, $rawline);
4890 my $fixed_line = $rawline;
4891 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4894 fix_insert_line($fixlinenr, ltrim($line1));
4895 fix_insert_line($fixlinenr, "\+{");
4896 if ($line2 !~ /^\s*$/) {
4897 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4902 # open braces for enum, union and struct go on the same line.
4903 if ($line =~ /^.\s*{/ &&
4904 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4905 if (ERROR("OPEN_BRACE",
4906 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4907 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4908 fix_delete_line($fixlinenr - 1, $prevrawline);
4909 fix_delete_line($fixlinenr, $rawline);
4910 my $fixedline = rtrim($prevrawline) . " {";
4911 fix_insert_line($fixlinenr, $fixedline);
4912 $fixedline = $rawline;
4913 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4914 if ($fixedline !~ /^\+\s*$/) {
4915 fix_insert_line($fixlinenr, $fixedline);
4920 # missing space after union, struct or enum definition
4921 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4923 "missing space after $1 definition\n" . $herecurr) &&
4925 $fixed[$fixlinenr] =~
4926 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4930 # Function pointer declarations
4931 # check spacing between type, funcptr, and args
4932 # canonical declaration is "type (*funcptr)(args...)"
4933 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4935 my $pre_pointer_space = $2;
4936 my $post_pointer_space = $3;
4938 my $post_funcname_space = $5;
4939 my $pre_args_space = $6;
4941 # the $Declare variable will capture all spaces after the type
4942 # so check it for a missing trailing missing space but pointer return types
4943 # don't need a space so don't warn for those.
4944 my $post_declare_space = "";
4945 if ($declare =~ /(\s+)$/) {
4946 $post_declare_space = $1;
4947 $declare = rtrim($declare);
4949 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4951 "missing space after return type\n" . $herecurr);
4952 $post_declare_space = " ";
4955 # unnecessary space "type (*funcptr)(args...)"
4956 # This test is not currently implemented because these declarations are
4958 # int foo(int bar, ...)
4959 # and this is form shouldn't/doesn't generate a checkpatch warning.
4961 # elsif ($declare =~ /\s{2,}$/) {
4963 # "Multiple spaces after return type\n" . $herecurr);
4966 # unnecessary space "type ( *funcptr)(args...)"
4967 if (defined $pre_pointer_space &&
4968 $pre_pointer_space =~ /^\s/) {
4970 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4973 # unnecessary space "type (* funcptr)(args...)"
4974 if (defined $post_pointer_space &&
4975 $post_pointer_space =~ /^\s/) {
4977 "Unnecessary space before function pointer name\n" . $herecurr);
4980 # unnecessary space "type (*funcptr )(args...)"
4981 if (defined $post_funcname_space &&
4982 $post_funcname_space =~ /^\s/) {
4984 "Unnecessary space after function pointer name\n" . $herecurr);
4987 # unnecessary space "type (*funcptr) (args...)"
4988 if (defined $pre_args_space &&
4989 $pre_args_space =~ /^\s/) {
4991 "Unnecessary space before function pointer arguments\n" . $herecurr);
4994 if (show_type("SPACING") && $fix) {
4995 $fixed[$fixlinenr] =~
4996 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5000 # check for spacing round square brackets; allowed:
5001 # 1. with a type on the left -- int [] a;
5002 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5003 # 3. inside a curly brace -- = { [0...10] = 5 }
5004 while ($line =~ /(.*?\s)\[/g) {
5005 my ($where, $prefix) = ($-[1], $1);
5006 if ($prefix !~ /$Type\s+$/ &&
5007 ($where != 0 || $prefix !~ /^.\s+$/) &&
5008 $prefix !~ /[{,:]\s+$/) {
5009 if (ERROR("BRACKET_SPACE",
5010 "space prohibited before open square bracket '['\n" . $herecurr) &&
5012 $fixed[$fixlinenr] =~
5013 s/^(\+.*?)\s+\[/$1\[/;
5018 # check for spaces between functions and their parentheses.
5019 while ($line =~ /($Ident)\s+\(/g) {
5021 my $ctx_before = substr($line, 0, $-[1]);
5022 my $ctx = "$ctx_before$name";
5024 # Ignore those directives where spaces _are_ permitted.
5026 if|for|while|switch|return|case|
5027 volatile|__volatile__|
5028 __attribute__|format|__extension__|
5031 # cpp #define statements have non-optional spaces, ie
5032 # if there is a space between the name and the open
5033 # parenthesis it is simply not a parameter group.
5034 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5036 # cpp #elif statement condition may start with a (
5037 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5039 # If this whole things ends with a type its most
5040 # likely a typedef for a function.
5041 } elsif ($ctx =~ /$Type$/) {
5045 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5047 $fixed[$fixlinenr] =~
5048 s/\b$name\s+\(/$name\(/;
5053 # Check operator spacing.
5054 if (!($line=~/\#\s*include/)) {
5055 my $fixed_line = "";
5059 <<=|>>=|<=|>=|==|!=|
5060 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5061 =>|->|<<|>>|<|>|=|!|~|
5062 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5065 my @elements = split(/($ops|;)/, $opline);
5067 ## print("element count: <" . $#elements . ">\n");
5068 ## foreach my $el (@elements) {
5069 ## print("el: <$el>\n");
5072 my @fix_elements = ();
5075 foreach my $el (@elements) {
5076 push(@fix_elements, substr($rawline, $off, length($el)));
5077 $off += length($el);
5082 my $blank = copy_spacing($opline);
5083 my $last_after = -1;
5085 for (my $n = 0; $n < $#elements; $n += 2) {
5087 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5089 ## print("n: <$n> good: <$good>\n");
5091 $off += length($elements[$n]);
5093 # Pick up the preceding and succeeding characters.
5094 my $ca = substr($opline, 0, $off);
5096 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5097 $cc = substr($opline, $off + length($elements[$n + 1]));
5099 my $cb = "$ca$;$cc";
5102 $a = 'V' if ($elements[$n] ne '');
5103 $a = 'W' if ($elements[$n] =~ /\s$/);
5104 $a = 'C' if ($elements[$n] =~ /$;$/);
5105 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5106 $a = 'O' if ($elements[$n] eq '');
5107 $a = 'E' if ($ca =~ /^\s*$/);
5109 my $op = $elements[$n + 1];
5112 if (defined $elements[$n + 2]) {
5113 $c = 'V' if ($elements[$n + 2] ne '');
5114 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5115 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5116 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5117 $c = 'O' if ($elements[$n + 2] eq '');
5118 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5123 my $ctx = "${a}x${c}";
5125 my $at = "(ctx:$ctx)";
5127 my $ptr = substr($blank, 0, $off) . "^";
5128 my $hereptr = "$hereline$ptr\n";
5130 # Pull out the value of this operator.
5131 my $op_type = substr($curr_values, $off + 1, 1);
5133 # Get the full operator variant.
5134 my $opv = $op . substr($curr_vars, $off, 1);
5136 # Ignore operators passed as parameters.
5137 if ($op_type ne 'V' &&
5138 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5141 # } elsif ($op =~ /^$;+$/) {
5143 # ; should have either the end of line or a space or \ after it
5144 } elsif ($op eq ';') {
5145 if ($ctx !~ /.x[WEBC]/ &&
5146 $cc !~ /^\\/ && $cc !~ /^;/) {
5147 if (ERROR("SPACING",
5148 "space required after that '$op' $at\n" . $hereptr)) {
5149 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5155 } elsif ($op eq '//') {
5157 # : when part of a bitfield
5158 } elsif ($opv eq ':B') {
5159 # skip the bitfield test for now
5163 } elsif ($op eq '->') {
5164 if ($ctx =~ /Wx.|.xW/) {
5165 if (ERROR("SPACING",
5166 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5167 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5168 if (defined $fix_elements[$n + 2]) {
5169 $fix_elements[$n + 2] =~ s/^\s+//;
5175 # , must not have a space before and must have a space on the right.
5176 } elsif ($op eq ',') {
5177 my $rtrim_before = 0;
5178 my $space_after = 0;
5179 if ($ctx =~ /Wx./) {
5180 if (ERROR("SPACING",
5181 "space prohibited before that '$op' $at\n" . $hereptr)) {
5186 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5187 if (ERROR("SPACING",
5188 "space required after that '$op' $at\n" . $hereptr)) {
5194 if ($rtrim_before || $space_after) {
5195 if ($rtrim_before) {
5196 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5198 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5205 # '*' as part of a type definition -- reported already.
5206 } elsif ($opv eq '*_') {
5207 #warn "'*' is part of type\n";
5209 # unary operators should have a space before and
5210 # none after. May be left adjacent to another
5211 # unary operator, or a cast
5212 } elsif ($op eq '!' || $op eq '~' ||
5213 $opv eq '*U' || $opv eq '-U' ||
5214 $opv eq '&U' || $opv eq '&&U') {
5215 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5216 if (ERROR("SPACING",
5217 "space required before that '$op' $at\n" . $hereptr)) {
5218 if ($n != $last_after + 2) {
5219 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5224 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5225 # A unary '*' may be const
5227 } elsif ($ctx =~ /.xW/) {
5228 if (ERROR("SPACING",
5229 "space prohibited after that '$op' $at\n" . $hereptr)) {
5230 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5231 if (defined $fix_elements[$n + 2]) {
5232 $fix_elements[$n + 2] =~ s/^\s+//;
5238 # unary ++ and unary -- are allowed no space on one side.
5239 } elsif ($op eq '++' or $op eq '--') {
5240 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5241 if (ERROR("SPACING",
5242 "space required one side of that '$op' $at\n" . $hereptr)) {
5243 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5247 if ($ctx =~ /Wx[BE]/ ||
5248 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5249 if (ERROR("SPACING",
5250 "space prohibited before that '$op' $at\n" . $hereptr)) {
5251 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5255 if ($ctx =~ /ExW/) {
5256 if (ERROR("SPACING",
5257 "space prohibited after that '$op' $at\n" . $hereptr)) {
5258 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5259 if (defined $fix_elements[$n + 2]) {
5260 $fix_elements[$n + 2] =~ s/^\s+//;
5266 # << and >> may either have or not have spaces both sides
5267 } elsif ($op eq '<<' or $op eq '>>' or
5268 $op eq '&' or $op eq '^' or $op eq '|' or
5269 $op eq '+' or $op eq '-' or
5270 $op eq '*' or $op eq '/' or
5274 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5276 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5277 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5278 $fix_elements[$n + 2] =~ s/^\s+//;
5281 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5283 "space preferred before that '$op' $at\n" . $hereptr)) {
5284 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5288 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5289 if (ERROR("SPACING",
5290 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5291 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5292 if (defined $fix_elements[$n + 2]) {
5293 $fix_elements[$n + 2] =~ s/^\s+//;
5299 # A colon needs no spaces before when it is
5300 # terminating a case value or a label.
5301 } elsif ($opv eq ':C' || $opv eq ':L') {
5302 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5303 if (ERROR("SPACING",
5304 "space prohibited before that '$op' $at\n" . $hereptr)) {
5305 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5310 # All the others need spaces both sides.
5311 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5314 # Ignore email addresses <foo@bar>
5316 $cc =~ /^\S+\@\S+>/) ||
5318 $ca =~ /<\S+\@\S+$/))
5323 # for asm volatile statements
5324 # ignore a colon with another
5325 # colon immediately before or after
5327 ($ca =~ /:$/ || $cc =~ /^:/)) {
5331 # messages are ERROR, but ?: are CHK
5333 my $msg_level = \&ERROR;
5334 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5336 if (&{$msg_level}("SPACING",
5337 "spaces required around that '$op' $at\n" . $hereptr)) {
5338 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5339 if (defined $fix_elements[$n + 2]) {
5340 $fix_elements[$n + 2] =~ s/^\s+//;
5346 $off += length($elements[$n + 1]);
5348 ## print("n: <$n> GOOD: <$good>\n");
5350 $fixed_line = $fixed_line . $good;
5353 if (($#elements % 2) == 0) {
5354 $fixed_line = $fixed_line . $fix_elements[$#elements];
5357 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5358 $fixed[$fixlinenr] = $fixed_line;
5364 # check for whitespace before a non-naked semicolon
5365 if ($line =~ /^\+.*\S\s+;\s*$/) {
5367 "space prohibited before semicolon\n" . $herecurr) &&
5369 1 while $fixed[$fixlinenr] =~
5370 s/^(\+.*\S)\s+;/$1;/;
5374 # check for multiple assignments
5375 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5376 CHK("MULTIPLE_ASSIGNMENTS",
5377 "multiple assignments should be avoided\n" . $herecurr);
5380 ## # check for multiple declarations, allowing for a function declaration
5382 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5383 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5385 ## # Remove any bracketed sections to ensure we do not
5386 ## # falsely report the parameters of functions.
5388 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5390 ## if ($ln =~ /,/) {
5391 ## WARN("MULTIPLE_DECLARATION",
5392 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5396 #need space before brace following if, while, etc
5397 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5398 $line =~ /\b(?:else|do)\{/) {
5399 if (ERROR("SPACING",
5400 "space required before the open brace '{'\n" . $herecurr) &&
5402 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5406 ## # check for blank lines before declarations
5407 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5408 ## $prevrawline =~ /^.\s*$/) {
5410 ## "No blank lines before declarations\n" . $hereprev);
5414 # closing brace should have a space following it when it has anything
5416 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5417 if (ERROR("SPACING",
5418 "space required after that close brace '}'\n" . $herecurr) &&
5420 $fixed[$fixlinenr] =~
5421 s/}((?!(?:,|;|\)))\S)/} $1/;
5425 # check spacing on square brackets
5426 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5427 if (ERROR("SPACING",
5428 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5430 $fixed[$fixlinenr] =~
5434 if ($line =~ /\s\]/) {
5435 if (ERROR("SPACING",
5436 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5438 $fixed[$fixlinenr] =~
5443 # check spacing on parentheses
5444 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5445 $line !~ /for\s*\(\s+;/) {
5446 if (ERROR("SPACING",
5447 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5449 $fixed[$fixlinenr] =~
5453 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5454 $line !~ /for\s*\(.*;\s+\)/ &&
5455 $line !~ /:\s+\)/) {
5456 if (ERROR("SPACING",
5457 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5459 $fixed[$fixlinenr] =~
5464 # check unnecessary parentheses around addressof/dereference single $Lvals
5465 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5467 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5469 if (CHK("UNNECESSARY_PARENTHESES",
5470 "Unnecessary parentheses around $var\n" . $herecurr) &&
5472 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5476 # check for unnecessary parentheses around function pointer uses
5477 # ie: (foo->bar)(); should be foo->bar();
5478 # but not "if (foo->bar) (" to avoid some false positives
5479 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5481 if (CHK("UNNECESSARY_PARENTHESES",
5482 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5484 my $var2 = deparenthesize($var);
5486 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5490 # check for unnecessary parentheses around comparisons in if uses
5491 # when !drivers/staging or command-line uses --strict
5492 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5493 $perl_version_ok && defined($stat) &&
5494 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5496 my $test = substr($2, 1, -1);
5498 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5500 # avoid parentheses around potential macro args
5501 next if ($match =~ /^\s*\w+\s*$/);
5502 if (!defined($herectx)) {
5503 $herectx = $here . "\n";
5504 my $cnt = statement_rawlines($if_stat);
5505 for (my $n = 0; $n < $cnt; $n++) {
5506 my $rl = raw_line($linenr, $n);
5507 $herectx .= $rl . "\n";
5508 last if $rl =~ /^[ \+].*\{/;
5511 CHK("UNNECESSARY_PARENTHESES",
5512 "Unnecessary parentheses around '$match'\n" . $herectx);
5516 # check that goto labels aren't indented (allow a single space indentation)
5517 # and ignore bitfield definitions like foo:1
5518 # Strictly, labels can have whitespace after the identifier and before the :
5519 # but this is not allowed here as many ?: uses would appear to be labels
5520 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5521 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5522 $sline !~ /^.\s+default:/) {
5523 if (WARN("INDENTED_LABEL",
5524 "labels should not be indented\n" . $herecurr) &&
5526 $fixed[$fixlinenr] =~
5531 # check if a statement with a comma should be two statements like:
5532 # foo = bar(), /* comma should be semicolon */
5534 if (defined($stat) &&
5535 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5536 my $cnt = statement_rawlines($stat);
5537 my $herectx = get_stat_here($linenr, $cnt, $here);
5538 WARN("SUSPECT_COMMA_SEMICOLON",
5539 "Possible comma where semicolon could be used\n" . $herectx);
5542 # return is not a function
5543 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5545 if ($perl_version_ok &&
5546 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5548 $value = deparenthesize($value);
5549 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5550 ERROR("RETURN_PARENTHESES",
5551 "return is not a function, parentheses are not required\n" . $herecurr);
5553 } elsif ($spacing !~ /\s+/) {
5555 "space required before the open parenthesis '('\n" . $herecurr);
5559 # unnecessary return in a void function
5560 # at end-of-function, with the previous line a single leading tab, then return;
5561 # and the line before that not a goto label target like "out:"
5562 if ($sline =~ /^[ \+]}\s*$/ &&
5563 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5565 $lines[$linenr - 3] =~ /^[ +]/ &&
5566 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5568 "void function return statements are not generally useful\n" . $hereprev);
5571 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5572 if ($perl_version_ok &&
5573 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5574 my $openparens = $1;
5575 my $count = $openparens =~ tr@\(@\(@;
5577 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5578 my $comp = $4; #Not $1 because of $LvalOrFunc
5579 $msg = " - maybe == should be = ?" if ($comp eq "==");
5580 WARN("UNNECESSARY_PARENTHESES",
5581 "Unnecessary parentheses$msg\n" . $herecurr);
5585 # comparisons with a constant or upper case identifier on the left
5586 # avoid cases like "foo + BAR < baz"
5587 # only fix matches surrounded by parentheses to avoid incorrect
5588 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5589 if ($perl_version_ok &&
5590 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5595 my $newcomp = $comp;
5596 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5597 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5598 WARN("CONSTANT_COMPARISON",
5599 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5603 } elsif ($comp eq "<=") {
5605 } elsif ($comp eq ">") {
5607 } elsif ($comp eq ">=") {
5610 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5614 # Return of what appears to be an errno should normally be negative
5615 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5617 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5618 WARN("USE_NEGATIVE_ERRNO",
5619 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5623 # Need a space before open parenthesis after if, while etc
5624 if ($line =~ /\b(if|while|for|switch)\(/) {
5625 if (ERROR("SPACING",
5626 "space required before the open parenthesis '('\n" . $herecurr) &&
5628 $fixed[$fixlinenr] =~
5629 s/\b(if|while|for|switch)\(/$1 \(/;
5633 # Check for illegal assignment in if conditional -- and check for trailing
5634 # statements after the conditional.
5635 if ($line =~ /do\s*(?!{)/) {
5636 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5637 ctx_statement_block($linenr, $realcnt, 0)
5638 if (!defined $stat);
5639 my ($stat_next) = ctx_statement_block($line_nr_next,
5640 $remain_next, $off_next);
5641 $stat_next =~ s/\n./\n /g;
5642 ##print "stat<$stat> stat_next<$stat_next>\n";
5644 if ($stat_next =~ /^\s*while\b/) {
5645 # If the statement carries leading newlines,
5646 # then count those as offsets.
5648 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5650 statement_rawlines($whitespace) - 1;
5652 $suppress_whiletrailers{$line_nr_next +
5656 if (!defined $suppress_whiletrailers{$linenr} &&
5657 defined($stat) && defined($cond) &&
5658 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5659 my ($s, $c) = ($stat, $cond);
5660 my $fixed_assign_in_if = 0;
5662 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5663 if (ERROR("ASSIGN_IN_IF",
5664 "do not use assignment in if condition\n" . $herecurr) &&
5665 $fix && $perl_version_ok) {
5666 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5674 fix_delete_line($fixlinenr, $rawline);
5675 fix_insert_line($fixlinenr, "$space$statement;");
5676 my $newline = "${space}if (";
5677 $newline .= '!' if defined($not);
5678 $newline .= '(' if (defined $not && defined($test) && defined($against));
5679 $newline .= "$assigned";
5680 $newline .= " $test $against" if (defined($test) && defined($against));
5681 $newline .= ')' if (defined $not && defined($test) && defined($against));
5683 $newline .= " {" if (defined($brace));
5684 fix_insert_line($fixlinenr + 1, $newline);
5685 $fixed_assign_in_if = 1;
5690 # Find out what is on the end of the line after the
5692 substr($s, 0, length($c), '');
5694 $s =~ s/$;//g; # Remove any comments
5695 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5696 $c !~ /}\s*while\s*/)
5698 # Find out how long the conditional actually is.
5699 my @newlines = ($c =~ /\n/gs);
5700 my $cond_lines = 1 + $#newlines;
5703 $stat_real = raw_line($linenr, $cond_lines)
5704 . "\n" if ($cond_lines);
5705 if (defined($stat_real) && $cond_lines > 1) {
5706 $stat_real = "[...]\n$stat_real";
5709 if (ERROR("TRAILING_STATEMENTS",
5710 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5711 !$fixed_assign_in_if &&
5713 $fix && $perl_version_ok &&
5714 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5717 my $rest = rtrim($4);
5718 if ($rest =~ /;$/) {
5719 $fixed[$fixlinenr] = "\+$indent$test";
5720 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5726 # Check for bitwise tests written as boolean
5738 WARN("HEXADECIMAL_BOOLEAN_TEST",
5739 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5742 # if and else should not have general statements after it
5743 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5745 $s =~ s/$;//g; # Remove any comments
5746 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5747 ERROR("TRAILING_STATEMENTS",
5748 "trailing statements should be on next line\n" . $herecurr);
5751 # if should not continue a brace
5752 if ($line =~ /}\s*if\b/) {
5753 ERROR("TRAILING_STATEMENTS",
5754 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5757 # case and default should not have general statements after them
5758 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5760 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5764 ERROR("TRAILING_STATEMENTS",
5765 "trailing statements should be on next line\n" . $herecurr);
5768 # Check for }<nl>else {, these must be at the same
5769 # indent level to be relevant to each other.
5770 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5771 $previndent == $indent) {
5772 if (ERROR("ELSE_AFTER_BRACE",
5773 "else should follow close brace '}'\n" . $hereprev) &&
5774 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5775 fix_delete_line($fixlinenr - 1, $prevrawline);
5776 fix_delete_line($fixlinenr, $rawline);
5777 my $fixedline = $prevrawline;
5778 $fixedline =~ s/}\s*$//;
5779 if ($fixedline !~ /^\+\s*$/) {
5780 fix_insert_line($fixlinenr, $fixedline);
5782 $fixedline = $rawline;
5783 $fixedline =~ s/^(.\s*)else/$1} else/;
5784 fix_insert_line($fixlinenr, $fixedline);
5788 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5789 $previndent == $indent) {
5790 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5792 # Find out what is on the end of the line after the
5794 substr($s, 0, length($c), '');
5797 if ($s =~ /^\s*;/) {
5798 if (ERROR("WHILE_AFTER_BRACE",
5799 "while should follow close brace '}'\n" . $hereprev) &&
5800 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5801 fix_delete_line($fixlinenr - 1, $prevrawline);
5802 fix_delete_line($fixlinenr, $rawline);
5803 my $fixedline = $prevrawline;
5804 my $trailing = $rawline;
5805 $trailing =~ s/^\+//;
5806 $trailing = trim($trailing);
5807 $fixedline =~ s/}\s*$/} $trailing/;
5808 fix_insert_line($fixlinenr, $fixedline);
5813 #Specific variable tests
5814 while ($line =~ m{($Constant|$Lval)}g) {
5819 if ($var !~ /^$Constant$/ &&
5820 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5821 #Ignore some autogenerated defines and enum values
5822 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5823 #Ignore Page<foo> variants
5824 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5825 #Ignore SI style variants like nS, mV and dB
5826 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5827 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5828 #Ignore some three character SI units explicitly, like MiB and KHz
5829 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5832 # OpenOCD Specific: Begin: remove Linux exceptions, extend to camel[0-9_]*CASE
5833 if ($var !~ /^$Constant$/ &&
5834 $var =~ /[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z]/) {
5835 # OpenOCD Specific: End
5836 while ($var =~ m{\b($Ident)}g) {
5839 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5841 # OpenOCD Specific: Begin: extend to camel[0-9_]*CASE
5842 next if ($word !~ /[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z]/);
5843 # OpenOCD Specific: End
5845 # This will not work for OpenOCD jenkins because it runs
5846 # checkpatch from a tree already patched. Any new camelcase
5847 # in include file will be ignored as it was pre-existing.
5849 seed_camelcase_includes();
5850 if (!$file && !$camelcase_file_seeded) {
5851 seed_camelcase_file($realfile);
5852 $camelcase_file_seeded = 1;
5856 if (!defined $camelcase{$word}) {
5857 $camelcase{$word} = 1;
5859 "Avoid CamelCase: <$word>\n" . $herecurr);
5865 #no spaces allowed after \ in define
5866 if ($line =~ /\#\s*define.*\\\s+$/) {
5867 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5868 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5870 $fixed[$fixlinenr] =~ s/\s+$//;
5874 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5875 # itself <asm/foo.h> (uses RAW line)
5876 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5878 my $checkfile = "include/linux/$file";
5879 if (-f "$root/$checkfile" &&
5880 $realfile ne $checkfile &&
5881 $1 !~ /$allowed_asm_includes/)
5883 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5884 if ($asminclude > 0) {
5885 if ($realfile =~ m{^arch/}) {
5886 CHK("ARCH_INCLUDE_LINUX",
5887 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5889 WARN("INCLUDE_LINUX",
5890 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5896 # multi-statement macros should be enclosed in a do while loop, grab the
5897 # first statement and ensure its the whole macro if its not enclosed
5898 # in a known good container
5899 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5900 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5903 my ($off, $dstat, $dcond, $rest);
5905 my $has_flow_statement = 0;
5906 my $has_arg_concat = 0;
5907 ($dstat, $dcond, $ln, $cnt, $off) =
5908 ctx_statement_block($linenr, $realcnt, 0);
5910 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5911 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5913 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5914 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5916 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5917 my $define_args = $1;
5918 my $define_stmt = $dstat;
5921 if (defined $define_args && $define_args ne "") {
5922 $define_args = substr($define_args, 1, length($define_args) - 2);
5923 $define_args =~ s/\s*//g;
5924 $define_args =~ s/\\\+?//g;
5925 @def_args = split(",", $define_args);
5929 $dstat =~ s/\\\n.//g;
5930 $dstat =~ s/^\s*//s;
5931 $dstat =~ s/\s*$//s;
5933 # Flatten any parentheses and braces
5934 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5935 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5936 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5940 # Flatten any obvious string concatenation.
5941 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5942 $dstat =~ s/$Ident\s*($String)/$1/)
5946 # Make asm volatile uses seem like a generic function
5947 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5949 my $exceptions = qr{
5962 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5965 my $stmt_cnt = statement_rawlines($ctx);
5966 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5969 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5970 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5971 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5972 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5973 $dstat !~ /$exceptions/ &&
5974 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5975 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5976 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5977 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5978 $dstat !~ /^for\s*$Constant$/ && # for (...)
5979 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5980 $dstat !~ /^do\s*{/ && # do {...
5981 $dstat !~ /^\(\{/ && # ({...
5982 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5984 if ($dstat =~ /^\s*if\b/) {
5985 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5986 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5987 } elsif ($dstat =~ /;/) {
5988 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5989 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5991 ERROR("COMPLEX_MACRO",
5992 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5997 # Make $define_stmt single line, comment-free, etc
5998 my @stmt_array = split('\n', $define_stmt);
6001 foreach my $l (@stmt_array) {
6006 } elsif ($l =~ /^[\+ ]/) {
6007 $define_stmt .= substr($l, 1);
6010 $define_stmt =~ s/$;//g;
6011 $define_stmt =~ s/\s+/ /g;
6012 $define_stmt = trim($define_stmt);
6014 # check if any macro arguments are reused (ignore '...' and 'type')
6015 foreach my $arg (@def_args) {
6016 next if ($arg =~ /\.\.\./);
6017 next if ($arg =~ /^type$/i);
6018 my $tmp_stmt = $define_stmt;
6019 $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;
6020 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6021 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
6022 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6024 CHK("MACRO_ARG_REUSE",
6025 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6027 # check if any macro arguments may have other precedence issues
6028 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6029 ((defined($1) && $1 ne ',') ||
6030 (defined($2) && $2 ne ','))) {
6031 CHK("MACRO_ARG_PRECEDENCE",
6032 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6036 # check for macros with flow control, but without ## concatenation
6037 # ## concatenation is commonly a macro that defines a function so ignore those
6038 if ($has_flow_statement && !$has_arg_concat) {
6039 my $cnt = statement_rawlines($ctx);
6040 my $herectx = get_stat_here($linenr, $cnt, $here);
6042 WARN("MACRO_WITH_FLOW_CONTROL",
6043 "Macros with flow control statements should be avoided\n" . "$herectx");
6046 # check for line continuations outside of #defines, preprocessor #, and asm
6049 if ($prevline !~ /^..*\\$/ &&
6050 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6051 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
6052 $line =~ /^\+.*\\$/) {
6053 WARN("LINE_CONTINUATIONS",
6054 "Avoid unnecessary line continuations\n" . $herecurr);
6058 # do {} while (0) macro tests:
6059 # single-statement macros do not need to be enclosed in do while (0) loop,
6060 # macro should not end with a semicolon
6061 if ($perl_version_ok &&
6062 $realfile !~ m@/vmlinux.lds.h$@ &&
6063 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6066 my ($off, $dstat, $dcond, $rest);
6068 ($dstat, $dcond, $ln, $cnt, $off) =
6069 ctx_statement_block($linenr, $realcnt, 0);
6072 $dstat =~ s/\\\n.//g;
6075 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6080 my $cnt = statement_rawlines($ctx);
6081 my $herectx = get_stat_here($linenr, $cnt, $here);
6083 if (($stmts =~ tr/;/;/) == 1 &&
6084 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6085 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6086 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6088 if (defined $semis && $semis ne "") {
6089 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6090 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6092 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6094 my $cnt = statement_rawlines($ctx);
6095 my $herectx = get_stat_here($linenr, $cnt, $here);
6097 WARN("TRAILING_SEMICOLON",
6098 "macros should not use a trailing semicolon\n" . "$herectx");
6102 # check for redundant bracing round if etc
6103 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6104 my ($level, $endln, @chunks) =
6105 ctx_statement_full($linenr, $realcnt, 1);
6106 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6107 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6108 if ($#chunks > 0 && $level == 0) {
6112 my $herectx = $here . "\n";
6113 my $ln = $linenr - 1;
6114 for my $chunk (@chunks) {
6115 my ($cond, $block) = @{$chunk};
6117 # If the condition carries leading newlines, then count those as offsets.
6118 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6119 my $offset = statement_rawlines($whitespace) - 1;
6121 $allowed[$allow] = 0;
6122 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6124 # We have looked at and allowed this specific line.
6125 $suppress_ifbraces{$ln + $offset} = 1;
6127 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6128 $ln += statement_rawlines($block) - 1;
6130 substr($block, 0, length($cond), '');
6132 $seen++ if ($block =~ /^\s*{/);
6134 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6135 if (statement_lines($cond) > 1) {
6136 #print "APW: ALLOWED: cond<$cond>\n";
6137 $allowed[$allow] = 1;
6139 if ($block =~/\b(?:if|for|while)\b/) {
6140 #print "APW: ALLOWED: block<$block>\n";
6141 $allowed[$allow] = 1;
6143 if (statement_block_size($block) > 1) {
6144 #print "APW: ALLOWED: lines block<$block>\n";
6145 $allowed[$allow] = 1;
6150 my $sum_allowed = 0;
6151 foreach (@allowed) {
6154 if ($sum_allowed == 0) {
6156 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6157 } elsif ($sum_allowed != $allow &&
6160 "braces {} should be used on all arms of this statement\n" . $herectx);
6165 if (!defined $suppress_ifbraces{$linenr - 1} &&
6166 $line =~ /\b(if|while|for|else)\b/) {
6169 # Check the pre-context.
6170 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6171 #print "APW: ALLOWED: pre<$1>\n";
6175 my ($level, $endln, @chunks) =
6176 ctx_statement_full($linenr, $realcnt, $-[0]);
6178 # Check the condition.
6179 my ($cond, $block) = @{$chunks[0]};
6180 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6181 if (defined $cond) {
6182 substr($block, 0, length($cond), '');
6184 if (statement_lines($cond) > 1) {
6185 #print "APW: ALLOWED: cond<$cond>\n";
6188 if ($block =~/\b(?:if|for|while)\b/) {
6189 #print "APW: ALLOWED: block<$block>\n";
6192 if (statement_block_size($block) > 1) {
6193 #print "APW: ALLOWED: lines block<$block>\n";
6196 # Check the post-context.
6197 if (defined $chunks[1]) {
6198 my ($cond, $block) = @{$chunks[1]};
6199 if (defined $cond) {
6200 substr($block, 0, length($cond), '');
6202 if ($block =~ /^\s*\{/) {
6203 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6207 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6208 my $cnt = statement_rawlines($block);
6209 my $herectx = get_stat_here($linenr, $cnt, $here);
6212 "braces {} are not necessary for single statement blocks\n" . $herectx);
6216 # check for single line unbalanced braces
6217 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6218 $sline =~ /^.\s*else\s*\{\s*$/) {
6219 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6222 # check for unnecessary blank lines around braces
6223 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6225 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6226 $fix && $prevrawline =~ /^\+/) {
6227 fix_delete_line($fixlinenr - 1, $prevrawline);
6230 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6232 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6234 fix_delete_line($fixlinenr, $rawline);
6238 # no volatiles please
6239 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6240 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6242 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6245 # Check for user-visible strings broken across lines, which breaks the ability
6246 # to grep for the string. Make exceptions when the previous string ends in a
6247 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6248 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6249 if ($line =~ /^\+\s*$String/ &&
6250 $prevline =~ /"\s*$/ &&
6251 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6252 if (WARN("SPLIT_STRING",
6253 "quoted string split across lines\n" . $hereprev) &&
6255 $prevrawline =~ /^\+.*"\s*$/ &&
6256 $last_coalesced_string_linenr != $linenr - 1) {
6257 my $extracted_string = get_quoted_string($line, $rawline);
6258 my $comma_close = "";
6259 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6263 fix_delete_line($fixlinenr - 1, $prevrawline);
6264 fix_delete_line($fixlinenr, $rawline);
6265 my $fixedline = $prevrawline;
6266 $fixedline =~ s/"\s*$//;
6267 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6268 fix_insert_line($fixlinenr - 1, $fixedline);
6269 $fixedline = $rawline;
6270 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6271 if ($fixedline !~ /\+\s*$/) {
6272 fix_insert_line($fixlinenr, $fixedline);
6274 $last_coalesced_string_linenr = $linenr;
6278 # check for missing a space in a string concatenation
6279 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6280 WARN('MISSING_SPACE',
6281 "break quoted strings at a space character\n" . $hereprev);
6284 # check for an embedded function name in a string when the function is known
6285 # This does not work very well for -f --file checking as it depends on patch
6286 # context providing the function name or a single line form for in-file
6287 # function declarations
6288 if ($line =~ /^\+.*$String/ &&
6289 defined($context_function) &&
6290 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6291 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6292 WARN("EMBEDDED_FUNCTION_NAME",
6293 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6296 # check for unnecessary function tracing like uses
6297 # This does not use $logFunctions because there are many instances like
6298 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6299 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6300 if (WARN("TRACING_LOGGING",
6301 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6303 fix_delete_line($fixlinenr, $rawline);
6307 # check for spaces before a quoted newline
6308 if ($rawline =~ /^.*\".*\s\\n/) {
6309 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6310 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6312 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6317 # concatenated string without spaces between elements
6318 if ($line =~ /$String[A-Z_]/ ||
6319 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6320 if (CHK("CONCATENATED_STRING",
6321 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6323 while ($line =~ /($String)/g) {
6324 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6325 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6326 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6331 # uncoalesced string fragments
6332 if ($line =~ /$String\s*[Lu]?"/) {
6333 if (WARN("STRING_FRAGMENTS",
6334 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6336 while ($line =~ /($String)(?=\s*")/g) {
6337 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6338 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6343 # check for non-standard and hex prefixed decimal printf formats
6344 my $show_L = 1; #don't show the same defect twice
6346 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6347 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6348 $string =~ s/%%/__/g;
6350 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6352 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6356 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6358 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6361 # check for 0x<decimal>
6362 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6363 ERROR("PRINTF_0XDECIMAL",
6364 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6368 # check for line continuations in quoted strings with odd counts of "
6369 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6370 WARN("LINE_CONTINUATIONS",
6371 "Avoid line continuations in quoted strings\n" . $herecurr);
6375 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6377 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6381 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6383 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6386 # check for needless "if (<foo>) fn(<foo>)" uses
6387 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6388 my $tested = quotemeta($1);
6389 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6390 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6392 if (WARN('NEEDLESS_IF',
6393 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6396 my $leading_tabs = "";
6397 my $new_leading_tabs = "";
6398 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6403 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6404 $new_leading_tabs = $1;
6405 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6412 fix_delete_line($fixlinenr - 1, $prevrawline);
6413 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6419 # check for unnecessary "Out of Memory" messages
6420 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6421 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6422 (defined $1 || defined $3) &&
6425 my $testline = $lines[$linenr - 3];
6427 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6428 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6430 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6431 $s !~ /\b__GFP_NOWARN\b/ ) {
6433 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6437 # check for logging functions with KERN_<LEVEL>
6438 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6439 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6441 if (WARN("UNNECESSARY_KERN_LEVEL",
6442 "Possible unnecessary $level\n" . $herecurr) &&
6444 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6448 # check for logging continuations
6449 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6450 WARN("LOGGING_CONTINUATION",
6451 "Avoid logging continuation uses where feasible\n" . $herecurr);
6454 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6455 if (defined $stat &&
6456 $line =~ /\b$logFunctions\s*\(/ &&
6457 index($stat, '"') >= 0) {
6458 my $lc = $stat =~ tr@\n@@;
6459 $lc = $lc + $linenr;
6460 my $stat_real = get_stat_real($linenr, $lc);
6461 pos($stat_real) = index($stat_real, '"');
6462 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6465 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6466 if (WARN("UNNECESSARY_MODIFIER",
6467 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6468 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6471 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6476 # check for mask then right shift without a parentheses
6477 if ($perl_version_ok &&
6478 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6479 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6480 WARN("MASK_THEN_SHIFT",
6481 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6484 # check for pointer comparisons to NULL
6485 if ($perl_version_ok) {
6486 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6489 $equal = "" if ($4 eq "!=");
6490 if (CHK("COMPARISON_TO_NULL",
6491 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6493 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6498 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6499 if ($line =~ /(\b$InitAttribute\b)/) {
6501 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6504 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6505 ERROR("MISPLACED_INIT",
6506 "$attr should be placed after $var\n" . $herecurr)) ||
6507 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6508 WARN("MISPLACED_INIT",
6509 "$attr should be placed after $var\n" . $herecurr))) &&
6511 $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;
6516 # check for $InitAttributeData (ie: __initdata) with const
6517 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6519 $attr =~ /($InitAttributePrefix)(.*)/;
6520 my $attr_prefix = $1;
6522 if (ERROR("INIT_ATTRIBUTE",
6523 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6525 $fixed[$fixlinenr] =~
6526 s/$InitAttributeData/${attr_prefix}initconst/;
6530 # check for $InitAttributeConst (ie: __initconst) without const
6531 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6533 if (ERROR("INIT_ATTRIBUTE",
6534 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6536 my $lead = $fixed[$fixlinenr] =~
6537 /(^\+\s*(?:static\s+))/;
6539 $lead = "$lead " if ($lead !~ /^\+$/);
6540 $lead = "${lead}const ";
6541 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6545 # check for __read_mostly with const non-pointer (should just be const)
6546 if ($line =~ /\b__read_mostly\b/ &&
6547 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6548 if (ERROR("CONST_READ_MOSTLY",
6549 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6551 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6555 # don't use __constant_<foo> functions outside of include/uapi/
6556 if ($realfile !~ m@^include/uapi/@ &&
6557 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6558 my $constant_func = $1;
6559 my $func = $constant_func;
6560 $func =~ s/^__constant_//;
6561 if (WARN("CONSTANT_CONVERSION",
6562 "$constant_func should be $func\n" . $herecurr) &&
6564 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6568 # prefer usleep_range over udelay
6569 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6571 # ignore udelay's < 10, however
6572 if (! ($delay < 10) ) {
6574 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6576 if ($delay > 2000) {
6578 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6582 # warn about unexpectedly long msleep's
6583 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6586 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6590 # check for comparisons of jiffies
6591 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6592 WARN("JIFFIES_COMPARISON",
6593 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6596 # check for comparisons of get_jiffies_64()
6597 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6598 WARN("JIFFIES_COMPARISON",
6599 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6602 # warn about #ifdefs in C files
6603 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6604 # print "#ifdef in C files should be avoided\n";
6605 # print "$herecurr";
6609 # warn about spacing in #ifdefs
6610 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6611 if (ERROR("SPACING",
6612 "exactly one space required after that #$1\n" . $herecurr) &&
6614 $fixed[$fixlinenr] =~
6615 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6620 # check for spinlock_t definitions without a comment.
6621 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6622 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6624 if (!ctx_has_comment($first_line, $linenr)) {
6625 CHK("UNCOMMENTED_DEFINITION",
6626 "$1 definition without comment\n" . $herecurr);
6629 # check for memory barriers without a comment.
6636 my $barrier_stems = qr{
6644 my $all_barriers = qr{
6646 smp_(?:$barrier_stems)|
6647 virt_(?:$barrier_stems)
6650 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6651 if (!ctx_has_comment($first_line, $linenr)) {
6652 WARN("MEMORY_BARRIER",
6653 "memory barrier without comment\n" . $herecurr);
6657 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6659 if ($realfile !~ m@^include/asm-generic/@ &&
6660 $realfile !~ m@/barrier\.h$@ &&
6661 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6662 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6663 WARN("MEMORY_BARRIER",
6664 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6667 # check for waitqueue_active without a comment.
6668 if ($line =~ /\bwaitqueue_active\s*\(/) {
6669 if (!ctx_has_comment($first_line, $linenr)) {
6670 WARN("WAITQUEUE_ACTIVE",
6671 "waitqueue_active without comment\n" . $herecurr);
6675 # check for data_race without a comment.
6676 if ($line =~ /\bdata_race\s*\(/) {
6677 if (!ctx_has_comment($first_line, $linenr)) {
6679 "data_race without comment\n" . $herecurr);
6683 # check of hardware specific defines
6684 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6686 "architecture specific defines should be avoided\n" . $herecurr);
6689 # check that the storage class is not after a type
6690 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6691 WARN("STORAGE_CLASS",
6692 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6694 # Check that the storage class is at the beginning of a declaration
6695 if ($line =~ /\b$Storage\b/ &&
6696 $line !~ /^.\s*$Storage/ &&
6697 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6698 $1 !~ /[\,\)]\s*$/) {
6699 WARN("STORAGE_CLASS",
6700 "storage class should be at the beginning of the declaration\n" . $herecurr);
6703 # check the location of the inline attribute, that it is between
6704 # storage class and type.
6705 if ($line =~ /\b$Type\s+$Inline\b/ ||
6706 $line =~ /\b$Inline\s+$Storage\b/) {
6707 ERROR("INLINE_LOCATION",
6708 "inline keyword should sit between storage class and type\n" . $herecurr);
6711 # Check for __inline__ and __inline, prefer inline
6712 if ($realfile !~ m@\binclude/uapi/@ &&
6713 $line =~ /\b(__inline__|__inline)\b/) {
6715 "plain inline is preferred over $1\n" . $herecurr) &&
6717 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6722 # Check for compiler attributes
6723 if ($realfile !~ m@\binclude/uapi/@ &&
6724 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6726 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6729 "alias" => "__alias",
6730 "aligned" => "__aligned",
6731 "always_inline" => "__always_inline",
6732 "assume_aligned" => "__assume_aligned",
6734 "const" => "__attribute_const__",
6736 "designated_init" => "__designated_init",
6737 "externally_visible" => "__visible",
6738 "format" => "printf|scanf",
6739 "gnu_inline" => "__gnu_inline",
6740 "malloc" => "__malloc",
6742 "no_caller_saved_registers" => "__no_caller_saved_registers",
6743 "noclone" => "__noclone",
6744 "noinline" => "noinline",
6745 "nonstring" => "__nonstring",
6746 "noreturn" => "__noreturn",
6747 "packed" => "__packed",
6749 "section" => "__section",
6754 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6757 $params = $2 if defined($2);
6758 my $curr_attr = $orig_attr;
6759 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6760 if (exists($attr_list{$curr_attr})) {
6761 my $new = $attr_list{$curr_attr};
6762 if ($curr_attr eq "format" && $params) {
6763 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6766 $new = "$new$params";
6768 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6769 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6771 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6772 $fixed[$fixlinenr] =~ s/$remove//;
6773 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6774 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6775 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6780 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6781 if ($attr =~ /^_*unused/) {
6782 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6783 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6787 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6788 if ($perl_version_ok &&
6789 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6790 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6791 $line =~ /\b__weak\b/)) {
6792 ERROR("WEAK_DECLARATION",
6793 "Using weak declarations can have unintended link defects\n" . $herecurr);
6796 # check for c99 types like uint8_t used outside of uapi/ and tools/
6797 if ($realfile !~ m@\binclude/uapi/@ &&
6798 $realfile !~ m@\btools/@ &&
6799 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6801 if ($type =~ /\b($typeC99Typedefs)\b/) {
6803 my $kernel_type = 'u';
6804 $kernel_type = 's' if ($type =~ /^_*[si]/);
6807 if (CHK("PREFER_KERNEL_TYPES",
6808 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6810 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6815 # check for cast of C90 native int or longer types constants
6816 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6820 my $newconst = $const;
6821 $newconst =~ s/${Int_type}$//;
6822 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6823 if ($cast =~ /\blong\s+long\b/) {
6825 } elsif ($cast =~ /\blong\b/) {
6828 if (WARN("TYPECAST_INT_CONSTANT",
6829 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6831 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6835 # check for sizeof(&)
6836 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6837 WARN("SIZEOF_ADDRESS",
6838 "sizeof(& should be avoided\n" . $herecurr);
6841 # check for sizeof without parenthesis
6842 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6843 if (WARN("SIZEOF_PARENTHESIS",
6844 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6846 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6850 # check for struct spinlock declarations
6851 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6852 WARN("USE_SPINLOCK_T",
6853 "struct spinlock should be spinlock_t\n" . $herecurr);
6856 # check for seq_printf uses that could be seq_puts
6857 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6858 my $fmt = get_quoted_string($line, $rawline);
6861 if (WARN("PREFER_SEQ_PUTS",
6862 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6864 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6869 # check for vsprintf extension %p<foo> misuses
6870 if ($perl_version_ok &&
6872 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6873 $1 !~ /^_*volatile_*$/) {
6876 my $lc = $stat =~ tr@\n@@;
6877 $lc = $lc + $linenr;
6878 for (my $count = $linenr; $count <= $lc; $count++) {
6882 my $bad_specifier = "";
6883 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6886 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6890 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6891 ($extension eq "f" &&
6892 defined $qualifier && $qualifier !~ /^w/) ||
6893 ($extension eq "4" &&
6894 defined $qualifier && $qualifier !~ /^cc/)) {
6895 $bad_specifier = $specifier;
6898 if ($extension eq "x" && !defined($stat_real)) {
6899 if (!defined($stat_real)) {
6900 $stat_real = get_stat_real($linenr, $lc);
6902 WARN("VSPRINTF_SPECIFIER_PX",
6903 "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");
6906 if ($bad_specifier ne "") {
6907 my $stat_real = get_stat_real($linenr, $lc);
6908 my $ext_type = "Invalid";
6910 if ($bad_specifier =~ /p[Ff]/) {
6911 $use = " - use %pS instead";
6912 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6915 WARN("VSPRINTF_POINTER_EXTENSION",
6916 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6921 # Check for misused memsets
6922 if ($perl_version_ok &&
6924 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6930 if ($ms_size =~ /^(0x|)0$/i) {
6932 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6933 } elsif ($ms_size =~ /^(0x|)1$/i) {
6935 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6939 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6940 # if ($perl_version_ok &&
6942 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6943 # if (WARN("PREFER_ETHER_ADDR_COPY",
6944 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6946 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6950 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6951 # if ($perl_version_ok &&
6953 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6954 # WARN("PREFER_ETHER_ADDR_EQUAL",
6955 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6958 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6959 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6960 # if ($perl_version_ok &&
6962 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6966 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6967 # if (WARN("PREFER_ETH_ZERO_ADDR",
6968 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6970 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6972 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6973 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6974 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6976 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6981 # strlcpy uses that should likely be strscpy
6982 if ($line =~ /\bstrlcpy\s*\(/) {
6984 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6987 # typecasts on min/max could be min_t/max_t
6988 if ($perl_version_ok &&
6990 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6991 if (defined $2 || defined $7) {
6993 my $cast1 = deparenthesize($2);
6995 my $cast2 = deparenthesize($7);
6999 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7000 $cast = "$cast1 or $cast2";
7001 } elsif ($cast1 ne "") {
7007 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7011 # check usleep_range arguments
7012 if ($perl_version_ok &&
7014 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7018 WARN("USLEEP_RANGE",
7019 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7020 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7022 WARN("USLEEP_RANGE",
7023 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7027 # check for naked sscanf
7028 if ($perl_version_ok &&
7030 $line =~ /\bsscanf\b/ &&
7031 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7032 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7033 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7034 my $lc = $stat =~ tr@\n@@;
7035 $lc = $lc + $linenr;
7036 my $stat_real = get_stat_real($linenr, $lc);
7037 WARN("NAKED_SSCANF",
7038 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7041 # check for simple sscanf that should be kstrto<foo>
7042 if ($perl_version_ok &&
7044 $line =~ /\bsscanf\b/) {
7045 my $lc = $stat =~ tr@\n@@;
7046 $lc = $lc + $linenr;
7047 my $stat_real = get_stat_real($linenr, $lc);
7048 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7050 my $count = $format =~ tr@%@%@;
7052 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7053 WARN("SSCANF_TO_KSTRTO",
7054 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7059 # check for new externs in .h files.
7060 if ($realfile =~ /\.h$/ &&
7061 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7062 if (CHK("AVOID_EXTERNS",
7063 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
7065 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7069 # check for new externs in .c files.
7070 if ($realfile =~ /\.c$/ && defined $stat &&
7071 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7073 my $function_name = $1;
7074 my $paren_space = $2;
7077 if (defined $cond) {
7078 substr($s, 0, length($cond), '');
7082 WARN("AVOID_EXTERNS",
7083 "externs should be avoided in .c files\n" . $herecurr);
7086 if ($paren_space =~ /\n/) {
7087 WARN("FUNCTION_ARGUMENTS",
7088 "arguments for function declarations should follow identifier\n" . $herecurr);
7091 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7092 $stat =~ /^.\s*extern\s+/)
7094 WARN("AVOID_EXTERNS",
7095 "externs should be avoided in .c files\n" . $herecurr);
7098 # check for function declarations that have arguments without identifier names
7099 if (defined $stat &&
7100 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7102 my $args = trim($1);
7103 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7105 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7106 WARN("FUNCTION_ARGUMENTS",
7107 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7112 # check for function definitions
7113 if ($perl_version_ok &&
7115 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7116 $context_function = $1;
7118 # check for multiline function definition with misplaced open brace
7120 my $cnt = statement_rawlines($stat);
7121 my $herectx = $here . "\n";
7122 for (my $n = 0; $n < $cnt; $n++) {
7123 my $rl = raw_line($linenr, $n);
7124 $herectx .= $rl . "\n";
7125 $ok = 1 if ($rl =~ /^[ \+]\{/);
7126 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7127 last if $rl =~ /^[ \+].*\{/;
7131 "open brace '{' following function definitions go on the next line\n" . $herectx);
7135 # checks for new __setup's
7136 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7139 if (!grep(/$name/, @setup_docs)) {
7140 CHK("UNDOCUMENTED_SETUP",
7141 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7145 # check for pointless casting of alloc functions
7146 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7147 WARN("UNNECESSARY_CASTS",
7148 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7152 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7153 if ($perl_version_ok &&
7154 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7155 CHK("ALLOC_SIZEOF_STRUCT",
7156 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7159 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7160 if ($perl_version_ok &&
7162 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7166 my $newfunc = "kmalloc_array";
7167 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7168 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7169 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7172 if ($a1 =~ /^sizeof\s*\S/) {
7176 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7177 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7178 my $cnt = statement_rawlines($stat);
7179 my $herectx = get_stat_here($linenr, $cnt, $here);
7181 if (WARN("ALLOC_WITH_MULTIPLY",
7182 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7185 $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;
7190 # check for krealloc arg reuse
7191 if ($perl_version_ok &&
7192 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7194 WARN("KREALLOC_ARG_REUSE",
7195 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7198 # check for alloc argument mismatch
7199 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7200 WARN("ALLOC_ARRAY_ARGS",
7201 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7204 # check for multiple semicolons
7205 if ($line =~ /;\s*;\s*$/) {
7206 if (WARN("ONE_SEMICOLON",
7207 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7209 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7213 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7214 if ($realfile !~ m@^include/uapi/@ &&
7215 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7217 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7218 if (CHK("BIT_MACRO",
7219 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7221 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7225 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7226 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7227 WARN("IS_ENABLED_CONFIG",
7228 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7231 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7232 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7234 if (WARN("PREFER_IS_ENABLED",
7235 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7237 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7241 # check for /* fallthrough */ like comment, prefer fallthrough;
7242 my @fallthroughs = (
7245 'lint -fallthrough[ \t]*',
7246 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7247 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7248 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7249 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7251 if ($raw_comment ne '') {
7252 foreach my $ft (@fallthroughs) {
7253 if ($raw_comment =~ /$ft/) {
7254 my $msg_level = \&WARN;
7255 $msg_level = \&CHK if ($file);
7256 &{$msg_level}("PREFER_FALLTHROUGH",
7257 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7263 # check for switch/default statements without a break;
7264 if ($perl_version_ok &&
7266 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7267 my $cnt = statement_rawlines($stat);
7268 my $herectx = get_stat_here($linenr, $cnt, $here);
7270 WARN("DEFAULT_NO_BREAK",
7271 "switch default: should use break\n" . $herectx);
7274 # check for gcc specific __FUNCTION__
7275 if ($line =~ /\b__FUNCTION__\b/) {
7276 if (WARN("USE_FUNC",
7277 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7279 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7283 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7284 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7286 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7289 # check for use of yield()
7290 if ($line =~ /\byield\s*\(\s*\)/) {
7292 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7295 # check for comparisons against true and false
7296 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7304 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7306 my $type = lc($otype);
7307 if ($type =~ /^(?:true|false)$/) {
7308 if (("$test" eq "==" && "$type" eq "true") ||
7309 ("$test" eq "!=" && "$type" eq "false")) {
7313 CHK("BOOL_COMPARISON",
7314 "Using comparison to $otype is error prone\n" . $herecurr);
7316 ## maybe suggesting a correct construct would better
7317 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7322 # check for semaphores initialized locked
7323 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7324 WARN("CONSIDER_COMPLETION",
7325 "consider using a completion\n" . $herecurr);
7328 # recommend kstrto* over simple_strto* and strict_strto*
7329 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7330 WARN("CONSIDER_KSTRTO",
7331 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7334 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7335 if ($line =~ /^.\s*__initcall\s*\(/) {
7336 WARN("USE_DEVICE_INITCALL",
7337 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7340 # check for spin_is_locked(), suggest lockdep instead
7341 if ($line =~ /\bspin_is_locked\(/) {
7343 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7346 # check for deprecated apis
7347 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7348 my $deprecated_api = $1;
7349 my $new_api = $deprecated_apis{$deprecated_api};
7350 WARN("DEPRECATED_API",
7351 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7354 # check for various structs that are normally const (ops, kgdb, device_tree)
7355 # and avoid what seem like struct definitions 'struct foo {'
7356 if (defined($const_structs) &&
7357 $line !~ /\bconst\b/ &&
7358 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7359 WARN("CONST_STRUCT",
7360 "struct $1 should normally be const\n" . $herecurr);
7363 # use of NR_CPUS is usually wrong
7364 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7365 # ignore designated initializers using NR_CPUS
7366 if ($line =~ /\bNR_CPUS\b/ &&
7367 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7368 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7369 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7370 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7371 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7372 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7375 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7378 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7379 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7380 ERROR("DEFINE_ARCH_HAS",
7381 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7384 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7385 if ($perl_version_ok &&
7386 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7387 WARN("LIKELY_MISUSE",
7388 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7391 # return sysfs_emit(foo, fmt, ...) fmt without newline
7392 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7393 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7394 my $offset = $+[6] - 1;
7395 if (WARN("SYSFS_EMIT",
7396 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7398 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7402 # nested likely/unlikely calls
7403 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7404 WARN("LIKELY_MISUSE",
7405 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7408 # whine mightly about in_atomic
7409 if ($line =~ /\bin_atomic\s*\(/) {
7410 if ($realfile =~ m@^drivers/@) {
7412 "do not use in_atomic in drivers\n" . $herecurr);
7413 } elsif ($realfile !~ m@^kernel/@) {
7415 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7419 # check for lockdep_set_novalidate_class
7420 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7421 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7422 if ($realfile !~ m@^kernel/lockdep@ &&
7423 $realfile !~ m@^include/linux/lockdep@ &&
7424 $realfile !~ m@^drivers/base/core@) {
7426 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7430 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7431 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7432 WARN("EXPORTED_WORLD_WRITABLE",
7433 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7436 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7437 # and whether or not function naming is typical and if
7438 # DEVICE_ATTR permissions uses are unusual too
7439 if ($perl_version_ok &&
7441 $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*\)/) {
7446 my $octal_perms = perms_to_octal($perms);
7447 if ($show =~ /^${var}_show$/ &&
7448 $store =~ /^${var}_store$/ &&
7449 $octal_perms eq "0644") {
7450 if (WARN("DEVICE_ATTR_RW",
7451 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7453 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7455 } elsif ($show =~ /^${var}_show$/ &&
7456 $store =~ /^NULL$/ &&
7457 $octal_perms eq "0444") {
7458 if (WARN("DEVICE_ATTR_RO",
7459 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7461 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7463 } elsif ($show =~ /^NULL$/ &&
7464 $store =~ /^${var}_store$/ &&
7465 $octal_perms eq "0200") {
7466 if (WARN("DEVICE_ATTR_WO",
7467 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7469 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7471 } elsif ($octal_perms eq "0644" ||
7472 $octal_perms eq "0444" ||
7473 $octal_perms eq "0200") {
7474 my $newshow = "$show";
7475 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7476 my $newstore = $store;
7477 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7479 if ($show ne $newshow) {
7480 $rename .= " '$show' to '$newshow'";
7482 if ($store ne $newstore) {
7483 $rename .= " '$store' to '$newstore'";
7485 WARN("DEVICE_ATTR_FUNCTIONS",
7486 "Consider renaming function(s)$rename\n" . $herecurr);
7488 WARN("DEVICE_ATTR_PERMS",
7489 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7493 # Mode permission misuses where it seems decimal should be octal
7494 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7495 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7496 # specific definition of not visible in sysfs.
7497 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7498 # use the default permissions
7499 if ($perl_version_ok &&
7501 $line =~ /$mode_perms_search/) {
7502 foreach my $entry (@mode_permission_funcs) {
7503 my $func = $entry->[0];
7504 my $arg_pos = $entry->[1];
7506 my $lc = $stat =~ tr@\n@@;
7507 $lc = $lc + $linenr;
7508 my $stat_real = get_stat_real($linenr, $lc);
7513 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7515 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7516 if ($stat =~ /$test/) {
7518 $val = $6 if ($skip_args ne "");
7519 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7520 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7521 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7522 ERROR("NON_OCTAL_PERMISSIONS",
7523 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7525 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7526 ERROR("EXPORTED_WORLD_WRITABLE",
7527 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7533 # check for uses of S_<PERMS> that could be octal for readability
7534 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7536 my $octal = perms_to_octal($oval);
7537 if (WARN("SYMBOLIC_PERMS",
7538 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7540 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7544 # validate content of MODULE_LICENSE against list from include/linux/module.h
7545 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7546 my $extracted_string = get_quoted_string($line, $rawline);
7547 my $valid_licenses = qr{
7550 GPL\ and\ additional\ rights|
7556 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7557 WARN("MODULE_LICENSE",
7558 "unknown module license " . $extracted_string . "\n" . $herecurr);
7560 if (!$file && $extracted_string eq '"GPL v2"') {
7561 if (WARN("MODULE_LICENSE",
7562 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7564 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7569 # check for sysctl duplicate constants
7570 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7571 WARN("DUPLICATED_SYSCTL_CONST",
7572 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7576 # If we have no input at all, then there is nothing to report on
7577 # so just keep quiet.
7578 if ($#rawlines == -1) {
7582 # In mailback mode only produce a report in the negative, for
7583 # things that appear to be patches.
7584 if ($mailback && ($clean == 1 || !$is_patch)) {
7588 # This is not a patch, and we are in 'no-patch' mode so
7590 if (!$chk_patch && !$is_patch) {
7594 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7595 ERROR("NOT_UNIFIED_DIFF",
7596 "Does not appear to be a unified-diff format patch\n");
7598 if ($is_patch && $has_commit_log && $chk_signoff) {
7599 if ($signoff == 0) {
7600 ERROR("MISSING_SIGN_OFF",
7601 "Missing Signed-off-by: line(s)\n");
7602 } elsif ($authorsignoff != 1) {
7603 # authorsignoff values:
7604 # 0 -> missing sign off
7605 # 1 -> sign off identical
7606 # 2 -> names and addresses match, comments mismatch
7607 # 3 -> addresses match, names different
7608 # 4 -> names match, addresses different
7609 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7611 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7613 if ($authorsignoff == 0) {
7614 ERROR("NO_AUTHOR_SIGN_OFF",
7615 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7616 } elsif ($authorsignoff == 2) {
7617 CHK("FROM_SIGN_OFF_MISMATCH",
7618 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7619 } elsif ($authorsignoff == 3) {
7620 WARN("FROM_SIGN_OFF_MISMATCH",
7621 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7622 } elsif ($authorsignoff == 4) {
7623 WARN("FROM_SIGN_OFF_MISMATCH",
7624 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7625 } elsif ($authorsignoff == 5) {
7626 WARN("FROM_SIGN_OFF_MISMATCH",
7627 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7632 print report_dump();
7633 if ($summary && !($clean == 1 && $quiet == 1)) {
7634 print "$filename " if ($summary_file);
7635 print "total: $cnt_error errors, $cnt_warn warnings, " .
7636 (($check)? "$cnt_chk checks, " : "") .
7637 "$cnt_lines lines checked\n";
7641 # If there were any defects found and not already fixing them
7642 if (!$clean and !$fix) {
7645 NOTE: For some of the reported defects, checkpatch may be able to
7646 mechanically convert to the typical style using --fix or --fix-inplace.
7649 # If there were whitespace errors which cleanpatch can fix
7650 # then suggest that.
7651 if ($rpt_cleaners) {
7655 NOTE: Whitespace errors detected.
7656 You may wish to use scripts/cleanpatch or scripts/cleanfile
7661 if ($clean == 0 && $fix &&
7662 ("@rawlines" ne "@fixed" ||
7663 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7664 my $newfile = $filename;
7665 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7669 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7671 open($f, '>', $newfile)
7672 or die "$P: Can't open $newfile for write\n";
7673 foreach my $fixed_line (@fixed) {
7676 if ($linecount > 3) {
7677 $fixed_line =~ s/^\+//;
7678 print $f $fixed_line . "\n";
7681 print $f $fixed_line . "\n";
7689 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7691 Do _NOT_ trust the results written to this file.
7692 Do _NOT_ submit these changes without inspecting them for correctness.
7694 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7695 No warranties, expressed or implied...
7703 print "$vname has no obvious style problems and is ready for submission.\n";
7705 print "$vname has style problems, please review.\n";