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 = "tools/scripts/camelcase.txt";
1000 warn "Ignore list of allowed camelcase symbols.\n";
1001 } elsif (open(my $words, '<', "$root/$allowed_camelcase_file")) {
1005 $line =~ s/\s*\n?$//g;
1008 next if ($line =~ m/^\s*#/);
1009 next if ($line =~ m/^\s*$/);
1010 if ($line =~ /\s/) {
1011 print("$allowed_camelcase_file: '$line' invalid - ignored\n");
1015 $camelcase{$line} = 1;
1017 close("$root/$allowed_camelcase_file");
1019 warn "Failed opening file '$root/$allowed_camelcase_file': $!\n";
1022 # OpenOCD specific: End
1025 if (show_type("CONST_STRUCT")) {
1026 read_words(\$const_structs, $conststructsfile)
1027 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1030 if (defined($typedefsfile)) {
1031 my $typeOtherTypedefs;
1032 read_words(\$typeOtherTypedefs, $typedefsfile)
1033 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
1034 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1038 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
1039 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
1040 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
1041 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
1042 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
1044 (?:$typeTypedefs\b)|
1048 (?:$Modifier\s+|const\s+)*
1050 (?:typeof|__typeof__)\s*\([^\)]*\)|
1051 (?:$typeTypedefs\b)|
1054 (?:\s+$Modifier|\s+const)*
1056 $NonptrTypeMisordered = qr{
1057 (?:$Modifier\s+|const\s+)*
1061 (?:\s+$Modifier|\s+const)*
1063 $NonptrTypeWithAttr = qr{
1064 (?:$Modifier\s+|const\s+)*
1066 (?:typeof|__typeof__)\s*\([^\)]*\)|
1067 (?:$typeTypedefs\b)|
1068 (?:${allWithAttr}\b)
1070 (?:\s+$Modifier|\s+const)*
1074 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1075 (?:\s+$Inline|\s+$Modifier)*
1077 $TypeMisordered = qr{
1078 $NonptrTypeMisordered
1079 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1080 (?:\s+$Inline|\s+$Modifier)*
1082 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1083 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1087 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1089 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1090 # requires at least perl version v5.10.0
1091 # Any use must be runtime checked with $^V
1093 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1094 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1095 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1097 our $declaration_macros = qr{(?x:
1098 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1099 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1100 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1101 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1104 our %allow_repeated_words = (
1111 sub deparenthesize {
1113 return "" if (!defined($string));
1115 while ($string =~ /^\s*\(.*\)\s*$/) {
1116 $string =~ s@^\s*\(\s*@@;
1117 $string =~ s@\s*\)\s*$@@;
1120 $string =~ s@\s+@ @g;
1125 sub seed_camelcase_file {
1128 return if (!(-f $file));
1132 open(my $include_file, '<', "$file")
1133 or warn "$P: Can't read '$file' $!\n";
1134 my $text = <$include_file>;
1135 close($include_file);
1137 my @lines = split('\n', $text);
1139 foreach my $line (@lines) {
1141 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1142 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1144 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1146 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1150 # OpenOCD Specific: Begin: extend to camel[0-9_]*CASE
1151 next if ($line !~ /(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])/);
1152 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)/) {
1154 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)\s*[\(\[,;]/) {
1156 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z])\w*)\s*[;\{]/) {
1159 # OpenOCD Specific: End
1163 our %maintained_status = ();
1165 sub is_maintained_obsolete {
1166 my ($filename) = @_;
1168 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1170 if (!exists($maintained_status{$filename})) {
1171 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1174 return $maintained_status{$filename} =~ /obsolete/i;
1177 sub is_SPDX_License_valid {
1180 # OpenOCD specific: Begin: replace s"scripts"tools/scripts"
1181 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/tools/scripts/spdxcheck.py") || !(-e "$gitroot"));
1183 my $root_path = abs_path($root);
1184 my $status = `cd "$root_path"; echo "$license" | tools/scripts/spdxcheck.py -`;
1185 # OpenOCD specific: End
1186 return 0 if ($status ne "");
1190 my $camelcase_seeded = 0;
1191 sub seed_camelcase_includes {
1192 return if ($camelcase_seeded);
1195 my $camelcase_cache = "";
1196 my @include_files = ();
1198 $camelcase_seeded = 1;
1200 if (-e "$gitroot") {
1201 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1202 chomp $git_last_include_commit;
1203 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1205 my $last_mod_date = 0;
1206 $files = `find $root/include -name "*.h"`;
1207 @include_files = split('\n', $files);
1208 foreach my $file (@include_files) {
1209 my $date = POSIX::strftime("%Y%m%d%H%M",
1210 localtime((stat $file)[9]));
1211 $last_mod_date = $date if ($last_mod_date < $date);
1213 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1216 if ($camelcase_cache ne "" && -f $camelcase_cache) {
1217 open(my $camelcase_file, '<', "$camelcase_cache")
1218 or warn "$P: Can't read '$camelcase_cache' $!\n";
1219 while (<$camelcase_file>) {
1223 close($camelcase_file);
1228 if (-e "$gitroot") {
1229 $files = `${git_command} ls-files "include/*.h"`;
1230 @include_files = split('\n', $files);
1233 foreach my $file (@include_files) {
1234 seed_camelcase_file($file);
1237 if ($camelcase_cache ne "") {
1238 unlink glob ".checkpatch-camelcase.*";
1239 open(my $camelcase_file, '>', "$camelcase_cache")
1240 or warn "$P: Can't write '$camelcase_cache' $!\n";
1241 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1242 print $camelcase_file ("$_\n");
1244 close($camelcase_file);
1248 sub git_is_single_file {
1249 my ($filename) = @_;
1251 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1253 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1254 my $count = $output =~ tr/\n//;
1255 return $count eq 1 && $output =~ m{^${filename}$};
1258 sub git_commit_info {
1259 my ($commit, $id, $desc) = @_;
1261 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1263 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1264 $output =~ s/^\s*//gm;
1265 my @lines = split("\n", $output);
1267 return ($id, $desc) if ($#lines < 0);
1269 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1270 # Maybe one day convert this block of bash into something that returns
1271 # all matching commit ids, but it's very slow...
1273 # echo "checking commits $1..."
1274 # git rev-list --remotes | grep -i "^$1" |
1275 # while read line ; do
1276 # git log --format='%H %s' -1 $line |
1277 # echo "commit $(cut -c 1-12,41-)"
1279 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1280 $lines[0] =~ /^fatal: bad object $commit/) {
1283 $id = substr($lines[0], 0, 12);
1284 $desc = substr($lines[0], 41);
1287 return ($id, $desc);
1290 $chk_signoff = 0 if ($file);
1295 my @fixed_inserted = ();
1296 my @fixed_deleted = ();
1299 # If input is git commits, extract all commits from the commit expressions.
1300 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1301 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1305 foreach my $commit_expr (@ARGV) {
1307 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1308 $git_range = "-$2 $1";
1309 } elsif ($commit_expr =~ m/\.\./) {
1310 $git_range = "$commit_expr";
1312 $git_range = "-1 $commit_expr";
1314 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1315 foreach my $line (split(/\n/, $lines)) {
1316 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1317 next if (!defined($1) || !defined($2));
1320 unshift(@commits, $sha1);
1321 $git_commits{$sha1} = $subject;
1324 die "$P: no git commits after extraction!\n" if (@commits == 0);
1329 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1330 for my $filename (@ARGV) {
1332 my $is_git_file = git_is_single_file($filename);
1333 my $oldfile = $file;
1334 $file = 1 if ($is_git_file);
1336 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1337 die "$P: $filename: git format-patch failed - $!\n";
1339 open($FILE, '-|', "diff -u /dev/null $filename") ||
1340 die "$P: $filename: diff failed - $!\n";
1341 } elsif ($filename eq '-') {
1342 open($FILE, '<&STDIN');
1344 open($FILE, '<', "$filename") ||
1345 die "$P: $filename: open failed - $!\n";
1347 if ($filename eq '-') {
1348 $vname = 'Your patch';
1350 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1356 push(@rawlines, $_);
1357 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1361 if ($#ARGV > 0 && $quiet == 0) {
1362 print '-' x length($vname) . "\n";
1364 print '-' x length($vname) . "\n";
1367 if (!process($filename)) {
1373 @fixed_inserted = ();
1374 @fixed_deleted = ();
1376 @modifierListFile = ();
1379 $file = $oldfile if ($is_git_file);
1383 hash_show_words(\%use_type, "Used");
1384 hash_show_words(\%ignore_type, "Ignored");
1386 if (!$perl_version_ok) {
1389 NOTE: perl $^V is not modern enough to detect all possible issues.
1390 An upgrade to at least perl $minimum_perl_version is suggested.
1397 NOTE: If any of the errors are false positives, please report
1398 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1401 # OpenOCD specific: Begin
1404 NOTE: If any of the errors are false positives, please report
1405 them to the openocd-devel mailing list or prepare a patch
1406 and send it to Gerrit for review.
1408 # OpenOCD specific: End
1414 sub top_of_kernel_tree {
1419 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1420 "README", "Documentation", "arch", "include", "drivers",
1421 "fs", "init", "ipc", "kernel", "lib", "scripts",
1424 # OpenOCD specific: Begin
1426 "AUTHORS", "BUGS", "COPYING", "HACKING", "Makefile.am",
1427 "README", "contrib", "doc", "src", "tcl", "testing", "tools",
1429 # OpenOCD specific: End
1431 foreach my $check (@tree_check) {
1432 if (! -e $root . '/' . $check) {
1440 my ($formatted_email) = @_;
1444 my $name_comment = "";
1448 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1451 $comment = $3 if defined $3;
1452 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1454 $comment = $2 if defined $2;
1455 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1457 $comment = $2 if defined $2;
1458 $formatted_email =~ s/\Q$address\E.*$//;
1459 $name = $formatted_email;
1460 $name = trim($name);
1461 $name =~ s/^\"|\"$//g;
1462 # If there's a name left after stripping spaces and
1463 # leading quotes, and the address doesn't have both
1464 # leading and trailing angle brackets, the address
1466 # "joe smith joe@smith.com" bad
1467 # "joe smith <joe@smith.com" bad
1468 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1473 # OpenOCD specific: Begin: handle jenkins as valid email
1474 } elsif ($formatted_email eq "jenkins") {
1475 $address = "jenkins";
1476 # OpenOCD specific: End
1479 # Extract comments from names excluding quoted parts
1480 # "John D. (Doe)" - Do not extract
1481 if ($name =~ s/\"(.+)\"//) {
1484 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1485 $name_comment .= trim($1);
1487 $name =~ s/^[ \"]+|[ \"]+$//g;
1488 $name = trim("$quoted $name");
1490 $address = trim($address);
1491 $address =~ s/^\<|\>$//g;
1492 $comment = trim($comment);
1494 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1495 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1496 $name = "\"$name\"";
1499 return ($name, $name_comment, $address, $comment);
1503 my ($name, $name_comment, $address, $comment) = @_;
1505 my $formatted_email;
1507 $name =~ s/^[ \"]+|[ \"]+$//g;
1508 $address = trim($address);
1509 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1511 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1512 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1513 $name = "\"$name\"";
1516 $name_comment = trim($name_comment);
1517 $name_comment = " $name_comment" if ($name_comment ne "");
1518 $comment = trim($comment);
1519 $comment = " $comment" if ($comment ne "");
1521 if ("$name" eq "") {
1522 $formatted_email = "$address";
1524 $formatted_email = "$name$name_comment <$address>";
1526 $formatted_email .= "$comment";
1527 return $formatted_email;
1530 sub reformat_email {
1533 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1534 return format_email($email_name, $name_comment, $email_address, $comment);
1537 sub same_email_addresses {
1538 my ($email1, $email2) = @_;
1540 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1541 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1543 return $email1_name eq $email2_name &&
1544 $email1_address eq $email2_address &&
1545 $name1_comment eq $name2_comment &&
1546 $comment1 eq $comment2;
1552 foreach my $path (split(/:/, $ENV{PATH})) {
1553 if (-e "$path/$bin") {
1554 return "$path/$bin";
1564 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1565 if (-e "$path/$conf") {
1566 return "$path/$conf";
1578 for my $c (split(//, $str)) {
1582 for (; ($n % $tabsize) != 0; $n++) {
1594 (my $res = shift) =~ tr/\t/ /c;
1601 # Drop the diff line leader and expand tabs
1603 $line = expand_tabs($line);
1605 # Pick the indent from the front of the line.
1606 my ($white) = ($line =~ /^(\s*)/);
1608 return (length($line), length($white));
1611 my $sanitise_quote = '';
1613 sub sanitise_line_reset {
1614 my ($in_comment) = @_;
1617 $sanitise_quote = '*/';
1619 $sanitise_quote = '';
1632 # Always copy over the diff marker.
1633 $res = substr($line, 0, 1);
1635 for ($off = 1; $off < length($line); $off++) {
1636 $c = substr($line, $off, 1);
1638 # Comments we are whacking completely including the begin
1639 # and end, all to $;.
1640 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1641 $sanitise_quote = '*/';
1643 substr($res, $off, 2, "$;$;");
1647 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1648 $sanitise_quote = '';
1649 substr($res, $off, 2, "$;$;");
1653 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1654 $sanitise_quote = '//';
1656 substr($res, $off, 2, $sanitise_quote);
1661 # A \ in a string means ignore the next character.
1662 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1664 substr($res, $off, 2, 'XX');
1669 if ($c eq "'" || $c eq '"') {
1670 if ($sanitise_quote eq '') {
1671 $sanitise_quote = $c;
1673 substr($res, $off, 1, $c);
1675 } elsif ($sanitise_quote eq $c) {
1676 $sanitise_quote = '';
1680 #print "c<$c> SQ<$sanitise_quote>\n";
1681 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1682 substr($res, $off, 1, $;);
1683 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1684 substr($res, $off, 1, $;);
1685 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1686 substr($res, $off, 1, 'X');
1688 substr($res, $off, 1, $c);
1692 if ($sanitise_quote eq '//') {
1693 $sanitise_quote = '';
1696 # The pathname on a #include may be surrounded by '<' and '>'.
1697 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1698 my $clean = 'X' x length($1);
1699 $res =~ s@\<.*\>@<$clean>@;
1701 # The whole of a #error is a string.
1702 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1703 my $clean = 'X' x length($1);
1704 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1707 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1709 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1715 sub get_quoted_string {
1716 my ($line, $rawline) = @_;
1718 return "" if (!defined($line) || !defined($rawline));
1719 return "" if ($line !~ m/($String)/g);
1720 return substr($rawline, $-[0], $+[0] - $-[0]);
1723 sub ctx_statement_block {
1724 my ($linenr, $remain, $off) = @_;
1725 my $line = $linenr - 1;
1728 my $coff = $off - 1;
1742 @stack = (['', 0]) if ($#stack == -1);
1744 #warn "CSB: blk<$blk> remain<$remain>\n";
1745 # If we are about to drop off the end, pull in more
1748 for (; $remain > 0; $line++) {
1749 last if (!defined $lines[$line]);
1750 next if ($lines[$line] =~ /^-/);
1753 $blk .= $lines[$line] . "\n";
1754 $len = length($blk);
1758 # Bail if there is no further context.
1759 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1763 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1769 $c = substr($blk, $off, 1);
1770 $remainder = substr($blk, $off);
1772 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1774 # Handle nested #if/#else.
1775 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1776 push(@stack, [ $type, $level ]);
1777 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1778 ($type, $level) = @{$stack[$#stack - 1]};
1779 } elsif ($remainder =~ /^#\s*endif\b/) {
1780 ($type, $level) = @{pop(@stack)};
1783 # Statement ends at the ';' or a close '}' at the
1785 if ($level == 0 && $c eq ';') {
1789 # An else is really a conditional as long as its not else if
1790 if ($level == 0 && $coff_set == 0 &&
1791 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1792 $remainder =~ /^(else)(?:\s|{)/ &&
1793 $remainder !~ /^else\s+if\b/) {
1794 $coff = $off + length($1) - 1;
1796 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1797 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1800 if (($type eq '' || $type eq '(') && $c eq '(') {
1804 if ($type eq '(' && $c eq ')') {
1806 $type = ($level != 0)? '(' : '';
1808 if ($level == 0 && $coff < $soff) {
1811 #warn "CSB: mark coff<$coff>\n";
1814 if (($type eq '' || $type eq '{') && $c eq '{') {
1818 if ($type eq '{' && $c eq '}') {
1820 $type = ($level != 0)? '{' : '';
1823 if (substr($blk, $off + 1, 1) eq ';') {
1829 # Preprocessor commands end at the newline unless escaped.
1830 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1838 # We are truly at the end, so shuffle to the next line.
1845 my $statement = substr($blk, $soff, $off - $soff + 1);
1846 my $condition = substr($blk, $soff, $coff - $soff + 1);
1848 #warn "STATEMENT<$statement>\n";
1849 #warn "CONDITION<$condition>\n";
1851 #print "coff<$coff> soff<$off> loff<$loff>\n";
1853 return ($statement, $condition,
1854 $line, $remain + 1, $off - $loff + 1, $level);
1857 sub statement_lines {
1860 # Strip the diff line prefixes and rip blank lines at start and end.
1861 $stmt =~ s/(^|\n)./$1/g;
1865 my @stmt_lines = ($stmt =~ /\n/g);
1867 return $#stmt_lines + 2;
1870 sub statement_rawlines {
1873 my @stmt_lines = ($stmt =~ /\n/g);
1875 return $#stmt_lines + 2;
1878 sub statement_block_size {
1881 $stmt =~ s/(^|\n)./$1/g;
1887 my @stmt_lines = ($stmt =~ /\n/g);
1888 my @stmt_statements = ($stmt =~ /;/g);
1890 my $stmt_lines = $#stmt_lines + 2;
1891 my $stmt_statements = $#stmt_statements + 1;
1893 if ($stmt_lines > $stmt_statements) {
1896 return $stmt_statements;
1900 sub ctx_statement_full {
1901 my ($linenr, $remain, $off) = @_;
1902 my ($statement, $condition, $level);
1906 # Grab the first conditional/block pair.
1907 ($statement, $condition, $linenr, $remain, $off, $level) =
1908 ctx_statement_block($linenr, $remain, $off);
1909 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1910 push(@chunks, [ $condition, $statement ]);
1911 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1912 return ($level, $linenr, @chunks);
1915 # Pull in the following conditional/block pairs and see if they
1916 # could continue the statement.
1918 ($statement, $condition, $linenr, $remain, $off, $level) =
1919 ctx_statement_block($linenr, $remain, $off);
1920 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1921 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1923 push(@chunks, [ $condition, $statement ]);
1926 return ($level, $linenr, @chunks);
1930 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1932 my $start = $linenr - 1;
1939 my @stack = ($level);
1940 for ($line = $start; $remain > 0; $line++) {
1941 next if ($rawlines[$line] =~ /^-/);
1944 $blk .= $rawlines[$line];
1946 # Handle nested #if/#else.
1947 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1948 push(@stack, $level);
1949 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1950 $level = $stack[$#stack - 1];
1951 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1952 $level = pop(@stack);
1955 foreach my $c (split(//, $lines[$line])) {
1956 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1962 if ($c eq $close && $level > 0) {
1964 last if ($level == 0);
1965 } elsif ($c eq $open) {
1970 if (!$outer || $level <= 1) {
1971 push(@res, $rawlines[$line]);
1974 last if ($level == 0);
1977 return ($level, @res);
1979 sub ctx_block_outer {
1980 my ($linenr, $remain) = @_;
1982 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1986 my ($linenr, $remain) = @_;
1988 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1992 my ($linenr, $remain, $off) = @_;
1994 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1997 sub ctx_block_level {
1998 my ($linenr, $remain) = @_;
2000 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
2002 sub ctx_statement_level {
2003 my ($linenr, $remain, $off) = @_;
2005 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
2008 sub ctx_locate_comment {
2009 my ($first_line, $end_line) = @_;
2011 # If c99 comment on the current line, or the line before or after
2012 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
2013 return $current_comment if (defined $current_comment);
2014 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
2015 return $current_comment if (defined $current_comment);
2016 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
2017 return $current_comment if (defined $current_comment);
2019 # Catch a comment on the end of the line itself.
2020 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
2021 return $current_comment if (defined $current_comment);
2023 # Look through the context and try and figure out if there is a
2026 $current_comment = '';
2027 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
2028 my $line = $rawlines[$linenr - 1];
2030 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
2033 if ($line =~ m@/\*@) {
2036 if (!$in_comment && $current_comment ne '') {
2037 $current_comment = '';
2039 $current_comment .= $line . "\n" if ($in_comment);
2040 if ($line =~ m@\*/@) {
2045 chomp($current_comment);
2046 return($current_comment);
2048 sub ctx_has_comment {
2049 my ($first_line, $end_line) = @_;
2050 my $cmt = ctx_locate_comment($first_line, $end_line);
2052 ##print "LINE: $rawlines[$end_line - 1 ]\n";
2053 ##print "CMMT: $cmt\n";
2055 return ($cmt ne '');
2059 my ($linenr, $cnt) = @_;
2061 my $offset = $linenr - 1;
2066 $line = $rawlines[$offset++];
2067 next if (defined($line) && $line =~ /^-/);
2075 my ($linenr, $lc) = @_;
2077 my $stat_real = raw_line($linenr, 0);
2078 for (my $count = $linenr + 1; $count <= $lc; $count++) {
2079 $stat_real = $stat_real . "\n" . raw_line($count, 0);
2086 my ($linenr, $cnt, $here) = @_;
2088 my $herectx = $here . "\n";
2089 for (my $n = 0; $n < $cnt; $n++) {
2090 $herectx .= raw_line($linenr, $n) . "\n";
2101 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2104 $coded = sprintf("^%c", unpack('C', $2) + 64);
2113 my $av_preprocessor = 0;
2118 sub annotate_reset {
2119 $av_preprocessor = 0;
2121 @av_paren_type = ('E');
2122 $av_pend_colon = 'O';
2125 sub annotate_values {
2126 my ($stream, $type) = @_;
2129 my $var = '_' x length($stream);
2132 print "$stream\n" if ($dbg_values > 1);
2134 while (length($cur)) {
2135 @av_paren_type = ('E') if ($#av_paren_type < 0);
2136 print " <" . join('', @av_paren_type) .
2137 "> <$type> <$av_pending>" if ($dbg_values > 1);
2138 if ($cur =~ /^(\s+)/o) {
2139 print "WS($1)\n" if ($dbg_values > 1);
2140 if ($1 =~ /\n/ && $av_preprocessor) {
2141 $type = pop(@av_paren_type);
2142 $av_preprocessor = 0;
2145 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2146 print "CAST($1)\n" if ($dbg_values > 1);
2147 push(@av_paren_type, $type);
2150 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2151 print "DECLARE($1)\n" if ($dbg_values > 1);
2154 } elsif ($cur =~ /^($Modifier)\s*/) {
2155 print "MODIFIER($1)\n" if ($dbg_values > 1);
2158 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2159 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2160 $av_preprocessor = 1;
2161 push(@av_paren_type, $type);
2167 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2168 print "UNDEF($1)\n" if ($dbg_values > 1);
2169 $av_preprocessor = 1;
2170 push(@av_paren_type, $type);
2172 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2173 print "PRE_START($1)\n" if ($dbg_values > 1);
2174 $av_preprocessor = 1;
2176 push(@av_paren_type, $type);
2177 push(@av_paren_type, $type);
2180 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2181 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2182 $av_preprocessor = 1;
2184 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2188 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2189 print "PRE_END($1)\n" if ($dbg_values > 1);
2191 $av_preprocessor = 1;
2193 # Assume all arms of the conditional end as this
2194 # one does, and continue as if the #endif was not here.
2195 pop(@av_paren_type);
2196 push(@av_paren_type, $type);
2199 } elsif ($cur =~ /^(\\\n)/o) {
2200 print "PRECONT($1)\n" if ($dbg_values > 1);
2202 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2203 print "ATTR($1)\n" if ($dbg_values > 1);
2204 $av_pending = $type;
2207 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2208 print "SIZEOF($1)\n" if ($dbg_values > 1);
2214 } elsif ($cur =~ /^(if|while|for)\b/o) {
2215 print "COND($1)\n" if ($dbg_values > 1);
2219 } elsif ($cur =~/^(case)/o) {
2220 print "CASE($1)\n" if ($dbg_values > 1);
2221 $av_pend_colon = 'C';
2224 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2225 print "KEYWORD($1)\n" if ($dbg_values > 1);
2228 } elsif ($cur =~ /^(\()/o) {
2229 print "PAREN('$1')\n" if ($dbg_values > 1);
2230 push(@av_paren_type, $av_pending);
2234 } elsif ($cur =~ /^(\))/o) {
2235 my $new_type = pop(@av_paren_type);
2236 if ($new_type ne '_') {
2238 print "PAREN('$1') -> $type\n"
2239 if ($dbg_values > 1);
2241 print "PAREN('$1')\n" if ($dbg_values > 1);
2244 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2245 print "FUNC($1)\n" if ($dbg_values > 1);
2249 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2250 if (defined $2 && $type eq 'C' || $type eq 'T') {
2251 $av_pend_colon = 'B';
2252 } elsif ($type eq 'E') {
2253 $av_pend_colon = 'L';
2255 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2258 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2259 print "IDENT($1)\n" if ($dbg_values > 1);
2262 } elsif ($cur =~ /^($Assignment)/o) {
2263 print "ASSIGN($1)\n" if ($dbg_values > 1);
2266 } elsif ($cur =~/^(;|{|})/) {
2267 print "END($1)\n" if ($dbg_values > 1);
2269 $av_pend_colon = 'O';
2271 } elsif ($cur =~/^(,)/) {
2272 print "COMMA($1)\n" if ($dbg_values > 1);
2275 } elsif ($cur =~ /^(\?)/o) {
2276 print "QUESTION($1)\n" if ($dbg_values > 1);
2279 } elsif ($cur =~ /^(:)/o) {
2280 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2282 substr($var, length($res), 1, $av_pend_colon);
2283 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2288 $av_pend_colon = 'O';
2290 } elsif ($cur =~ /^(\[)/o) {
2291 print "CLOSE($1)\n" if ($dbg_values > 1);
2294 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2297 print "OPV($1)\n" if ($dbg_values > 1);
2304 substr($var, length($res), 1, $variant);
2307 } elsif ($cur =~ /^($Operators)/o) {
2308 print "OP($1)\n" if ($dbg_values > 1);
2309 if ($1 ne '++' && $1 ne '--') {
2313 } elsif ($cur =~ /(^.)/o) {
2314 print "C($1)\n" if ($dbg_values > 1);
2317 $cur = substr($cur, length($1));
2318 $res .= $type x length($1);
2322 return ($res, $var);
2326 my ($possible, $line) = @_;
2327 my $notPermitted = qr{(?:
2344 ^(?:typedef|struct|enum)\b
2346 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2347 if ($possible !~ $notPermitted) {
2348 # Check for modifiers.
2349 $possible =~ s/\s*$Storage\s*//g;
2350 $possible =~ s/\s*$Sparse\s*//g;
2351 if ($possible =~ /^\s*$/) {
2353 } elsif ($possible =~ /\s/) {
2354 $possible =~ s/\s*$Type\s*//g;
2355 for my $modifier (split(' ', $possible)) {
2356 if ($modifier !~ $notPermitted) {
2357 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2358 push(@modifierListFile, $modifier);
2363 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2364 push(@typeListFile, $possible);
2368 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2377 $type =~ tr/[a-z]/[A-Z]/;
2379 return defined $use_type{$type} if (scalar keys %use_type > 0);
2381 return !defined $ignore_type{$type};
2385 my ($level, $type, $msg) = @_;
2387 if (!show_type($type) ||
2388 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2393 if ($level eq 'ERROR') {
2395 } elsif ($level eq 'WARNING') {
2401 $output .= $prefix . $level . ':';
2403 $output .= BLUE if ($color);
2404 $output .= "$type:";
2406 $output .= RESET if ($color);
2407 $output .= ' ' . $msg . "\n";
2410 my @lines = split("\n", $output, -1);
2411 splice(@lines, 1, 1);
2412 $output = join("\n", @lines);
2416 $output = (split('\n', $output))[0] . "\n";
2419 if ($verbose && exists($verbose_messages{$type}) &&
2420 !exists($verbose_emitted{$type})) {
2421 $output .= $verbose_messages{$type} . "\n\n";
2422 $verbose_emitted{$type} = 1;
2425 push(our @report, $output);
2434 sub fixup_current_range {
2435 my ($lineRef, $offset, $length) = @_;
2437 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2440 my $no = $o + $offset;
2441 my $nl = $l + $length;
2442 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2446 sub fix_inserted_deleted_lines {
2447 my ($linesRef, $insertedRef, $deletedRef) = @_;
2449 my $range_last_linenr = 0;
2450 my $delta_offset = 0;
2455 my $next_insert = 0;
2456 my $next_delete = 0;
2460 my $inserted = @{$insertedRef}[$next_insert++];
2461 my $deleted = @{$deletedRef}[$next_delete++];
2463 foreach my $old_line (@{$linesRef}) {
2465 my $line = $old_line; #don't modify the array
2466 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2468 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2469 $range_last_linenr = $new_linenr;
2470 fixup_current_range(\$line, $delta_offset, 0);
2473 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2474 $deleted = @{$deletedRef}[$next_delete++];
2476 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2479 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2480 push(@lines, ${$inserted}{'LINE'});
2481 $inserted = @{$insertedRef}[$next_insert++];
2483 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2487 push(@lines, $line);
2497 sub fix_insert_line {
2498 my ($linenr, $line) = @_;
2504 push(@fixed_inserted, $inserted);
2507 sub fix_delete_line {
2508 my ($linenr, $line) = @_;
2515 push(@fixed_deleted, $deleted);
2519 my ($type, $msg) = @_;
2521 if (report("ERROR", $type, $msg)) {
2529 my ($type, $msg) = @_;
2531 if (report("WARNING", $type, $msg)) {
2539 my ($type, $msg) = @_;
2541 if ($check && report("CHECK", $type, $msg)) {
2549 sub check_absolute_file {
2550 my ($absolute, $herecurr) = @_;
2551 my $file = $absolute;
2553 ##print "absolute<$absolute>\n";
2555 # See if any suffix of this path is a path within the tree.
2556 while ($file =~ s@^[^/]*/@@) {
2557 if (-f "$root/$file") {
2558 ##print "file<$file>\n";
2566 # It is, so see if the prefix is acceptable.
2567 my $prefix = $absolute;
2568 substr($prefix, -length($file)) = '';
2570 ##print "prefix<$prefix>\n";
2571 if ($prefix ne ".../") {
2572 WARN("USE_RELATIVE_PATH",
2573 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2580 $string =~ s/^\s+|\s+$//g;
2588 $string =~ s/^\s+//;
2596 $string =~ s/\s+$//;
2601 sub string_find_replace {
2602 my ($string, $find, $replace) = @_;
2604 $string =~ s/$find/$replace/g;
2612 my $source_indent = $tabsize;
2613 my $max_spaces_before_tab = $source_indent - 1;
2614 my $spaces_to_tab = " " x $source_indent;
2616 #convert leading spaces to tabs
2617 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2618 #Remove spaces before a tab
2619 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2624 sub pos_last_openparen {
2629 my $opens = $line =~ tr/\(/\(/;
2630 my $closes = $line =~ tr/\)/\)/;
2632 my $last_openparen = 0;
2634 if (($opens == 0) || ($closes >= $opens)) {
2638 my $len = length($line);
2640 for ($pos = 0; $pos < $len; $pos++) {
2641 my $string = substr($line, $pos);
2642 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2643 $pos += length($1) - 1;
2644 } elsif (substr($line, $pos, 1) eq '(') {
2645 $last_openparen = $pos;
2646 } elsif (index($string, '(') == -1) {
2651 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2654 sub get_raw_comment {
2655 my ($line, $rawline) = @_;
2658 for my $i (0 .. (length($line) - 1)) {
2659 if (substr($line, $i, 1) eq "$;") {
2660 $comment .= substr($rawline, $i, 1);
2667 sub exclude_global_initialisers {
2668 my ($realfile) = @_;
2670 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2671 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2672 $realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2673 $realfile =~ m@/bpf/.*\.bpf\.c$@;
2677 my $filename = shift;
2683 my $stashrawline="";
2693 my $authorsignoff = 0;
2694 my $author_sob = '';
2696 my $is_binding_patch = -1;
2697 my $in_header_lines = $file ? 0 : 1;
2698 my $in_commit_log = 0; #Scanning lines before patch
2699 my $has_patch_separator = 0; #Found a --- line
2700 my $has_commit_log = 0; #Encountered lines before patch
2701 my $commit_log_lines = 0; #Number of commit log lines
2702 my $commit_log_possible_stack_dump = 0;
2703 my $commit_log_long_line = 0;
2704 my $commit_log_has_diff = 0;
2705 my $reported_maintainer_file = 0;
2706 my $non_utf8_charset = 0;
2708 my $last_git_commit_id_linenr = -1;
2710 my $last_blank_line = 0;
2711 my $last_coalesced_string_linenr = -1;
2719 # Trace the real file/line as we go.
2724 my $context_function; #undef'd unless there's a known function
2726 my $comment_edge = 0;
2730 my $prev_values = 'E';
2733 my %suppress_ifbraces;
2734 my %suppress_whiletrailers;
2735 my %suppress_export;
2736 my $suppress_statement = 0;
2738 my %signatures = ();
2740 # Pre-scan the patch sanitizing the lines.
2741 # Pre-scan the patch looking for any __setup documentation.
2743 my @setup_docs = ();
2746 my $camelcase_file_seeded = 0;
2748 my $checklicenseline = 1;
2750 sanitise_line_reset();
2752 foreach my $rawline (@rawlines) {
2756 push(@fixed, $rawline) if ($fix);
2758 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2760 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2765 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2774 # Guestimate if this is a continuing comment. Run
2775 # the context looking for a comment "edge". If this
2776 # edge is a close comment then we must be in a comment
2780 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2781 next if (defined $rawlines[$ln - 1] &&
2782 $rawlines[$ln - 1] =~ /^-/);
2784 #print "RAW<$rawlines[$ln - 1]>\n";
2785 last if (!defined $rawlines[$ln - 1]);
2786 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2787 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2792 if (defined $edge && $edge eq '*/') {
2796 # Guestimate if this is a continuing comment. If this
2797 # is the start of a diff block and this line starts
2798 # ' *' then it is very likely a comment.
2799 if (!defined $edge &&
2800 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2805 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2806 sanitise_line_reset($in_comment);
2808 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2809 # Standardise the strings and chars within the input to
2810 # simplify matching -- only bother with positive lines.
2811 $line = sanitise_line($rawline);
2813 push(@lines, $line);
2816 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2821 #print "==>$rawline\n";
2822 #print "-->$line\n";
2824 if ($setup_docs && $line =~ /^\+/) {
2825 push(@setup_docs, $line);
2834 foreach my $line (@lines) {
2837 my $sline = $line; #copy of $line
2838 $sline =~ s/$;/ /g; #with comments as spaces
2840 my $rawline = $rawlines[$linenr - 1];
2841 my $raw_comment = get_raw_comment($line, $rawline);
2843 # check if it's a mode change, rename or start of a patch
2844 if (!$in_commit_log &&
2845 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2846 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2847 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2851 #extract the line range in the file after the patch is applied
2852 if (!$in_commit_log &&
2853 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2856 $first_line = $linenr + 1;
2866 %suppress_ifbraces = ();
2867 %suppress_whiletrailers = ();
2868 %suppress_export = ();
2869 $suppress_statement = 0;
2870 if ($context =~ /\b(\w+)\s*\(/) {
2871 $context_function = $1;
2873 undef $context_function;
2877 # track the line number as we move through the hunk, note that
2878 # new versions of GNU diff omit the leading space on completely
2879 # blank context lines so we need to count that too.
2880 } elsif ($line =~ /^( |\+|$)/) {
2882 $realcnt-- if ($realcnt != 0);
2884 # Measure the line length and indent.
2885 ($length, $indent) = line_stats($rawline);
2887 # Track the previous line.
2888 ($prevline, $stashline) = ($stashline, $line);
2889 ($previndent, $stashindent) = ($stashindent, $indent);
2890 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2892 #warn "line<$line>\n";
2894 } elsif ($realcnt == 1) {
2898 my $hunk_line = ($realcnt != 0);
2900 $here = "#$linenr: " if (!$file);
2901 $here = "#$realline: " if ($file);
2904 # extract the filename as it passes
2905 if ($line =~ /^diff --git.*?(\S+)$/) {
2907 $realfile =~ s@^([^/]*)/@@ if (!$file);
2910 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2912 $realfile =~ s@^([^/]*)/@@ if (!$file);
2916 if (!$file && $tree && $p1_prefix ne '' &&
2917 -e "$root/$p1_prefix") {
2918 WARN("PATCH_PREFIX",
2919 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2922 if ($realfile =~ m@^include/asm/@) {
2923 ERROR("MODIFIED_INCLUDE_ASM",
2924 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2929 #make up the handle for any error we report on this line
2931 $prefix = "$realfile:$realline: "
2934 $prefix = "$filename:$realline: ";
2936 $prefix = "$filename:$linenr: ";
2941 if (is_maintained_obsolete($realfile)) {
2943 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2945 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2948 $check = $check_orig;
2950 $checklicenseline = 1;
2952 if ($realfile !~ /^MAINTAINERS/) {
2953 my $last_binding_patch = $is_binding_patch;
2955 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2957 if (($last_binding_patch != -1) &&
2958 ($last_binding_patch ^ $is_binding_patch)) {
2959 WARN("DT_SPLIT_BINDING_PATCH",
2960 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2967 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2969 my $hereline = "$here\n$rawline\n";
2970 my $herecurr = "$here\n$rawline\n";
2971 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2973 $cnt_lines++ if ($realcnt != 0);
2975 # Verify the existence of a commit log if appropriate
2976 # 2 is used because a $signature is counted in $commit_log_lines
2977 if ($in_commit_log) {
2978 if ($line !~ /^\s*$/) {
2979 $commit_log_lines++; #could be a $signature
2981 } elsif ($has_commit_log && $commit_log_lines < 2) {
2982 WARN("COMMIT_MESSAGE",
2983 "Missing commit description - Add an appropriate one\n");
2984 $commit_log_lines = 2; #warn only once
2987 # Check if the commit log has what seems like a diff which can confuse patch
2988 if ($in_commit_log && !$commit_log_has_diff &&
2989 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2990 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2991 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2992 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2993 ERROR("DIFF_IN_COMMIT_MSG",
2994 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2995 $commit_log_has_diff = 1;
2998 # Check for incorrect file permissions
2999 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
3000 my $permhere = $here . "FILE: $realfile\n";
3001 if ($realfile !~ m@scripts/@ &&
3002 $realfile !~ /\.(py|pl|awk|sh)$/) {
3003 ERROR("EXECUTE_PERMISSIONS",
3004 "do not set execute permissions for source files\n" . $permhere);
3008 # Check the patch for a From:
3009 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
3011 my $curline = $linenr;
3012 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
3015 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
3017 $author = reformat_email($author);
3020 # Check the patch for a signoff:
3021 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
3024 if ($author ne '' && $authorsignoff != 1) {
3025 if (same_email_addresses($1, $author)) {
3029 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
3030 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
3032 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
3035 } elsif (lc $email_address eq lc $author_address) {
3038 } elsif ($email_name eq $author_name) {
3042 my $address1 = $email_address;
3043 my $address2 = $author_address;
3045 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
3048 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
3051 if ($address1 eq $address2) {
3059 # OpenOCD specific: Begin: Extend list of checkpatch tests to ignore
3060 if ($in_commit_log && $line =~ /^\s*Checkpatch-ignore:\s*(.*)/) {
3061 my @array = split(/[\s,]+/, $1);
3062 hash_save_array_words(\%ignore_type, \@array);
3064 # OpenOCD specific: End
3066 # Check for patch separator
3067 if ($line =~ /^---$/) {
3068 $has_patch_separator = 1;
3072 # Check if MAINTAINERS is being updated. If so, there's probably no need to
3073 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
3074 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3075 $reported_maintainer_file = 1;
3078 # Check signature styles
3079 if (!$in_header_lines &&
3080 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3081 my $space_before = $1;
3083 my $space_after = $3;
3085 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3087 if ($sign_off !~ /$signature_tags/) {
3088 my $suggested_signature = find_standard_signature($sign_off);
3089 if ($suggested_signature eq "") {
3090 WARN("BAD_SIGN_OFF",
3091 "Non-standard signature: $sign_off\n" . $herecurr);
3093 if (WARN("BAD_SIGN_OFF",
3094 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3096 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3100 if (defined $space_before && $space_before ne "") {
3101 if (WARN("BAD_SIGN_OFF",
3102 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3104 $fixed[$fixlinenr] =
3105 "$ucfirst_sign_off $email";
3108 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3109 if (WARN("BAD_SIGN_OFF",
3110 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3112 $fixed[$fixlinenr] =
3113 "$ucfirst_sign_off $email";
3117 if (!defined $space_after || $space_after ne " ") {
3118 if (WARN("BAD_SIGN_OFF",
3119 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3121 $fixed[$fixlinenr] =
3122 "$ucfirst_sign_off $email";
3126 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3127 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3128 if ($suggested_email eq "") {
3129 ERROR("BAD_SIGN_OFF",
3130 "Unrecognized email address: '$email'\n" . $herecurr);
3132 my $dequoted = $suggested_email;
3133 $dequoted =~ s/^"//;
3134 $dequoted =~ s/" </ </;
3135 # Don't force email to have quotes
3136 # Allow just an angle bracketed address
3137 if (!same_email_addresses($email, $suggested_email)) {
3138 if (WARN("BAD_SIGN_OFF",
3139 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3141 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3145 # Address part shouldn't have comments
3146 my $stripped_address = $email_address;
3147 $stripped_address =~ s/\([^\(\)]*\)//g;
3148 if ($email_address ne $stripped_address) {
3149 if (WARN("BAD_SIGN_OFF",
3150 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3152 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3156 # Only one name comment should be allowed
3157 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3158 if ($comment_count > 1) {
3159 WARN("BAD_SIGN_OFF",
3160 "Use a single name comment in email: '$email'\n" . $herecurr);
3164 # stable@vger.kernel.org or stable@kernel.org shouldn't
3165 # have an email name. In addition comments should strictly
3167 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3168 if (($comment ne "" && $comment !~ /^#.+/) ||
3169 ($email_name ne "")) {
3170 my $cur_name = $email_name;
3171 my $new_comment = $comment;
3172 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3174 # Remove brackets enclosing comment text
3175 # and # from start of comments to get comment text
3176 $new_comment =~ s/^\((.*)\)$/$1/;
3177 $new_comment =~ s/^\[(.*)\]$/$1/;
3178 $new_comment =~ s/^[\s\#]+|\s+$//g;
3180 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3181 $new_comment = " # $new_comment" if ($new_comment ne "");
3182 my $new_email = "$email_address$new_comment";
3184 if (WARN("BAD_STABLE_ADDRESS_STYLE",
3185 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3187 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3190 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3191 my $new_comment = $comment;
3193 # Extract comment text from within brackets or
3194 # c89 style /*...*/ comments
3195 $new_comment =~ s/^\[(.*)\]$/$1/;
3196 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3198 $new_comment = trim($new_comment);
3199 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3200 $new_comment = "($new_comment)" if ($new_comment ne "");
3201 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3203 if (WARN("BAD_SIGN_OFF",
3204 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3206 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3211 # Check for duplicate signatures
3212 my $sig_nospace = $line;
3213 $sig_nospace =~ s/\s//g;
3214 $sig_nospace = lc($sig_nospace);
3215 if (defined $signatures{$sig_nospace}) {
3216 WARN("BAD_SIGN_OFF",
3217 "Duplicate signature\n" . $herecurr);
3219 $signatures{$sig_nospace} = 1;
3222 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3223 if ($sign_off =~ /^co-developed-by:$/i) {
3224 if ($email eq $author) {
3225 WARN("BAD_SIGN_OFF",
3226 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3228 if (!defined $lines[$linenr]) {
3229 WARN("BAD_SIGN_OFF",
3230 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3231 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3232 WARN("BAD_SIGN_OFF",
3233 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3234 } elsif ($1 ne $email) {
3235 WARN("BAD_SIGN_OFF",
3236 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3241 # Check email subject for common tools that don't need to be mentioned
3242 if ($in_header_lines &&
3243 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3244 WARN("EMAIL_SUBJECT",
3245 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3248 # Check for Gerrit Change-Ids not in any patch context
3249 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3250 if (ERROR("GERRIT_CHANGE_ID",
3251 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3253 fix_delete_line($fixlinenr, $rawline);
3257 # Check if the commit log is in a possible stack dump
3258 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3259 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3260 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3262 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3263 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3264 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3265 # stack dump address styles
3266 $commit_log_possible_stack_dump = 1;
3269 # Check for line lengths > 75 in commit log, warn once
3270 if ($in_commit_log && !$commit_log_long_line &&
3271 length($line) > 75 &&
3272 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3273 # file delta changes
3274 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3276 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3277 # A Fixes: or Link: line or signature tag line
3278 $commit_log_possible_stack_dump)) {
3279 WARN("COMMIT_LOG_LONG_LINE",
3280 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3281 $commit_log_long_line = 1;
3284 # Reset possible stack dump if a blank line is found
3285 if ($in_commit_log && $commit_log_possible_stack_dump &&
3287 $commit_log_possible_stack_dump = 0;
3290 # Check for lines starting with a #
3291 if ($in_commit_log && $line =~ /^#/) {
3292 if (WARN("COMMIT_COMMENT_SYMBOL",
3293 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3295 $fixed[$fixlinenr] =~ s/^/ /;
3299 # Check for git id commit length and improperly formed commit descriptions
3300 # A correctly formed commit description is:
3301 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3302 # with the commit subject '("' prefix and '")' suffix
3303 # This is a fairly compilicated block as it tests for what appears to be
3304 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3305 # possible SHA-1 matches.
3306 # A commit match can span multiple lines so this block attempts to find a
3307 # complete typical commit on a maximum of 3 lines
3308 if ($perl_version_ok &&
3309 $in_commit_log && !$commit_log_possible_stack_dump &&
3310 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3311 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3312 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3313 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3314 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3315 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3316 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3317 my $init_char = "c";
3318 my $orig_commit = "";
3323 my $id = '0123456789ab';
3324 my $orig_desc = "commit description";
3325 my $description = "";
3326 my $herectx = $herecurr;
3331 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3332 for (my $n = 0; $n < 2; $n++) {
3333 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3336 # Always strip leading/trailing parens then double quotes if existing
3337 $orig_desc = substr($orig_desc, 1, -1);
3338 if ($orig_desc =~ /^".*"$/) {
3339 $orig_desc = substr($orig_desc, 1, -1);
3344 last if ($#lines < $linenr + $n);
3345 $input .= " " . trim($rawlines[$linenr + $n]);
3346 $herectx .= "$rawlines[$linenr + $n]\n";
3348 $herectx = $herecurr if (!$has_parens);
3351 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3353 $orig_commit = lc($2);
3354 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3355 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3356 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3357 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3358 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3359 $orig_commit = lc($1);
3362 ($id, $description) = git_commit_info($orig_commit,
3366 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3367 $last_git_commit_id_linenr != $linenr - 1) {
3368 ERROR("GIT_COMMIT_ID",
3369 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3371 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3372 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3375 # Check for added, moved or deleted files
3376 if (!$reported_maintainer_file && !$in_commit_log &&
3377 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3378 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3379 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3380 (defined($1) || defined($2))))) {
3382 $reported_maintainer_file = 1;
3383 WARN("FILE_PATH_CHANGES",
3384 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3387 # Check for adding new DT bindings not in schema format
3388 if (!$in_commit_log &&
3389 ($line =~ /^new file mode\s*\d+\s*$/) &&
3390 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3391 WARN("DT_SCHEMA_BINDING_PATCH",
3392 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3395 # Check for wrappage within a valid hunk of the file
3396 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3397 ERROR("CORRUPTED_PATCH",
3398 "patch seems to be corrupt (line wrapped?)\n" .
3399 $herecurr) if (!$emitted_corrupt++);
3402 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3403 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3404 $rawline !~ m/^$UTF8*$/) {
3405 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3407 my $blank = copy_spacing($rawline);
3408 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3409 my $hereptr = "$hereline$ptr\n";
3412 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3415 # Check if it's the start of a commit log
3416 # (not a header line and we haven't seen the patch filename)
3417 if ($in_header_lines && $realfile =~ /^$/ &&
3418 !($rawline =~ /^\s+(?:\S|$)/ ||
3419 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3420 $in_header_lines = 0;
3422 $has_commit_log = 1;
3425 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3426 # declined it, i.e defined some charset where it is missing.
3427 if ($in_header_lines &&
3428 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3430 $non_utf8_charset = 1;
3433 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3434 $rawline =~ /$NON_ASCII_UTF8/) {
3435 WARN("UTF8_BEFORE_PATCH",
3436 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3439 # Check for absolute kernel paths in commit message
3440 if ($tree && $in_commit_log) {
3441 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3444 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3445 check_absolute_file($1, $herecurr)) {
3448 check_absolute_file($file, $herecurr);
3453 # Check for various typo / spelling mistakes
3454 if (defined($misspellings) &&
3455 # OpenOCD specific: Begin: don't check spelling on spelling_file
3456 index($spelling_file, $realfile) + length($realfile) != length($spelling_file) &&
3457 # OpenOCD specific: End
3458 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3459 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3461 my $blank = copy_spacing($rawline);
3462 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3463 my $hereptr = "$hereline$ptr\n";
3464 my $typo_fix = $spelling_fix{lc($typo)};
3465 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3466 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3467 my $msg_level = \&WARN;
3468 $msg_level = \&CHK if ($file);
3469 if (&{$msg_level}("TYPO_SPELLING",
3470 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3472 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3477 # check for invalid commit id
3478 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3481 ($id, $description) = git_commit_info($2, undef, undef);
3482 if (!defined($id)) {
3483 WARN("UNKNOWN_COMMIT_ID",
3484 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3488 # check for repeated words separated by a single space
3489 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3490 if (($rawline =~ /^\+/ || $in_commit_log) &&
3491 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3492 pos($rawline) = 1 if (!$in_commit_log);
3493 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3497 my $start_pos = $-[1];
3498 my $end_pos = $+[2];
3499 if ($first =~ /(?:struct|union|enum)/) {
3500 pos($rawline) += length($first) + length($second) + 1;
3504 next if (lc($first) ne lc($second));
3505 next if ($first eq 'long');
3507 # check for character before and after the word matches
3508 my $start_char = '';
3510 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3511 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3513 next if ($start_char =~ /^\S$/);
3514 next if (index(" \t.,;?!", $end_char) == -1);
3516 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3517 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3518 next if (!exists($allow_repeated_words{lc($first)}));
3521 if (WARN("REPEATED_WORD",
3522 "Possible repeated word: '$first'\n" . $herecurr) &&
3524 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3528 # if it's a repeated word on consecutive lines in a comment block
3529 if ($prevline =~ /$;+\s*$/ &&
3530 $prevrawline =~ /($word_pattern)\s*$/) {
3532 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3533 if (WARN("REPEATED_WORD",
3534 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3536 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3542 # ignore non-hunk lines and lines being removed
3543 next if (!$hunk_line || $line =~ /^-/);
3545 #trailing whitespace
3546 if ($line =~ /^\+.*\015/) {
3547 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3548 if (ERROR("DOS_LINE_ENDINGS",
3549 "DOS line endings\n" . $herevet) &&
3551 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3553 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3554 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3555 if (ERROR("TRAILING_WHITESPACE",
3556 "trailing whitespace\n" . $herevet) &&
3558 $fixed[$fixlinenr] =~ s/\s+$//;
3564 # Check for FSF mailing addresses.
3565 if ($rawline =~ /\bwrite to the Free/i ||
3566 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3567 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3568 $rawline =~ /\b51\s+Franklin\s+St/i) {
3569 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3570 my $msg_level = \&ERROR;
3571 $msg_level = \&CHK if ($file);
3572 &{$msg_level}("FSF_MAILING_ADDRESS",
3573 "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)
3576 # check for Kconfig help text having a real description
3577 # Only applies when adding the entry originally, after that we do not have
3578 # sufficient context to determine whether it is indeed long enough.
3579 if ($realfile =~ /Kconfig/ &&
3580 # 'choice' is usually the last thing on the line (though
3581 # Kconfig supports named choices), so use a word boundary
3582 # (\b) rather than a whitespace character (\s)
3583 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3587 my $help_length = 0;
3588 while (defined $lines[$ln]) {
3589 my $f = $lines[$ln++];
3591 next if ($f =~ /^-/);
3592 last if ($f !~ /^[\+ ]/); # !patch context
3594 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3598 if ($f =~ /^\+\s*help\s*$/) {
3603 $f =~ s/^.//; # strip patch context [+ ]
3604 $f =~ s/#.*//; # strip # directives
3605 $f =~ s/^\s+//; # strip leading blanks
3606 next if ($f =~ /^$/); # skip blank lines
3608 # At the end of this Kconfig block:
3609 # This only checks context lines in the patch
3610 # and so hopefully shouldn't trigger false
3611 # positives, even though some of these are
3612 # common words in help texts
3613 if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3614 if|endif|menu|endmenu|source)\b/x) {
3617 $help_length++ if ($has_help);
3620 $help_length < $min_conf_desc_length) {
3621 my $stat_real = get_stat_real($linenr, $ln - 1);
3622 WARN("CONFIG_DESCRIPTION",
3623 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n");
3627 # check MAINTAINERS entries
3628 if ($realfile =~ /^MAINTAINERS$/) {
3629 # check MAINTAINERS entries for the right form
3630 if ($rawline =~ /^\+[A-Z]:/ &&
3631 $rawline !~ /^\+[A-Z]:\t\S/) {
3632 if (WARN("MAINTAINERS_STYLE",
3633 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3635 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3638 # check MAINTAINERS entries for the right ordering too
3639 my $preferred_order = 'MRLSWQBCPTFXNK';
3640 if ($rawline =~ /^\+[A-Z]:/ &&
3641 $prevrawline =~ /^[\+ ][A-Z]:/) {
3642 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3645 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3648 my $curindex = index($preferred_order, $cur);
3649 my $previndex = index($preferred_order, $prev);
3650 if ($curindex < 0) {
3651 WARN("MAINTAINERS_STYLE",
3652 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3654 if ($previndex >= 0 && $curindex < $previndex) {
3655 WARN("MAINTAINERS_STYLE",
3656 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3657 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3658 ($prev eq 'X' && $cur eq 'X')) &&
3659 ($prevval cmp $curval) > 0) {
3660 WARN("MAINTAINERS_STYLE",
3661 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3667 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3668 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3671 'EXTRA_AFLAGS' => 'asflags-y',
3672 'EXTRA_CFLAGS' => 'ccflags-y',
3673 'EXTRA_CPPFLAGS' => 'cppflags-y',
3674 'EXTRA_LDFLAGS' => 'ldflags-y',
3677 WARN("DEPRECATED_VARIABLE",
3678 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3681 # check for DT compatible documentation
3682 if (defined $root &&
3683 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3684 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3686 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3688 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3689 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3691 foreach my $compat (@compats) {
3692 my $compat2 = $compat;
3693 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3694 my $compat3 = $compat;
3695 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3696 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3698 WARN("UNDOCUMENTED_DT_STRING",
3699 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3702 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3704 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3706 WARN("UNDOCUMENTED_DT_STRING",
3707 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3712 # check for using SPDX license tag at beginning of files
3713 if ($realline == $checklicenseline) {
3714 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3715 $checklicenseline = 2;
3716 } elsif ($rawline =~ /^\+/) {
3718 if ($realfile =~ /\.(h|s|S)$/) {
3720 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3722 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3724 } elsif ($realfile =~ /\.rst$/) {
3726 # OpenOCD specific: Begin
3727 } elsif ($realfile =~ /\.(am|cfg|tcl)$/) {
3729 # OpenOCD specific: End
3732 # check SPDX comment style for .[chsS] files
3733 if ($realfile =~ /\.[chsS]$/ &&
3734 $rawline =~ /SPDX-License-Identifier:/ &&
3735 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3736 WARN("SPDX_LICENSE_TAG",
3737 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3740 if ($comment !~ /^$/ &&
3741 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3742 WARN("SPDX_LICENSE_TAG",
3743 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3744 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3745 my $spdx_license = $1;
3746 if (!is_SPDX_License_valid($spdx_license)) {
3747 WARN("SPDX_LICENSE_TAG",
3748 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3750 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3751 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3752 my $msg_level = \&WARN;
3753 $msg_level = \&CHK if ($file);
3754 if (&{$msg_level}("SPDX_LICENSE_TAG",
3756 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3758 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3765 # check for embedded filenames
3766 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3767 WARN("EMBEDDED_FILENAME",
3768 "It's generally not useful to have the filename in the file\n" . $herecurr);
3771 # check we are in a valid source file if not then ignore this hunk
3772 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3774 # check for using SPDX-License-Identifier on the wrong line number
3775 if ($realline != $checklicenseline &&
3776 $rawline =~ /\bSPDX-License-Identifier:/ &&
3777 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3778 WARN("SPDX_LICENSE_TAG",
3779 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3782 # line length limit (with some exclusions)
3784 # There are a few types of lines that may extend beyond $max_line_length:
3785 # logging functions like pr_info that end in a string
3786 # lines with a single string
3787 # #defines that are a single string
3788 # lines with an RFC3986 like URL
3790 # There are 3 different line length message types:
3791 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3792 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3793 # LONG_LINE all other lines longer than $max_line_length
3795 # if LONG_LINE is ignored, the other 2 types are also ignored
3798 if ($line =~ /^\+/ && $length > $max_line_length) {
3799 my $msg_type = "LONG_LINE";
3801 # Check the allowed long line types first
3803 # logging functions that end in a string that starts
3804 # before $max_line_length
3805 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3806 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3809 # lines with only strings (w/ possible termination)
3810 # #defines with only strings
3811 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3812 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3815 # More special cases
3816 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3817 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3820 # URL ($rawline is used in case the URL is in a comment)
3821 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3824 # Otherwise set the alternate message types
3826 # a comment starts before $max_line_length
3827 } elsif ($line =~ /($;[\s$;]*)$/ &&
3828 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3829 $msg_type = "LONG_LINE_COMMENT"
3831 # a quoted string starts before $max_line_length
3832 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3833 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3834 $msg_type = "LONG_LINE_STRING"
3837 if ($msg_type ne "" &&
3838 (show_type("LONG_LINE") || show_type($msg_type))) {
3839 my $msg_level = \&WARN;
3840 $msg_level = \&CHK if ($file);
3841 &{$msg_level}($msg_type,
3842 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3846 # check for adding lines without a newline.
3847 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3848 if (WARN("MISSING_EOF_NEWLINE",
3849 "adding a line without newline at end of file\n" . $herecurr) &&
3851 fix_delete_line($fixlinenr+1, "No newline at end of file");
3855 # check for .L prefix local symbols in .S files
3856 if ($realfile =~ /\.S$/ &&
3857 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3858 WARN("AVOID_L_PREFIX",
3859 "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);
3862 # check we are in a valid source file C or perl if not then ignore this hunk
3863 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3865 # at the beginning of a line any tabs must come first and anything
3866 # more than $tabsize must use tabs.
3867 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3868 $rawline =~ /^\+\s* \s*/) {
3869 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3871 if (ERROR("CODE_INDENT",
3872 "code indent should use tabs where possible\n" . $herevet) &&
3874 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3878 # check for space before tabs.
3879 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3880 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3881 if (WARN("SPACE_BEFORE_TAB",
3882 "please, no space before tabs\n" . $herevet) &&
3884 while ($fixed[$fixlinenr] =~
3885 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3886 while ($fixed[$fixlinenr] =~
3887 s/(^\+.*) +\t/$1\t/) {}
3891 # check for assignments on the start of a line
3892 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3894 if (CHK("ASSIGNMENT_CONTINUATIONS",
3895 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3896 $fix && $prevrawline =~ /^\+/) {
3897 # add assignment operator to the previous line, remove from current line
3898 $fixed[$fixlinenr - 1] .= " $operator";
3899 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3903 # check for && or || at the start of a line
3904 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3906 if (CHK("LOGICAL_CONTINUATIONS",
3907 "Logical continuations should be on the previous line\n" . $hereprev) &&
3908 $fix && $prevrawline =~ /^\+/) {
3909 # insert logical operator at last non-comment, non-whitepsace char on previous line
3910 $prevline =~ /[\s$;]*$/;
3911 my $line_end = substr($prevrawline, $-[0]);
3912 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3913 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3917 # check indentation starts on a tab stop
3918 if ($perl_version_ok &&
3919 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3920 my $indent = length($1);
3921 if ($indent % $tabsize) {
3923 "Statements should start on a tabstop\n" . $herecurr) &&
3925 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3930 # check multi-line statement indentation matches previous line
3931 if ($perl_version_ok &&
3932 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3933 $prevline =~ /^\+(\t*)(.*)$/;
3937 my $pos = pos_last_openparen($rest);
3939 $line =~ /^(\+| )([ \t]*)/;
3942 my $goodtabindent = $oldindent .
3943 "\t" x ($pos / $tabsize) .
3944 " " x ($pos % $tabsize);
3945 my $goodspaceindent = $oldindent . " " x $pos;
3947 if ($newindent ne $goodtabindent &&
3948 $newindent ne $goodspaceindent) {
3950 if (CHK("PARENTHESIS_ALIGNMENT",
3951 "Alignment should match open parenthesis\n" . $hereprev) &&
3952 $fix && $line =~ /^\+/) {
3953 $fixed[$fixlinenr] =~
3954 s/^\+[ \t]*/\+$goodtabindent/;
3960 # check for space after cast like "(int) foo" or "(struct foo) bar"
3961 # avoid checking a few false positives:
3962 # "sizeof(<type>)" or "__alignof__(<type>)"
3963 # function pointer declarations like "(*foo)(int) = bar;"
3964 # structure definitions like "(struct foo) { 0 };"
3965 # multiline macros that define functions
3966 # known attributes or the __attribute__ keyword
3967 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3968 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3970 "No space is necessary after a cast\n" . $herecurr) &&
3972 $fixed[$fixlinenr] =~
3973 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3977 # Block comment styles
3978 # Networking with an initial /*
3979 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3980 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3981 $rawline =~ /^\+[ \t]*\*/ &&
3982 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3983 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3984 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3987 # Block comments use * on subsequent lines
3988 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3989 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3990 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3991 $rawline =~ /^\+/ && #line is new
3992 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3993 WARN("BLOCK_COMMENT_STYLE",
3994 "Block comments use * on subsequent lines\n" . $hereprev);
3997 # Block comments use */ on trailing lines
3998 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3999 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
4000 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
4001 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
4002 WARN("BLOCK_COMMENT_STYLE",
4003 "Block comments use a trailing */ on a separate line\n" . $herecurr);
4006 # Block comment * alignment
4007 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4008 $line =~ /^\+[ \t]*$;/ && #leading comment
4009 $rawline =~ /^\+[ \t]*\*/ && #leading *
4010 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
4011 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
4012 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4014 $prevrawline =~ m@^\+([ \t]*/?)\*@;
4016 $oldindent = expand_tabs($1);
4018 $prevrawline =~ m@^\+(.*/?)\*@;
4019 $oldindent = expand_tabs($1);
4021 $rawline =~ m@^\+([ \t]*)\*@;
4023 $newindent = expand_tabs($newindent);
4024 if (length($oldindent) ne length($newindent)) {
4025 WARN("BLOCK_COMMENT_STYLE",
4026 "Block comments should align the * on each line\n" . $hereprev);
4030 # check for missing blank lines after struct/union declarations
4031 # with exceptions for various attributes and macros
4032 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4034 !($line =~ /^\+\s*$/ ||
4035 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ ||
4036 $line =~ /^\+\s*MODULE_/i ||
4037 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4038 $line =~ /^\+[a-z_]*init/ ||
4039 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4040 $line =~ /^\+\s*DECLARE/ ||
4041 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4042 $line =~ /^\+\s*__setup/)) {
4043 if (CHK("LINE_SPACING",
4044 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4046 fix_insert_line($fixlinenr, "\+");
4050 # check for multiple consecutive blank lines
4051 if ($prevline =~ /^[\+ ]\s*$/ &&
4052 $line =~ /^\+\s*$/ &&
4053 $last_blank_line != ($linenr - 1)) {
4054 if (CHK("LINE_SPACING",
4055 "Please don't use multiple blank lines\n" . $hereprev) &&
4057 fix_delete_line($fixlinenr, $rawline);
4060 $last_blank_line = $linenr;
4063 # check for missing blank lines after declarations
4064 # (declarations must have the same indentation and not be at the start of line)
4065 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4069 # remove $Attribute/$Sparse uses to simplify comparisons
4070 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4071 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4072 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4073 # function pointer declarations
4074 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4075 # foo bar; where foo is some local typedef or #define
4076 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4077 # known declaration macros
4078 $pl =~ /^\+\s+$declaration_macros/) &&
4079 # for "else if" which can look like "$Ident $Ident"
4080 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4081 # other possible extensions of declaration lines
4082 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4083 # not starting a section or a macro "\" extended line
4084 $pl =~ /(?:\{\s*|\\)$/) &&
4085 # looks like a declaration
4086 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4087 # function pointer declarations
4088 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4089 # foo bar; where foo is some local typedef or #define
4090 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4091 # known declaration macros
4092 $sl =~ /^\+\s+$declaration_macros/ ||
4093 # start of struct or union or enum
4094 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4095 # start or end of block or continuation of declaration
4096 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4097 # bitfield continuation
4098 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4099 # other possible extensions of declaration lines
4100 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4101 if (WARN("LINE_SPACING",
4102 "Missing a blank line after declarations\n" . $hereprev) &&
4104 fix_insert_line($fixlinenr, "\+");
4109 # check for spaces at the beginning of a line.
4111 # 1) within comments
4112 # 2) indented preprocessor commands
4114 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4115 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4116 if (WARN("LEADING_SPACE",
4117 "please, no spaces at the start of a line\n" . $herevet) &&
4119 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4123 # check we are in a valid C source file if not then ignore this hunk
4124 next if ($realfile !~ /\.(h|c)$/);
4126 # check for unusual line ending [ or (
4127 if ($line =~ /^\+.*([\[\(])\s*$/) {
4128 CHK("OPEN_ENDED_LINE",
4129 "Lines should not end with a '$1'\n" . $herecurr);
4132 # check if this appears to be the start function declaration, save the name
4133 if ($sline =~ /^\+\{\s*$/ &&
4134 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4135 $context_function = $1;
4138 # check if this appears to be the end of function declaration
4139 if ($sline =~ /^\+\}\s*$/) {
4140 undef $context_function;
4143 # check indentation of any line with a bare else
4144 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4145 # if the previous line is a break or return and is indented 1 tab more...
4146 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4147 my $tabs = length($1) + 1;
4148 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4149 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4150 defined $lines[$linenr] &&
4151 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4152 WARN("UNNECESSARY_ELSE",
4153 "else is not generally useful after a break or return\n" . $hereprev);
4157 # check indentation of a line with a break;
4158 # if the previous line is a goto, return or break
4159 # and is indented the same # of tabs
4160 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4162 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4163 if (WARN("UNNECESSARY_BREAK",
4164 "break is not useful after a $1\n" . $hereprev) &&
4166 fix_delete_line($fixlinenr, $rawline);
4171 # check for RCS/CVS revision markers
4172 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4174 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4177 # check for old HOTPLUG __dev<foo> section markings
4178 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4179 WARN("HOTPLUG_SECTION",
4180 "Using $1 is unnecessary\n" . $herecurr);
4183 # Check for potential 'bare' types
4184 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4186 #print "LINE<$line>\n";
4187 if ($linenr > $suppress_statement &&
4188 $realcnt && $sline =~ /.\s*\S/) {
4189 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4190 ctx_statement_block($linenr, $realcnt, 0);
4191 $stat =~ s/\n./\n /g;
4192 $cond =~ s/\n./\n /g;
4194 #print "linenr<$linenr> <$stat>\n";
4195 # If this statement has no statement boundaries within
4196 # it there is no point in retrying a statement scan
4197 # until we hit end of it.
4198 my $frag = $stat; $frag =~ s/;+\s*$//;
4199 if ($frag !~ /(?:{|;)/) {
4200 #print "skip<$line_nr_next>\n";
4201 $suppress_statement = $line_nr_next;
4204 # Find the real next line.
4205 $realline_next = $line_nr_next;
4206 if (defined $realline_next &&
4207 (!defined $lines[$realline_next - 1] ||
4208 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4215 # Ignore goto labels.
4216 if ($s =~ /$Ident:\*$/s) {
4218 # Ignore functions being called
4219 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4221 } elsif ($s =~ /^.\s*else\b/s) {
4223 # declarations always start with types
4224 } 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) {
4227 possible($type, "A:" . $s);
4229 # definitions in global scope can only start with types
4230 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4231 possible($1, "B:" . $s);
4234 # any (foo ... *) is a pointer cast, and foo is a type
4235 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4236 possible($1, "C:" . $s);
4239 # Check for any sort of function declaration.
4240 # int foo(something bar, other baz);
4241 # void (*store_gdt)(x86_descr_ptr *);
4242 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4243 my ($name_len) = length($1);
4246 substr($ctx, 0, $name_len + 1, '');
4247 $ctx =~ s/\)[^\)]*$//;
4249 for my $arg (split(/\s*,\s*/, $ctx)) {
4250 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4252 possible($1, "D:" . $s);
4260 # Checks which may be anchored in the context.
4263 # Check for switch () and associated case and default
4264 # statements should be at the same indent.
4265 if ($line=~/\bswitch\s*\(.*\)/) {
4268 my @ctx = ctx_block_outer($linenr, $realcnt);
4270 for my $ctx (@ctx) {
4271 my ($clen, $cindent) = line_stats($ctx);
4272 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4273 $indent != $cindent) {
4274 $err .= "$sep$ctx\n";
4281 ERROR("SWITCH_CASE_INDENT_LEVEL",
4282 "switch and case should be at the same indent\n$hereline$err");
4286 # if/while/etc brace do not go on next line, unless defining a do while loop,
4287 # or if that brace on the next line is for something else
4288 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4289 my $pre_ctx = "$1$2";
4291 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4293 # OpenOCD specific: Begin: replace s/6/10/
4294 if ($line =~ /^\+\t{10,}/) {
4295 # OpenOCD specific: End
4296 WARN("DEEP_INDENTATION",
4297 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4300 my $ctx_cnt = $realcnt - $#ctx - 1;
4301 my $ctx = join("\n", @ctx);
4303 my $ctx_ln = $linenr;
4304 my $ctx_skip = $realcnt;
4306 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4307 defined $lines[$ctx_ln - 1] &&
4308 $lines[$ctx_ln - 1] =~ /^-/)) {
4309 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4310 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4314 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4315 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4317 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4319 "that open brace { should be on the previous line\n" .
4320 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4322 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4323 $ctx =~ /\)\s*\;\s*$/ &&
4324 defined $lines[$ctx_ln - 1])
4326 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4327 if ($nindent > $indent) {
4328 WARN("TRAILING_SEMICOLON",
4329 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4330 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4335 # Check relative indent for conditionals and blocks.
4336 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4337 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4338 ctx_statement_block($linenr, $realcnt, 0)
4339 if (!defined $stat);
4340 my ($s, $c) = ($stat, $cond);
4342 substr($s, 0, length($c), '');
4344 # remove inline comments
4348 # Find out how long the conditional actually is.
4349 my @newlines = ($c =~ /\n/gs);
4350 my $cond_lines = 1 + $#newlines;
4352 # Make sure we remove the line prefixes as we have
4353 # none on the first line, and are going to readd them
4356 while ($s =~ /\n\s+\\\n/) {
4357 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4360 # We want to check the first line inside the block
4361 # starting at the end of the conditional, so remove:
4362 # 1) any blank line termination
4363 # 2) any opening brace { on end of the line
4365 my $continuation = 0;
4367 $s =~ s/^.*\bdo\b//;
4369 if ($s =~ s/^\s*\\//) {
4372 if ($s =~ s/^\s*?\n//) {
4377 # Also ignore a loop construct at the end of a
4378 # preprocessor statement.
4379 if (($prevline =~ /^.\s*#\s*define\s/ ||
4380 $prevline =~ /\\\s*$/) && $continuation == 0) {
4386 while ($cond_ptr != $cond_lines) {
4387 $cond_ptr = $cond_lines;
4389 # If we see an #else/#elif then the code
4391 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4396 # 1) blank lines, they should be at 0,
4397 # 2) preprocessor lines, and
4399 if ($continuation ||
4401 $s =~ /^\s*#\s*?/ ||
4402 $s =~ /^\s*$Ident\s*:/) {
4403 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4404 if ($s =~ s/^.*?\n//) {
4410 my (undef, $sindent) = line_stats("+" . $s);
4411 my $stat_real = raw_line($linenr, $cond_lines);
4413 # Check if either of these lines are modified, else
4414 # this is not this patch's fault.
4415 if (!defined($stat_real) ||
4416 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4419 if (defined($stat_real) && $cond_lines > 1) {
4420 $stat_real = "[...]\n$stat_real";
4423 #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";
4425 if ($check && $s ne '' &&
4426 (($sindent % $tabsize) != 0 ||
4427 ($sindent < $indent) ||
4428 ($sindent == $indent &&
4429 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4430 ($sindent > $indent + $tabsize))) {
4431 WARN("SUSPECT_CODE_INDENT",
4432 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4436 # Track the 'values' across context and added lines.
4437 my $opline = $line; $opline =~ s/^./ /;
4438 my ($curr_values, $curr_vars) =
4439 annotate_values($opline . "\n", $prev_values);
4440 $curr_values = $prev_values . $curr_values;
4442 my $outline = $opline; $outline =~ s/\t/ /g;
4443 print "$linenr > .$outline\n";
4444 print "$linenr > $curr_values\n";
4445 print "$linenr > $curr_vars\n";
4447 $prev_values = substr($curr_values, -1);
4449 #ignore lines not being added
4450 next if ($line =~ /^[^\+]/);
4452 # check for self assignments used to avoid compiler warnings
4453 # e.g.: int foo = foo, *bar = NULL;
4454 # struct foo bar = *(&(bar));
4455 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4457 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4458 WARN("SELF_ASSIGNMENT",
4459 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4463 # check for dereferences that span multiple lines
4464 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4465 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4466 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4468 $line =~ /^.\s*($Lval)/;
4471 WARN("MULTILINE_DEREFERENCE",
4472 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4475 # check for declarations of signed or unsigned without int
4476 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4479 $var = "" if (!defined $var);
4480 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4484 $pointer = "" if (!defined $pointer);
4486 if (WARN("UNSPECIFIED_INT",
4487 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4489 my $decl = trim($sign) . " int ";
4490 my $comp_pointer = $pointer;
4491 $comp_pointer =~ s/\s//g;
4492 $decl .= $comp_pointer;
4493 $decl = rtrim($decl) if ($var eq "");
4494 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4499 # TEST: allow direct testing of the type matcher.
4501 if ($line =~ /^.\s*$Declare\s*$/) {
4503 "TEST: is type\n" . $herecurr);
4504 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4505 ERROR("TEST_NOT_TYPE",
4506 "TEST: is not type ($1 is)\n". $herecurr);
4510 # TEST: allow direct testing of the attribute matcher.
4512 if ($line =~ /^.\s*$Modifier\s*$/) {
4514 "TEST: is attr\n" . $herecurr);
4515 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4516 ERROR("TEST_NOT_ATTR",
4517 "TEST: is not attr ($1 is)\n". $herecurr);
4522 # check for initialisation to aggregates open brace on the next line
4523 if ($line =~ /^.\s*{/ &&
4524 $prevline =~ /(?:^|[^=])=\s*$/) {
4525 if (ERROR("OPEN_BRACE",
4526 "that open brace { should be on the previous line\n" . $hereprev) &&
4527 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4528 fix_delete_line($fixlinenr - 1, $prevrawline);
4529 fix_delete_line($fixlinenr, $rawline);
4530 my $fixedline = $prevrawline;
4531 $fixedline =~ s/\s*=\s*$/ = {/;
4532 fix_insert_line($fixlinenr, $fixedline);
4534 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4535 fix_insert_line($fixlinenr, $fixedline);
4540 # Checks which are anchored on the added line.
4543 # check for malformed paths in #include statements (uses RAW line)
4544 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4546 if ($path =~ m{//}) {
4547 ERROR("MALFORMED_INCLUDE",
4548 "malformed #include filename\n" . $herecurr);
4550 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4551 ERROR("UAPI_INCLUDE",
4552 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4556 # no C99 // comments
4557 if ($line =~ m{//}) {
4558 if (ERROR("C99_COMMENTS",
4559 "do not use C99 // comments\n" . $herecurr) &&
4561 my $line = $fixed[$fixlinenr];
4562 if ($line =~ /\/\/(.*)$/) {
4563 my $comment = trim($1);
4564 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4568 # Remove C99 comments.
4570 $opline =~ s@//.*@@;
4572 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4573 # the whole statement.
4574 #print "APW <$lines[$realline_next - 1]>\n";
4575 if (defined $realline_next &&
4576 exists $lines[$realline_next - 1] &&
4577 !defined $suppress_export{$realline_next} &&
4578 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4579 # Handle definitions which produce identifiers with
4582 # EXPORT_SYMBOL(something_foo);
4584 $name =~ s/^\s*($Ident).*/$1/;
4585 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4586 $name =~ /^${Ident}_$2/) {
4587 #print "FOO C name<$name>\n";
4588 $suppress_export{$realline_next} = 1;
4590 } elsif ($stat !~ /(?:
4592 ^.DEFINE_$Ident\(\Q$name\E\)|
4593 ^.DECLARE_$Ident\(\Q$name\E\)|
4594 ^.LIST_HEAD\(\Q$name\E\)|
4595 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4596 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4598 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4599 $suppress_export{$realline_next} = 2;
4601 $suppress_export{$realline_next} = 1;
4604 if (!defined $suppress_export{$linenr} &&
4605 $prevline =~ /^.\s*$/ &&
4606 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4607 #print "FOO B <$lines[$linenr - 1]>\n";
4608 $suppress_export{$linenr} = 2;
4610 if (defined $suppress_export{$linenr} &&
4611 $suppress_export{$linenr} == 2) {
4612 WARN("EXPORT_SYMBOL",
4613 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4616 # check for global initialisers.
4617 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4618 !exclude_global_initialisers($realfile)) {
4619 if (ERROR("GLOBAL_INITIALISERS",
4620 "do not initialise globals to $1\n" . $herecurr) &&
4622 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4625 # check for static initialisers.
4626 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4627 if (ERROR("INITIALISED_STATIC",
4628 "do not initialise statics to $1\n" .
4631 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4635 # check for misordered declarations of char/short/int/long with signed/unsigned
4636 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4638 WARN("MISORDERED_TYPE",
4639 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4642 # check for unnecessary <signed> int declarations of short/long/long long
4643 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4644 my $type = trim($1);
4645 next if ($type !~ /\bint\b/);
4646 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4647 my $new_type = $type;
4648 $new_type =~ s/\b\s*int\s*\b/ /;
4649 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4650 $new_type =~ s/^const\s+//;
4651 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4652 $new_type = "const $new_type" if ($type =~ /^const\b/);
4653 $new_type =~ s/\s+/ /g;
4654 $new_type = trim($new_type);
4655 if (WARN("UNNECESSARY_INT",
4656 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4658 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4662 # check for static const char * arrays.
4663 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4664 WARN("STATIC_CONST_CHAR_ARRAY",
4665 "static const char * array should probably be static const char * const\n" .
4669 # check for initialized const char arrays that should be static const
4670 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4671 if (WARN("STATIC_CONST_CHAR_ARRAY",
4672 "const array should probably be static const\n" . $herecurr) &&
4674 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4678 # check for static char foo[] = "bar" declarations.
4679 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4680 WARN("STATIC_CONST_CHAR_ARRAY",
4681 "static char array declaration should probably be static const char\n" .
4685 # check for const <foo> const where <foo> is not a pointer or array type
4686 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4688 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4690 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4691 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4693 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4697 # check for const static or static <non ptr type> const declarations
4698 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4699 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4700 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4701 if (WARN("STATIC_CONST",
4702 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4704 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4705 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4709 # check for non-global char *foo[] = {"bar", ...} declarations.
4710 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4711 WARN("STATIC_CONST_CHAR_ARRAY",
4712 "char * array declaration might be better as static const\n" .
4716 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4717 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4719 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4721 if (WARN("ARRAY_SIZE",
4722 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4724 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4729 # check for function declarations without arguments like "int foo()"
4730 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4731 if (ERROR("FUNCTION_WITHOUT_ARGS",
4732 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4734 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4738 # check for new typedefs, only function parameters and sparse annotations
4740 if ($line =~ /\btypedef\s/ &&
4741 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4742 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4743 $line !~ /\b$typeTypedefs\b/ &&
4744 $line !~ /\b__bitwise\b/) {
4745 WARN("NEW_TYPEDEFS",
4746 "do not add new typedefs\n" . $herecurr);
4749 # * goes on variable not on type
4751 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4753 my ($ident, $from, $to) = ($1, $2, $2);
4755 # Should start with a space.
4756 $to =~ s/^(\S)/ $1/;
4757 # Should not end with a space.
4759 # '*'s should not have spaces between.
4760 while ($to =~ s/\*\s+\*/\*\*/) {
4763 ## print "1: from<$from> to<$to> ident<$ident>\n";
4765 if (ERROR("POINTER_LOCATION",
4766 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4768 my $sub_from = $ident;
4769 my $sub_to = $ident;
4770 $sub_to =~ s/\Q$from\E/$to/;
4771 $fixed[$fixlinenr] =~
4772 s@\Q$sub_from\E@$sub_to@;
4776 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4778 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4780 # Should start with a space.
4781 $to =~ s/^(\S)/ $1/;
4782 # Should not end with a space.
4784 # '*'s should not have spaces between.
4785 while ($to =~ s/\*\s+\*/\*\*/) {
4787 # Modifiers should have spaces.
4788 $to =~ s/(\b$Modifier$)/$1 /;
4790 ## print "2: from<$from> to<$to> ident<$ident>\n";
4791 if ($from ne $to && $ident !~ /^$Modifier$/) {
4792 if (ERROR("POINTER_LOCATION",
4793 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4796 my $sub_from = $match;
4797 my $sub_to = $match;
4798 $sub_to =~ s/\Q$from\E/$to/;
4799 $fixed[$fixlinenr] =~
4800 s@\Q$sub_from\E@$sub_to@;
4805 # avoid BUG() or BUG_ON()
4806 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4807 my $msg_level = \&WARN;
4808 $msg_level = \&CHK if ($file);
4809 &{$msg_level}("AVOID_BUG",
4810 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4813 # avoid LINUX_VERSION_CODE
4814 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4815 WARN("LINUX_VERSION_CODE",
4816 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4819 # check for uses of printk_ratelimit
4820 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4821 WARN("PRINTK_RATELIMITED",
4822 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4825 # printk should use KERN_* levels
4826 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4827 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4828 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4831 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4832 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4836 $modifier = "" if (!defined($modifier));
4837 my $level = lc($orig);
4838 $level = "warn" if ($level eq "warning");
4839 my $level2 = $level;
4840 $level2 = "dbg" if ($level eq "debug");
4841 $level .= $modifier;
4842 $level2 .= $modifier;
4843 WARN("PREFER_PR_LEVEL",
4844 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4847 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4848 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4850 my $level = lc($orig);
4851 $level = "warn" if ($level eq "warning");
4852 $level = "dbg" if ($level eq "debug");
4853 WARN("PREFER_DEV_LEVEL",
4854 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4857 # trace_printk should not be used in production code.
4858 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4859 WARN("TRACE_PRINTK",
4860 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4863 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4864 # number of false positives, but assembly files are not checked, so at
4865 # least the arch entry code will not trigger this warning.
4866 if ($line =~ /\bENOSYS\b/) {
4868 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4871 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4872 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4873 # Similarly to ENOSYS warning a small number of false positives is expected.
4874 if (!$file && $line =~ /\bENOTSUPP\b/) {
4875 if (WARN("ENOTSUPP",
4876 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4878 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4882 # function brace can't be on same line, except for #defines of do while,
4883 # or if closed on same line
4884 if ($perl_version_ok &&
4885 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4886 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4888 if (ERROR("OPEN_BRACE",
4889 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4891 fix_delete_line($fixlinenr, $rawline);
4892 my $fixed_line = $rawline;
4893 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4896 fix_insert_line($fixlinenr, ltrim($line1));
4897 fix_insert_line($fixlinenr, "\+{");
4898 if ($line2 !~ /^\s*$/) {
4899 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4904 # open braces for enum, union and struct go on the same line.
4905 if ($line =~ /^.\s*{/ &&
4906 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4907 if (ERROR("OPEN_BRACE",
4908 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4909 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4910 fix_delete_line($fixlinenr - 1, $prevrawline);
4911 fix_delete_line($fixlinenr, $rawline);
4912 my $fixedline = rtrim($prevrawline) . " {";
4913 fix_insert_line($fixlinenr, $fixedline);
4914 $fixedline = $rawline;
4915 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4916 if ($fixedline !~ /^\+\s*$/) {
4917 fix_insert_line($fixlinenr, $fixedline);
4922 # missing space after union, struct or enum definition
4923 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4925 "missing space after $1 definition\n" . $herecurr) &&
4927 $fixed[$fixlinenr] =~
4928 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4932 # Function pointer declarations
4933 # check spacing between type, funcptr, and args
4934 # canonical declaration is "type (*funcptr)(args...)"
4935 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4937 my $pre_pointer_space = $2;
4938 my $post_pointer_space = $3;
4940 my $post_funcname_space = $5;
4941 my $pre_args_space = $6;
4943 # the $Declare variable will capture all spaces after the type
4944 # so check it for a missing trailing missing space but pointer return types
4945 # don't need a space so don't warn for those.
4946 my $post_declare_space = "";
4947 if ($declare =~ /(\s+)$/) {
4948 $post_declare_space = $1;
4949 $declare = rtrim($declare);
4951 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4953 "missing space after return type\n" . $herecurr);
4954 $post_declare_space = " ";
4957 # unnecessary space "type (*funcptr)(args...)"
4958 # This test is not currently implemented because these declarations are
4960 # int foo(int bar, ...)
4961 # and this is form shouldn't/doesn't generate a checkpatch warning.
4963 # elsif ($declare =~ /\s{2,}$/) {
4965 # "Multiple spaces after return type\n" . $herecurr);
4968 # unnecessary space "type ( *funcptr)(args...)"
4969 if (defined $pre_pointer_space &&
4970 $pre_pointer_space =~ /^\s/) {
4972 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4975 # unnecessary space "type (* funcptr)(args...)"
4976 if (defined $post_pointer_space &&
4977 $post_pointer_space =~ /^\s/) {
4979 "Unnecessary space before function pointer name\n" . $herecurr);
4982 # unnecessary space "type (*funcptr )(args...)"
4983 if (defined $post_funcname_space &&
4984 $post_funcname_space =~ /^\s/) {
4986 "Unnecessary space after function pointer name\n" . $herecurr);
4989 # unnecessary space "type (*funcptr) (args...)"
4990 if (defined $pre_args_space &&
4991 $pre_args_space =~ /^\s/) {
4993 "Unnecessary space before function pointer arguments\n" . $herecurr);
4996 if (show_type("SPACING") && $fix) {
4997 $fixed[$fixlinenr] =~
4998 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5002 # check for spacing round square brackets; allowed:
5003 # 1. with a type on the left -- int [] a;
5004 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5005 # 3. inside a curly brace -- = { [0...10] = 5 }
5006 while ($line =~ /(.*?\s)\[/g) {
5007 my ($where, $prefix) = ($-[1], $1);
5008 if ($prefix !~ /$Type\s+$/ &&
5009 ($where != 0 || $prefix !~ /^.\s+$/) &&
5010 $prefix !~ /[{,:]\s+$/) {
5011 if (ERROR("BRACKET_SPACE",
5012 "space prohibited before open square bracket '['\n" . $herecurr) &&
5014 $fixed[$fixlinenr] =~
5015 s/^(\+.*?)\s+\[/$1\[/;
5020 # check for spaces between functions and their parentheses.
5021 while ($line =~ /($Ident)\s+\(/g) {
5023 my $ctx_before = substr($line, 0, $-[1]);
5024 my $ctx = "$ctx_before$name";
5026 # Ignore those directives where spaces _are_ permitted.
5028 if|for|while|switch|return|case|
5029 volatile|__volatile__|
5030 __attribute__|format|__extension__|
5033 # cpp #define statements have non-optional spaces, ie
5034 # if there is a space between the name and the open
5035 # parenthesis it is simply not a parameter group.
5036 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5038 # cpp #elif statement condition may start with a (
5039 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5041 # If this whole things ends with a type its most
5042 # likely a typedef for a function.
5043 } elsif ($ctx =~ /$Type$/) {
5047 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5049 $fixed[$fixlinenr] =~
5050 s/\b$name\s+\(/$name\(/;
5055 # Check operator spacing.
5056 if (!($line=~/\#\s*include/)) {
5057 my $fixed_line = "";
5061 <<=|>>=|<=|>=|==|!=|
5062 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5063 =>|->|<<|>>|<|>|=|!|~|
5064 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5067 my @elements = split(/($ops|;)/, $opline);
5069 ## print("element count: <" . $#elements . ">\n");
5070 ## foreach my $el (@elements) {
5071 ## print("el: <$el>\n");
5074 my @fix_elements = ();
5077 foreach my $el (@elements) {
5078 push(@fix_elements, substr($rawline, $off, length($el)));
5079 $off += length($el);
5084 my $blank = copy_spacing($opline);
5085 my $last_after = -1;
5087 for (my $n = 0; $n < $#elements; $n += 2) {
5089 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5091 ## print("n: <$n> good: <$good>\n");
5093 $off += length($elements[$n]);
5095 # Pick up the preceding and succeeding characters.
5096 my $ca = substr($opline, 0, $off);
5098 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5099 $cc = substr($opline, $off + length($elements[$n + 1]));
5101 my $cb = "$ca$;$cc";
5104 $a = 'V' if ($elements[$n] ne '');
5105 $a = 'W' if ($elements[$n] =~ /\s$/);
5106 $a = 'C' if ($elements[$n] =~ /$;$/);
5107 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5108 $a = 'O' if ($elements[$n] eq '');
5109 $a = 'E' if ($ca =~ /^\s*$/);
5111 my $op = $elements[$n + 1];
5114 if (defined $elements[$n + 2]) {
5115 $c = 'V' if ($elements[$n + 2] ne '');
5116 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5117 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5118 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5119 $c = 'O' if ($elements[$n + 2] eq '');
5120 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5125 my $ctx = "${a}x${c}";
5127 my $at = "(ctx:$ctx)";
5129 my $ptr = substr($blank, 0, $off) . "^";
5130 my $hereptr = "$hereline$ptr\n";
5132 # Pull out the value of this operator.
5133 my $op_type = substr($curr_values, $off + 1, 1);
5135 # Get the full operator variant.
5136 my $opv = $op . substr($curr_vars, $off, 1);
5138 # Ignore operators passed as parameters.
5139 if ($op_type ne 'V' &&
5140 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5143 # } elsif ($op =~ /^$;+$/) {
5145 # ; should have either the end of line or a space or \ after it
5146 } elsif ($op eq ';') {
5147 if ($ctx !~ /.x[WEBC]/ &&
5148 $cc !~ /^\\/ && $cc !~ /^;/) {
5149 if (ERROR("SPACING",
5150 "space required after that '$op' $at\n" . $hereptr)) {
5151 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5157 } elsif ($op eq '//') {
5159 # : when part of a bitfield
5160 } elsif ($opv eq ':B') {
5161 # skip the bitfield test for now
5165 } elsif ($op eq '->') {
5166 if ($ctx =~ /Wx.|.xW/) {
5167 if (ERROR("SPACING",
5168 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5169 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5170 if (defined $fix_elements[$n + 2]) {
5171 $fix_elements[$n + 2] =~ s/^\s+//;
5177 # , must not have a space before and must have a space on the right.
5178 } elsif ($op eq ',') {
5179 my $rtrim_before = 0;
5180 my $space_after = 0;
5181 if ($ctx =~ /Wx./) {
5182 if (ERROR("SPACING",
5183 "space prohibited before that '$op' $at\n" . $hereptr)) {
5188 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5189 if (ERROR("SPACING",
5190 "space required after that '$op' $at\n" . $hereptr)) {
5196 if ($rtrim_before || $space_after) {
5197 if ($rtrim_before) {
5198 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5200 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5207 # '*' as part of a type definition -- reported already.
5208 } elsif ($opv eq '*_') {
5209 #warn "'*' is part of type\n";
5211 # unary operators should have a space before and
5212 # none after. May be left adjacent to another
5213 # unary operator, or a cast
5214 } elsif ($op eq '!' || $op eq '~' ||
5215 $opv eq '*U' || $opv eq '-U' ||
5216 $opv eq '&U' || $opv eq '&&U') {
5217 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5218 if (ERROR("SPACING",
5219 "space required before that '$op' $at\n" . $hereptr)) {
5220 if ($n != $last_after + 2) {
5221 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5226 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5227 # A unary '*' may be const
5229 } elsif ($ctx =~ /.xW/) {
5230 if (ERROR("SPACING",
5231 "space prohibited after that '$op' $at\n" . $hereptr)) {
5232 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5233 if (defined $fix_elements[$n + 2]) {
5234 $fix_elements[$n + 2] =~ s/^\s+//;
5240 # unary ++ and unary -- are allowed no space on one side.
5241 } elsif ($op eq '++' or $op eq '--') {
5242 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5243 if (ERROR("SPACING",
5244 "space required one side of that '$op' $at\n" . $hereptr)) {
5245 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5249 if ($ctx =~ /Wx[BE]/ ||
5250 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5251 if (ERROR("SPACING",
5252 "space prohibited before that '$op' $at\n" . $hereptr)) {
5253 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5257 if ($ctx =~ /ExW/) {
5258 if (ERROR("SPACING",
5259 "space prohibited after that '$op' $at\n" . $hereptr)) {
5260 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5261 if (defined $fix_elements[$n + 2]) {
5262 $fix_elements[$n + 2] =~ s/^\s+//;
5268 # << and >> may either have or not have spaces both sides
5269 } elsif ($op eq '<<' or $op eq '>>' or
5270 $op eq '&' or $op eq '^' or $op eq '|' or
5271 $op eq '+' or $op eq '-' or
5272 $op eq '*' or $op eq '/' or
5276 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5278 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5279 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5280 $fix_elements[$n + 2] =~ s/^\s+//;
5283 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5285 "space preferred before that '$op' $at\n" . $hereptr)) {
5286 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5290 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5291 if (ERROR("SPACING",
5292 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5293 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5294 if (defined $fix_elements[$n + 2]) {
5295 $fix_elements[$n + 2] =~ s/^\s+//;
5301 # A colon needs no spaces before when it is
5302 # terminating a case value or a label.
5303 } elsif ($opv eq ':C' || $opv eq ':L') {
5304 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5305 if (ERROR("SPACING",
5306 "space prohibited before that '$op' $at\n" . $hereptr)) {
5307 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5312 # All the others need spaces both sides.
5313 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5316 # Ignore email addresses <foo@bar>
5318 $cc =~ /^\S+\@\S+>/) ||
5320 $ca =~ /<\S+\@\S+$/))
5325 # for asm volatile statements
5326 # ignore a colon with another
5327 # colon immediately before or after
5329 ($ca =~ /:$/ || $cc =~ /^:/)) {
5333 # messages are ERROR, but ?: are CHK
5335 my $msg_level = \&ERROR;
5336 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5338 if (&{$msg_level}("SPACING",
5339 "spaces required around that '$op' $at\n" . $hereptr)) {
5340 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5341 if (defined $fix_elements[$n + 2]) {
5342 $fix_elements[$n + 2] =~ s/^\s+//;
5348 $off += length($elements[$n + 1]);
5350 ## print("n: <$n> GOOD: <$good>\n");
5352 $fixed_line = $fixed_line . $good;
5355 if (($#elements % 2) == 0) {
5356 $fixed_line = $fixed_line . $fix_elements[$#elements];
5359 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5360 $fixed[$fixlinenr] = $fixed_line;
5366 # check for whitespace before a non-naked semicolon
5367 if ($line =~ /^\+.*\S\s+;\s*$/) {
5369 "space prohibited before semicolon\n" . $herecurr) &&
5371 1 while $fixed[$fixlinenr] =~
5372 s/^(\+.*\S)\s+;/$1;/;
5376 # check for multiple assignments
5377 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5378 CHK("MULTIPLE_ASSIGNMENTS",
5379 "multiple assignments should be avoided\n" . $herecurr);
5382 ## # check for multiple declarations, allowing for a function declaration
5384 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5385 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5387 ## # Remove any bracketed sections to ensure we do not
5388 ## # falsely report the parameters of functions.
5390 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5392 ## if ($ln =~ /,/) {
5393 ## WARN("MULTIPLE_DECLARATION",
5394 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5398 #need space before brace following if, while, etc
5399 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5400 $line =~ /\b(?:else|do)\{/) {
5401 if (ERROR("SPACING",
5402 "space required before the open brace '{'\n" . $herecurr) &&
5404 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5408 ## # check for blank lines before declarations
5409 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5410 ## $prevrawline =~ /^.\s*$/) {
5412 ## "No blank lines before declarations\n" . $hereprev);
5416 # closing brace should have a space following it when it has anything
5418 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5419 if (ERROR("SPACING",
5420 "space required after that close brace '}'\n" . $herecurr) &&
5422 $fixed[$fixlinenr] =~
5423 s/}((?!(?:,|;|\)))\S)/} $1/;
5427 # check spacing on square brackets
5428 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5429 if (ERROR("SPACING",
5430 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5432 $fixed[$fixlinenr] =~
5436 if ($line =~ /\s\]/) {
5437 if (ERROR("SPACING",
5438 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5440 $fixed[$fixlinenr] =~
5445 # check spacing on parentheses
5446 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5447 $line !~ /for\s*\(\s+;/) {
5448 if (ERROR("SPACING",
5449 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5451 $fixed[$fixlinenr] =~
5455 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5456 $line !~ /for\s*\(.*;\s+\)/ &&
5457 $line !~ /:\s+\)/) {
5458 if (ERROR("SPACING",
5459 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5461 $fixed[$fixlinenr] =~
5466 # check unnecessary parentheses around addressof/dereference single $Lvals
5467 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5469 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5471 if (CHK("UNNECESSARY_PARENTHESES",
5472 "Unnecessary parentheses around $var\n" . $herecurr) &&
5474 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5478 # check for unnecessary parentheses around function pointer uses
5479 # ie: (foo->bar)(); should be foo->bar();
5480 # but not "if (foo->bar) (" to avoid some false positives
5481 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5483 if (CHK("UNNECESSARY_PARENTHESES",
5484 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5486 my $var2 = deparenthesize($var);
5488 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5492 # check for unnecessary parentheses around comparisons in if uses
5493 # when !drivers/staging or command-line uses --strict
5494 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5495 $perl_version_ok && defined($stat) &&
5496 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5498 my $test = substr($2, 1, -1);
5500 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5502 # avoid parentheses around potential macro args
5503 next if ($match =~ /^\s*\w+\s*$/);
5504 if (!defined($herectx)) {
5505 $herectx = $here . "\n";
5506 my $cnt = statement_rawlines($if_stat);
5507 for (my $n = 0; $n < $cnt; $n++) {
5508 my $rl = raw_line($linenr, $n);
5509 $herectx .= $rl . "\n";
5510 last if $rl =~ /^[ \+].*\{/;
5513 CHK("UNNECESSARY_PARENTHESES",
5514 "Unnecessary parentheses around '$match'\n" . $herectx);
5518 # check that goto labels aren't indented (allow a single space indentation)
5519 # and ignore bitfield definitions like foo:1
5520 # Strictly, labels can have whitespace after the identifier and before the :
5521 # but this is not allowed here as many ?: uses would appear to be labels
5522 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5523 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5524 $sline !~ /^.\s+default:/) {
5525 if (WARN("INDENTED_LABEL",
5526 "labels should not be indented\n" . $herecurr) &&
5528 $fixed[$fixlinenr] =~
5533 # check if a statement with a comma should be two statements like:
5534 # foo = bar(), /* comma should be semicolon */
5536 if (defined($stat) &&
5537 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5538 my $cnt = statement_rawlines($stat);
5539 my $herectx = get_stat_here($linenr, $cnt, $here);
5540 WARN("SUSPECT_COMMA_SEMICOLON",
5541 "Possible comma where semicolon could be used\n" . $herectx);
5544 # return is not a function
5545 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5547 if ($perl_version_ok &&
5548 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5550 $value = deparenthesize($value);
5551 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5552 ERROR("RETURN_PARENTHESES",
5553 "return is not a function, parentheses are not required\n" . $herecurr);
5555 } elsif ($spacing !~ /\s+/) {
5557 "space required before the open parenthesis '('\n" . $herecurr);
5561 # unnecessary return in a void function
5562 # at end-of-function, with the previous line a single leading tab, then return;
5563 # and the line before that not a goto label target like "out:"
5564 if ($sline =~ /^[ \+]}\s*$/ &&
5565 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5567 $lines[$linenr - 3] =~ /^[ +]/ &&
5568 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5570 "void function return statements are not generally useful\n" . $hereprev);
5573 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5574 if ($perl_version_ok &&
5575 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5576 my $openparens = $1;
5577 my $count = $openparens =~ tr@\(@\(@;
5579 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5580 my $comp = $4; #Not $1 because of $LvalOrFunc
5581 $msg = " - maybe == should be = ?" if ($comp eq "==");
5582 WARN("UNNECESSARY_PARENTHESES",
5583 "Unnecessary parentheses$msg\n" . $herecurr);
5587 # comparisons with a constant or upper case identifier on the left
5588 # avoid cases like "foo + BAR < baz"
5589 # only fix matches surrounded by parentheses to avoid incorrect
5590 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5591 if ($perl_version_ok &&
5592 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5597 my $newcomp = $comp;
5598 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5599 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5600 WARN("CONSTANT_COMPARISON",
5601 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5605 } elsif ($comp eq "<=") {
5607 } elsif ($comp eq ">") {
5609 } elsif ($comp eq ">=") {
5612 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5616 # Return of what appears to be an errno should normally be negative
5617 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5619 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5620 WARN("USE_NEGATIVE_ERRNO",
5621 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5625 # Need a space before open parenthesis after if, while etc
5626 if ($line =~ /\b(if|while|for|switch)\(/) {
5627 if (ERROR("SPACING",
5628 "space required before the open parenthesis '('\n" . $herecurr) &&
5630 $fixed[$fixlinenr] =~
5631 s/\b(if|while|for|switch)\(/$1 \(/;
5635 # Check for illegal assignment in if conditional -- and check for trailing
5636 # statements after the conditional.
5637 if ($line =~ /do\s*(?!{)/) {
5638 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5639 ctx_statement_block($linenr, $realcnt, 0)
5640 if (!defined $stat);
5641 my ($stat_next) = ctx_statement_block($line_nr_next,
5642 $remain_next, $off_next);
5643 $stat_next =~ s/\n./\n /g;
5644 ##print "stat<$stat> stat_next<$stat_next>\n";
5646 if ($stat_next =~ /^\s*while\b/) {
5647 # If the statement carries leading newlines,
5648 # then count those as offsets.
5650 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5652 statement_rawlines($whitespace) - 1;
5654 $suppress_whiletrailers{$line_nr_next +
5658 if (!defined $suppress_whiletrailers{$linenr} &&
5659 defined($stat) && defined($cond) &&
5660 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5661 my ($s, $c) = ($stat, $cond);
5662 my $fixed_assign_in_if = 0;
5664 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5665 if (ERROR("ASSIGN_IN_IF",
5666 "do not use assignment in if condition\n" . $herecurr) &&
5667 $fix && $perl_version_ok) {
5668 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5676 fix_delete_line($fixlinenr, $rawline);
5677 fix_insert_line($fixlinenr, "$space$statement;");
5678 my $newline = "${space}if (";
5679 $newline .= '!' if defined($not);
5680 $newline .= '(' if (defined $not && defined($test) && defined($against));
5681 $newline .= "$assigned";
5682 $newline .= " $test $against" if (defined($test) && defined($against));
5683 $newline .= ')' if (defined $not && defined($test) && defined($against));
5685 $newline .= " {" if (defined($brace));
5686 fix_insert_line($fixlinenr + 1, $newline);
5687 $fixed_assign_in_if = 1;
5692 # Find out what is on the end of the line after the
5694 substr($s, 0, length($c), '');
5696 $s =~ s/$;//g; # Remove any comments
5697 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5698 $c !~ /}\s*while\s*/)
5700 # Find out how long the conditional actually is.
5701 my @newlines = ($c =~ /\n/gs);
5702 my $cond_lines = 1 + $#newlines;
5705 $stat_real = raw_line($linenr, $cond_lines)
5706 . "\n" if ($cond_lines);
5707 if (defined($stat_real) && $cond_lines > 1) {
5708 $stat_real = "[...]\n$stat_real";
5711 if (ERROR("TRAILING_STATEMENTS",
5712 "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5713 !$fixed_assign_in_if &&
5715 $fix && $perl_version_ok &&
5716 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5719 my $rest = rtrim($4);
5720 if ($rest =~ /;$/) {
5721 $fixed[$fixlinenr] = "\+$indent$test";
5722 fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5728 # Check for bitwise tests written as boolean
5740 WARN("HEXADECIMAL_BOOLEAN_TEST",
5741 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5744 # if and else should not have general statements after it
5745 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5747 $s =~ s/$;//g; # Remove any comments
5748 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5749 ERROR("TRAILING_STATEMENTS",
5750 "trailing statements should be on next line\n" . $herecurr);
5753 # if should not continue a brace
5754 if ($line =~ /}\s*if\b/) {
5755 ERROR("TRAILING_STATEMENTS",
5756 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5759 # case and default should not have general statements after them
5760 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5762 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5766 ERROR("TRAILING_STATEMENTS",
5767 "trailing statements should be on next line\n" . $herecurr);
5770 # Check for }<nl>else {, these must be at the same
5771 # indent level to be relevant to each other.
5772 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5773 $previndent == $indent) {
5774 if (ERROR("ELSE_AFTER_BRACE",
5775 "else should follow close brace '}'\n" . $hereprev) &&
5776 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5777 fix_delete_line($fixlinenr - 1, $prevrawline);
5778 fix_delete_line($fixlinenr, $rawline);
5779 my $fixedline = $prevrawline;
5780 $fixedline =~ s/}\s*$//;
5781 if ($fixedline !~ /^\+\s*$/) {
5782 fix_insert_line($fixlinenr, $fixedline);
5784 $fixedline = $rawline;
5785 $fixedline =~ s/^(.\s*)else/$1} else/;
5786 fix_insert_line($fixlinenr, $fixedline);
5790 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5791 $previndent == $indent) {
5792 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5794 # Find out what is on the end of the line after the
5796 substr($s, 0, length($c), '');
5799 if ($s =~ /^\s*;/) {
5800 if (ERROR("WHILE_AFTER_BRACE",
5801 "while should follow close brace '}'\n" . $hereprev) &&
5802 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5803 fix_delete_line($fixlinenr - 1, $prevrawline);
5804 fix_delete_line($fixlinenr, $rawline);
5805 my $fixedline = $prevrawline;
5806 my $trailing = $rawline;
5807 $trailing =~ s/^\+//;
5808 $trailing = trim($trailing);
5809 $fixedline =~ s/}\s*$/} $trailing/;
5810 fix_insert_line($fixlinenr, $fixedline);
5815 #Specific variable tests
5816 while ($line =~ m{($Constant|$Lval)}g) {
5821 if ($var !~ /^$Constant$/ &&
5822 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5823 #Ignore some autogenerated defines and enum values
5824 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5825 #Ignore Page<foo> variants
5826 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5827 #Ignore SI style variants like nS, mV and dB
5828 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5829 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5830 #Ignore some three character SI units explicitly, like MiB and KHz
5831 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5834 # OpenOCD Specific: Begin: remove Linux exceptions, extend to camel[0-9_]*CASE
5835 if ($var !~ /^$Constant$/ &&
5836 $var =~ /[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z]/) {
5837 # OpenOCD Specific: End
5838 while ($var =~ m{\b($Ident)}g) {
5841 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5843 # OpenOCD Specific: Begin: extend to camel[0-9_]*CASE
5844 next if ($word !~ /[A-Z][0-9_]*[a-z]|[a-z][0-9_]*[A-Z]/);
5845 # OpenOCD Specific: End
5847 # This will not work for OpenOCD jenkins because it runs
5848 # checkpatch from a tree already patched. Any new camelcase
5849 # in include file will be ignored as it was pre-existing.
5851 seed_camelcase_includes();
5852 if (!$file && !$camelcase_file_seeded) {
5853 seed_camelcase_file($realfile);
5854 $camelcase_file_seeded = 1;
5858 if (!defined $camelcase{$word}) {
5859 $camelcase{$word} = 1;
5861 "Avoid CamelCase: <$word>\n" . $herecurr);
5867 #no spaces allowed after \ in define
5868 if ($line =~ /\#\s*define.*\\\s+$/) {
5869 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5870 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5872 $fixed[$fixlinenr] =~ s/\s+$//;
5876 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5877 # itself <asm/foo.h> (uses RAW line)
5878 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5880 my $checkfile = "include/linux/$file";
5881 if (-f "$root/$checkfile" &&
5882 $realfile ne $checkfile &&
5883 $1 !~ /$allowed_asm_includes/)
5885 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5886 if ($asminclude > 0) {
5887 if ($realfile =~ m{^arch/}) {
5888 CHK("ARCH_INCLUDE_LINUX",
5889 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5891 WARN("INCLUDE_LINUX",
5892 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5898 # multi-statement macros should be enclosed in a do while loop, grab the
5899 # first statement and ensure its the whole macro if its not enclosed
5900 # in a known good container
5901 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5902 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5905 my ($off, $dstat, $dcond, $rest);
5907 my $has_flow_statement = 0;
5908 my $has_arg_concat = 0;
5909 ($dstat, $dcond, $ln, $cnt, $off) =
5910 ctx_statement_block($linenr, $realcnt, 0);
5912 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5913 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5915 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5916 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5918 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5919 my $define_args = $1;
5920 my $define_stmt = $dstat;
5923 if (defined $define_args && $define_args ne "") {
5924 $define_args = substr($define_args, 1, length($define_args) - 2);
5925 $define_args =~ s/\s*//g;
5926 $define_args =~ s/\\\+?//g;
5927 @def_args = split(",", $define_args);
5931 $dstat =~ s/\\\n.//g;
5932 $dstat =~ s/^\s*//s;
5933 $dstat =~ s/\s*$//s;
5935 # Flatten any parentheses and braces
5936 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5937 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5938 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5942 # Flatten any obvious string concatenation.
5943 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5944 $dstat =~ s/$Ident\s*($String)/$1/)
5948 # Make asm volatile uses seem like a generic function
5949 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5951 my $exceptions = qr{
5964 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5967 my $stmt_cnt = statement_rawlines($ctx);
5968 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5971 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5972 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5973 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5974 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5975 $dstat !~ /$exceptions/ &&
5976 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5977 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5978 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5979 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5980 $dstat !~ /^for\s*$Constant$/ && # for (...)
5981 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5982 $dstat !~ /^do\s*{/ && # do {...
5983 $dstat !~ /^\(\{/ && # ({...
5984 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5986 if ($dstat =~ /^\s*if\b/) {
5987 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5988 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5989 } elsif ($dstat =~ /;/) {
5990 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5991 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5993 ERROR("COMPLEX_MACRO",
5994 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5999 # Make $define_stmt single line, comment-free, etc
6000 my @stmt_array = split('\n', $define_stmt);
6003 foreach my $l (@stmt_array) {
6008 } elsif ($l =~ /^[\+ ]/) {
6009 $define_stmt .= substr($l, 1);
6012 $define_stmt =~ s/$;//g;
6013 $define_stmt =~ s/\s+/ /g;
6014 $define_stmt = trim($define_stmt);
6016 # check if any macro arguments are reused (ignore '...' and 'type')
6017 foreach my $arg (@def_args) {
6018 next if ($arg =~ /\.\.\./);
6019 next if ($arg =~ /^type$/i);
6020 my $tmp_stmt = $define_stmt;
6021 $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;
6022 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6023 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
6024 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6026 CHK("MACRO_ARG_REUSE",
6027 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6029 # check if any macro arguments may have other precedence issues
6030 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6031 ((defined($1) && $1 ne ',') ||
6032 (defined($2) && $2 ne ','))) {
6033 CHK("MACRO_ARG_PRECEDENCE",
6034 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6038 # check for macros with flow control, but without ## concatenation
6039 # ## concatenation is commonly a macro that defines a function so ignore those
6040 if ($has_flow_statement && !$has_arg_concat) {
6041 my $cnt = statement_rawlines($ctx);
6042 my $herectx = get_stat_here($linenr, $cnt, $here);
6044 WARN("MACRO_WITH_FLOW_CONTROL",
6045 "Macros with flow control statements should be avoided\n" . "$herectx");
6048 # check for line continuations outside of #defines, preprocessor #, and asm
6051 if ($prevline !~ /^..*\\$/ &&
6052 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6053 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
6054 $line =~ /^\+.*\\$/) {
6055 WARN("LINE_CONTINUATIONS",
6056 "Avoid unnecessary line continuations\n" . $herecurr);
6060 # do {} while (0) macro tests:
6061 # single-statement macros do not need to be enclosed in do while (0) loop,
6062 # macro should not end with a semicolon
6063 if ($perl_version_ok &&
6064 $realfile !~ m@/vmlinux.lds.h$@ &&
6065 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6068 my ($off, $dstat, $dcond, $rest);
6070 ($dstat, $dcond, $ln, $cnt, $off) =
6071 ctx_statement_block($linenr, $realcnt, 0);
6074 $dstat =~ s/\\\n.//g;
6077 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6082 my $cnt = statement_rawlines($ctx);
6083 my $herectx = get_stat_here($linenr, $cnt, $here);
6085 if (($stmts =~ tr/;/;/) == 1 &&
6086 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6087 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6088 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6090 if (defined $semis && $semis ne "") {
6091 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6092 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6094 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6096 my $cnt = statement_rawlines($ctx);
6097 my $herectx = get_stat_here($linenr, $cnt, $here);
6099 WARN("TRAILING_SEMICOLON",
6100 "macros should not use a trailing semicolon\n" . "$herectx");
6104 # check for redundant bracing round if etc
6105 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6106 my ($level, $endln, @chunks) =
6107 ctx_statement_full($linenr, $realcnt, 1);
6108 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6109 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6110 if ($#chunks > 0 && $level == 0) {
6114 my $herectx = $here . "\n";
6115 my $ln = $linenr - 1;
6116 for my $chunk (@chunks) {
6117 my ($cond, $block) = @{$chunk};
6119 # If the condition carries leading newlines, then count those as offsets.
6120 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6121 my $offset = statement_rawlines($whitespace) - 1;
6123 $allowed[$allow] = 0;
6124 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6126 # We have looked at and allowed this specific line.
6127 $suppress_ifbraces{$ln + $offset} = 1;
6129 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6130 $ln += statement_rawlines($block) - 1;
6132 substr($block, 0, length($cond), '');
6134 $seen++ if ($block =~ /^\s*{/);
6136 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6137 if (statement_lines($cond) > 1) {
6138 #print "APW: ALLOWED: cond<$cond>\n";
6139 $allowed[$allow] = 1;
6141 if ($block =~/\b(?:if|for|while)\b/) {
6142 #print "APW: ALLOWED: block<$block>\n";
6143 $allowed[$allow] = 1;
6145 if (statement_block_size($block) > 1) {
6146 #print "APW: ALLOWED: lines block<$block>\n";
6147 $allowed[$allow] = 1;
6152 my $sum_allowed = 0;
6153 foreach (@allowed) {
6156 if ($sum_allowed == 0) {
6158 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6159 } elsif ($sum_allowed != $allow &&
6162 "braces {} should be used on all arms of this statement\n" . $herectx);
6167 if (!defined $suppress_ifbraces{$linenr - 1} &&
6168 $line =~ /\b(if|while|for|else)\b/) {
6171 # Check the pre-context.
6172 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6173 #print "APW: ALLOWED: pre<$1>\n";
6177 my ($level, $endln, @chunks) =
6178 ctx_statement_full($linenr, $realcnt, $-[0]);
6180 # Check the condition.
6181 my ($cond, $block) = @{$chunks[0]};
6182 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6183 if (defined $cond) {
6184 substr($block, 0, length($cond), '');
6186 if (statement_lines($cond) > 1) {
6187 #print "APW: ALLOWED: cond<$cond>\n";
6190 if ($block =~/\b(?:if|for|while)\b/) {
6191 #print "APW: ALLOWED: block<$block>\n";
6194 if (statement_block_size($block) > 1) {
6195 #print "APW: ALLOWED: lines block<$block>\n";
6198 # Check the post-context.
6199 if (defined $chunks[1]) {
6200 my ($cond, $block) = @{$chunks[1]};
6201 if (defined $cond) {
6202 substr($block, 0, length($cond), '');
6204 if ($block =~ /^\s*\{/) {
6205 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6209 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6210 my $cnt = statement_rawlines($block);
6211 my $herectx = get_stat_here($linenr, $cnt, $here);
6214 "braces {} are not necessary for single statement blocks\n" . $herectx);
6218 # check for single line unbalanced braces
6219 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6220 $sline =~ /^.\s*else\s*\{\s*$/) {
6221 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6224 # check for unnecessary blank lines around braces
6225 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6227 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6228 $fix && $prevrawline =~ /^\+/) {
6229 fix_delete_line($fixlinenr - 1, $prevrawline);
6232 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6234 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6236 fix_delete_line($fixlinenr, $rawline);
6240 # no volatiles please
6241 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6242 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6244 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6247 # Check for user-visible strings broken across lines, which breaks the ability
6248 # to grep for the string. Make exceptions when the previous string ends in a
6249 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6250 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6251 if ($line =~ /^\+\s*$String/ &&
6252 $prevline =~ /"\s*$/ &&
6253 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6254 if (WARN("SPLIT_STRING",
6255 "quoted string split across lines\n" . $hereprev) &&
6257 $prevrawline =~ /^\+.*"\s*$/ &&
6258 $last_coalesced_string_linenr != $linenr - 1) {
6259 my $extracted_string = get_quoted_string($line, $rawline);
6260 my $comma_close = "";
6261 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6265 fix_delete_line($fixlinenr - 1, $prevrawline);
6266 fix_delete_line($fixlinenr, $rawline);
6267 my $fixedline = $prevrawline;
6268 $fixedline =~ s/"\s*$//;
6269 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
6270 fix_insert_line($fixlinenr - 1, $fixedline);
6271 $fixedline = $rawline;
6272 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6273 if ($fixedline !~ /\+\s*$/) {
6274 fix_insert_line($fixlinenr, $fixedline);
6276 $last_coalesced_string_linenr = $linenr;
6280 # check for missing a space in a string concatenation
6281 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6282 WARN('MISSING_SPACE',
6283 "break quoted strings at a space character\n" . $hereprev);
6286 # check for an embedded function name in a string when the function is known
6287 # This does not work very well for -f --file checking as it depends on patch
6288 # context providing the function name or a single line form for in-file
6289 # function declarations
6290 if ($line =~ /^\+.*$String/ &&
6291 defined($context_function) &&
6292 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6293 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6294 WARN("EMBEDDED_FUNCTION_NAME",
6295 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6298 # check for unnecessary function tracing like uses
6299 # This does not use $logFunctions because there are many instances like
6300 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6301 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6302 if (WARN("TRACING_LOGGING",
6303 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6305 fix_delete_line($fixlinenr, $rawline);
6309 # check for spaces before a quoted newline
6310 if ($rawline =~ /^.*\".*\s\\n/) {
6311 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6312 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6314 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6319 # concatenated string without spaces between elements
6320 if ($line =~ /$String[A-Z_]/ ||
6321 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6322 if (CHK("CONCATENATED_STRING",
6323 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6325 while ($line =~ /($String)/g) {
6326 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6327 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6328 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6333 # uncoalesced string fragments
6334 if ($line =~ /$String\s*[Lu]?"/) {
6335 if (WARN("STRING_FRAGMENTS",
6336 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6338 while ($line =~ /($String)(?=\s*")/g) {
6339 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6340 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6345 # check for non-standard and hex prefixed decimal printf formats
6346 my $show_L = 1; #don't show the same defect twice
6348 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6349 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6350 $string =~ s/%%/__/g;
6352 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6354 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6358 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6360 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6363 # check for 0x<decimal>
6364 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6365 ERROR("PRINTF_0XDECIMAL",
6366 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6370 # check for line continuations in quoted strings with odd counts of "
6371 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6372 WARN("LINE_CONTINUATIONS",
6373 "Avoid line continuations in quoted strings\n" . $herecurr);
6377 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6379 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6383 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6385 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6388 # check for needless "if (<foo>) fn(<foo>)" uses
6389 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6390 my $tested = quotemeta($1);
6391 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6392 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6394 if (WARN('NEEDLESS_IF',
6395 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6398 my $leading_tabs = "";
6399 my $new_leading_tabs = "";
6400 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6405 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6406 $new_leading_tabs = $1;
6407 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6414 fix_delete_line($fixlinenr - 1, $prevrawline);
6415 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6421 # check for unnecessary "Out of Memory" messages
6422 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6423 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6424 (defined $1 || defined $3) &&
6427 my $testline = $lines[$linenr - 3];
6429 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6430 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6432 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6433 $s !~ /\b__GFP_NOWARN\b/ ) {
6435 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6439 # check for logging functions with KERN_<LEVEL>
6440 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6441 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6443 if (WARN("UNNECESSARY_KERN_LEVEL",
6444 "Possible unnecessary $level\n" . $herecurr) &&
6446 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6450 # check for logging continuations
6451 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6452 WARN("LOGGING_CONTINUATION",
6453 "Avoid logging continuation uses where feasible\n" . $herecurr);
6456 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6457 if (defined $stat &&
6458 $line =~ /\b$logFunctions\s*\(/ &&
6459 index($stat, '"') >= 0) {
6460 my $lc = $stat =~ tr@\n@@;
6461 $lc = $lc + $linenr;
6462 my $stat_real = get_stat_real($linenr, $lc);
6463 pos($stat_real) = index($stat_real, '"');
6464 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6467 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6468 if (WARN("UNNECESSARY_MODIFIER",
6469 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6470 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6473 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6478 # check for mask then right shift without a parentheses
6479 if ($perl_version_ok &&
6480 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6481 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6482 WARN("MASK_THEN_SHIFT",
6483 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6486 # check for pointer comparisons to NULL
6487 if ($perl_version_ok) {
6488 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6491 $equal = "" if ($4 eq "!=");
6492 if (CHK("COMPARISON_TO_NULL",
6493 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6495 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6500 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6501 if ($line =~ /(\b$InitAttribute\b)/) {
6503 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6506 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6507 ERROR("MISPLACED_INIT",
6508 "$attr should be placed after $var\n" . $herecurr)) ||
6509 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6510 WARN("MISPLACED_INIT",
6511 "$attr should be placed after $var\n" . $herecurr))) &&
6513 $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;
6518 # check for $InitAttributeData (ie: __initdata) with const
6519 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6521 $attr =~ /($InitAttributePrefix)(.*)/;
6522 my $attr_prefix = $1;
6524 if (ERROR("INIT_ATTRIBUTE",
6525 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6527 $fixed[$fixlinenr] =~
6528 s/$InitAttributeData/${attr_prefix}initconst/;
6532 # check for $InitAttributeConst (ie: __initconst) without const
6533 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6535 if (ERROR("INIT_ATTRIBUTE",
6536 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6538 my $lead = $fixed[$fixlinenr] =~
6539 /(^\+\s*(?:static\s+))/;
6541 $lead = "$lead " if ($lead !~ /^\+$/);
6542 $lead = "${lead}const ";
6543 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6547 # check for __read_mostly with const non-pointer (should just be const)
6548 if ($line =~ /\b__read_mostly\b/ &&
6549 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6550 if (ERROR("CONST_READ_MOSTLY",
6551 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6553 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6557 # don't use __constant_<foo> functions outside of include/uapi/
6558 if ($realfile !~ m@^include/uapi/@ &&
6559 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6560 my $constant_func = $1;
6561 my $func = $constant_func;
6562 $func =~ s/^__constant_//;
6563 if (WARN("CONSTANT_CONVERSION",
6564 "$constant_func should be $func\n" . $herecurr) &&
6566 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6570 # prefer usleep_range over udelay
6571 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6573 # ignore udelay's < 10, however
6574 if (! ($delay < 10) ) {
6576 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6578 if ($delay > 2000) {
6580 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6584 # warn about unexpectedly long msleep's
6585 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6588 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6592 # check for comparisons of jiffies
6593 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6594 WARN("JIFFIES_COMPARISON",
6595 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6598 # check for comparisons of get_jiffies_64()
6599 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6600 WARN("JIFFIES_COMPARISON",
6601 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6604 # warn about #ifdefs in C files
6605 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6606 # print "#ifdef in C files should be avoided\n";
6607 # print "$herecurr";
6611 # warn about spacing in #ifdefs
6612 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6613 if (ERROR("SPACING",
6614 "exactly one space required after that #$1\n" . $herecurr) &&
6616 $fixed[$fixlinenr] =~
6617 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6622 # check for spinlock_t definitions without a comment.
6623 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6624 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6626 if (!ctx_has_comment($first_line, $linenr)) {
6627 CHK("UNCOMMENTED_DEFINITION",
6628 "$1 definition without comment\n" . $herecurr);
6631 # check for memory barriers without a comment.
6638 my $barrier_stems = qr{
6646 my $all_barriers = qr{
6648 smp_(?:$barrier_stems)|
6649 virt_(?:$barrier_stems)
6652 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6653 if (!ctx_has_comment($first_line, $linenr)) {
6654 WARN("MEMORY_BARRIER",
6655 "memory barrier without comment\n" . $herecurr);
6659 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6661 if ($realfile !~ m@^include/asm-generic/@ &&
6662 $realfile !~ m@/barrier\.h$@ &&
6663 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6664 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6665 WARN("MEMORY_BARRIER",
6666 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6669 # check for waitqueue_active without a comment.
6670 if ($line =~ /\bwaitqueue_active\s*\(/) {
6671 if (!ctx_has_comment($first_line, $linenr)) {
6672 WARN("WAITQUEUE_ACTIVE",
6673 "waitqueue_active without comment\n" . $herecurr);
6677 # check for data_race without a comment.
6678 if ($line =~ /\bdata_race\s*\(/) {
6679 if (!ctx_has_comment($first_line, $linenr)) {
6681 "data_race without comment\n" . $herecurr);
6685 # check of hardware specific defines
6686 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6688 "architecture specific defines should be avoided\n" . $herecurr);
6691 # check that the storage class is not after a type
6692 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6693 WARN("STORAGE_CLASS",
6694 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6696 # Check that the storage class is at the beginning of a declaration
6697 if ($line =~ /\b$Storage\b/ &&
6698 $line !~ /^.\s*$Storage/ &&
6699 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6700 $1 !~ /[\,\)]\s*$/) {
6701 WARN("STORAGE_CLASS",
6702 "storage class should be at the beginning of the declaration\n" . $herecurr);
6705 # check the location of the inline attribute, that it is between
6706 # storage class and type.
6707 if ($line =~ /\b$Type\s+$Inline\b/ ||
6708 $line =~ /\b$Inline\s+$Storage\b/) {
6709 ERROR("INLINE_LOCATION",
6710 "inline keyword should sit between storage class and type\n" . $herecurr);
6713 # Check for __inline__ and __inline, prefer inline
6714 if ($realfile !~ m@\binclude/uapi/@ &&
6715 $line =~ /\b(__inline__|__inline)\b/) {
6717 "plain inline is preferred over $1\n" . $herecurr) &&
6719 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6724 # Check for compiler attributes
6725 if ($realfile !~ m@\binclude/uapi/@ &&
6726 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6728 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6731 "alias" => "__alias",
6732 "aligned" => "__aligned",
6733 "always_inline" => "__always_inline",
6734 "assume_aligned" => "__assume_aligned",
6736 "const" => "__attribute_const__",
6738 "designated_init" => "__designated_init",
6739 "externally_visible" => "__visible",
6740 "format" => "printf|scanf",
6741 "gnu_inline" => "__gnu_inline",
6742 "malloc" => "__malloc",
6744 "no_caller_saved_registers" => "__no_caller_saved_registers",
6745 "noclone" => "__noclone",
6746 "noinline" => "noinline",
6747 "nonstring" => "__nonstring",
6748 "noreturn" => "__noreturn",
6749 "packed" => "__packed",
6751 "section" => "__section",
6756 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6759 $params = $2 if defined($2);
6760 my $curr_attr = $orig_attr;
6761 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6762 if (exists($attr_list{$curr_attr})) {
6763 my $new = $attr_list{$curr_attr};
6764 if ($curr_attr eq "format" && $params) {
6765 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6768 $new = "$new$params";
6770 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6771 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6773 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6774 $fixed[$fixlinenr] =~ s/$remove//;
6775 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6776 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6777 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6782 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6783 if ($attr =~ /^_*unused/) {
6784 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6785 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6789 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6790 if ($perl_version_ok &&
6791 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6792 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6793 $line =~ /\b__weak\b/)) {
6794 ERROR("WEAK_DECLARATION",
6795 "Using weak declarations can have unintended link defects\n" . $herecurr);
6798 # check for c99 types like uint8_t used outside of uapi/ and tools/
6799 if ($realfile !~ m@\binclude/uapi/@ &&
6800 $realfile !~ m@\btools/@ &&
6801 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6803 if ($type =~ /\b($typeC99Typedefs)\b/) {
6805 my $kernel_type = 'u';
6806 $kernel_type = 's' if ($type =~ /^_*[si]/);
6809 if (CHK("PREFER_KERNEL_TYPES",
6810 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6812 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6817 # check for cast of C90 native int or longer types constants
6818 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6822 my $newconst = $const;
6823 $newconst =~ s/${Int_type}$//;
6824 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6825 if ($cast =~ /\blong\s+long\b/) {
6827 } elsif ($cast =~ /\blong\b/) {
6830 if (WARN("TYPECAST_INT_CONSTANT",
6831 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6833 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6837 # check for sizeof(&)
6838 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6839 WARN("SIZEOF_ADDRESS",
6840 "sizeof(& should be avoided\n" . $herecurr);
6843 # check for sizeof without parenthesis
6844 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6845 if (WARN("SIZEOF_PARENTHESIS",
6846 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6848 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6852 # check for struct spinlock declarations
6853 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6854 WARN("USE_SPINLOCK_T",
6855 "struct spinlock should be spinlock_t\n" . $herecurr);
6858 # check for seq_printf uses that could be seq_puts
6859 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6860 my $fmt = get_quoted_string($line, $rawline);
6863 if (WARN("PREFER_SEQ_PUTS",
6864 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6866 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6871 # check for vsprintf extension %p<foo> misuses
6872 if ($perl_version_ok &&
6874 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6875 $1 !~ /^_*volatile_*$/) {
6878 my $lc = $stat =~ tr@\n@@;
6879 $lc = $lc + $linenr;
6880 for (my $count = $linenr; $count <= $lc; $count++) {
6884 my $bad_specifier = "";
6885 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6888 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6892 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6893 ($extension eq "f" &&
6894 defined $qualifier && $qualifier !~ /^w/) ||
6895 ($extension eq "4" &&
6896 defined $qualifier && $qualifier !~ /^cc/)) {
6897 $bad_specifier = $specifier;
6900 if ($extension eq "x" && !defined($stat_real)) {
6901 if (!defined($stat_real)) {
6902 $stat_real = get_stat_real($linenr, $lc);
6904 WARN("VSPRINTF_SPECIFIER_PX",
6905 "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");
6908 if ($bad_specifier ne "") {
6909 my $stat_real = get_stat_real($linenr, $lc);
6910 my $ext_type = "Invalid";
6912 if ($bad_specifier =~ /p[Ff]/) {
6913 $use = " - use %pS instead";
6914 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6917 WARN("VSPRINTF_POINTER_EXTENSION",
6918 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6923 # Check for misused memsets
6924 if ($perl_version_ok &&
6926 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6932 if ($ms_size =~ /^(0x|)0$/i) {
6934 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6935 } elsif ($ms_size =~ /^(0x|)1$/i) {
6937 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6941 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6942 # if ($perl_version_ok &&
6944 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6945 # if (WARN("PREFER_ETHER_ADDR_COPY",
6946 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6948 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6952 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6953 # if ($perl_version_ok &&
6955 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6956 # WARN("PREFER_ETHER_ADDR_EQUAL",
6957 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6960 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6961 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6962 # if ($perl_version_ok &&
6964 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6968 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6969 # if (WARN("PREFER_ETH_ZERO_ADDR",
6970 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6972 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6974 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6975 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6976 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6978 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6983 # strlcpy uses that should likely be strscpy
6984 if ($line =~ /\bstrlcpy\s*\(/) {
6986 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr);
6989 # typecasts on min/max could be min_t/max_t
6990 if ($perl_version_ok &&
6992 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6993 if (defined $2 || defined $7) {
6995 my $cast1 = deparenthesize($2);
6997 my $cast2 = deparenthesize($7);
7001 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7002 $cast = "$cast1 or $cast2";
7003 } elsif ($cast1 ne "") {
7009 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7013 # check usleep_range arguments
7014 if ($perl_version_ok &&
7016 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7020 WARN("USLEEP_RANGE",
7021 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7022 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7024 WARN("USLEEP_RANGE",
7025 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7029 # check for naked sscanf
7030 if ($perl_version_ok &&
7032 $line =~ /\bsscanf\b/ &&
7033 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7034 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7035 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7036 my $lc = $stat =~ tr@\n@@;
7037 $lc = $lc + $linenr;
7038 my $stat_real = get_stat_real($linenr, $lc);
7039 WARN("NAKED_SSCANF",
7040 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7043 # check for simple sscanf that should be kstrto<foo>
7044 if ($perl_version_ok &&
7046 $line =~ /\bsscanf\b/) {
7047 my $lc = $stat =~ tr@\n@@;
7048 $lc = $lc + $linenr;
7049 my $stat_real = get_stat_real($linenr, $lc);
7050 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7052 my $count = $format =~ tr@%@%@;
7054 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7055 WARN("SSCANF_TO_KSTRTO",
7056 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7061 # check for new externs in .h files.
7062 if ($realfile =~ /\.h$/ &&
7063 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7064 if (CHK("AVOID_EXTERNS",
7065 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
7067 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7071 # check for new externs in .c files.
7072 if ($realfile =~ /\.c$/ && defined $stat &&
7073 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7075 my $function_name = $1;
7076 my $paren_space = $2;
7079 if (defined $cond) {
7080 substr($s, 0, length($cond), '');
7084 WARN("AVOID_EXTERNS",
7085 "externs should be avoided in .c files\n" . $herecurr);
7088 if ($paren_space =~ /\n/) {
7089 WARN("FUNCTION_ARGUMENTS",
7090 "arguments for function declarations should follow identifier\n" . $herecurr);
7093 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7094 $stat =~ /^.\s*extern\s+/)
7096 WARN("AVOID_EXTERNS",
7097 "externs should be avoided in .c files\n" . $herecurr);
7100 # check for function declarations that have arguments without identifier names
7101 if (defined $stat &&
7102 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7104 my $args = trim($1);
7105 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7107 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7108 WARN("FUNCTION_ARGUMENTS",
7109 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7114 # check for function definitions
7115 if ($perl_version_ok &&
7117 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7118 $context_function = $1;
7120 # check for multiline function definition with misplaced open brace
7122 my $cnt = statement_rawlines($stat);
7123 my $herectx = $here . "\n";
7124 for (my $n = 0; $n < $cnt; $n++) {
7125 my $rl = raw_line($linenr, $n);
7126 $herectx .= $rl . "\n";
7127 $ok = 1 if ($rl =~ /^[ \+]\{/);
7128 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7129 last if $rl =~ /^[ \+].*\{/;
7133 "open brace '{' following function definitions go on the next line\n" . $herectx);
7137 # checks for new __setup's
7138 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7141 if (!grep(/$name/, @setup_docs)) {
7142 CHK("UNDOCUMENTED_SETUP",
7143 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7147 # check for pointless casting of alloc functions
7148 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7149 WARN("UNNECESSARY_CASTS",
7150 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7154 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7155 if ($perl_version_ok &&
7156 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7157 CHK("ALLOC_SIZEOF_STRUCT",
7158 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7161 # check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7162 if ($perl_version_ok &&
7164 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7168 my $newfunc = "kmalloc_array";
7169 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7170 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7171 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7174 if ($a1 =~ /^sizeof\s*\S/) {
7178 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7179 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7180 my $cnt = statement_rawlines($stat);
7181 my $herectx = get_stat_here($linenr, $cnt, $here);
7183 if (WARN("ALLOC_WITH_MULTIPLY",
7184 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7187 $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;
7192 # check for krealloc arg reuse
7193 if ($perl_version_ok &&
7194 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7196 WARN("KREALLOC_ARG_REUSE",
7197 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7200 # check for alloc argument mismatch
7201 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7202 WARN("ALLOC_ARRAY_ARGS",
7203 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7206 # check for multiple semicolons
7207 if ($line =~ /;\s*;\s*$/) {
7208 if (WARN("ONE_SEMICOLON",
7209 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7211 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7215 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7216 if ($realfile !~ m@^include/uapi/@ &&
7217 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7219 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7220 if (CHK("BIT_MACRO",
7221 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7223 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7227 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7228 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7229 WARN("IS_ENABLED_CONFIG",
7230 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7233 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7234 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7236 if (WARN("PREFER_IS_ENABLED",
7237 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7239 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7243 # check for /* fallthrough */ like comment, prefer fallthrough;
7244 my @fallthroughs = (
7247 'lint -fallthrough[ \t]*',
7248 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7249 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7250 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7251 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7253 if ($raw_comment ne '') {
7254 foreach my $ft (@fallthroughs) {
7255 if ($raw_comment =~ /$ft/) {
7256 my $msg_level = \&WARN;
7257 $msg_level = \&CHK if ($file);
7258 &{$msg_level}("PREFER_FALLTHROUGH",
7259 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7265 # check for switch/default statements without a break;
7266 if ($perl_version_ok &&
7268 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7269 my $cnt = statement_rawlines($stat);
7270 my $herectx = get_stat_here($linenr, $cnt, $here);
7272 WARN("DEFAULT_NO_BREAK",
7273 "switch default: should use break\n" . $herectx);
7276 # check for gcc specific __FUNCTION__
7277 if ($line =~ /\b__FUNCTION__\b/) {
7278 if (WARN("USE_FUNC",
7279 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7281 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7285 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7286 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7288 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7291 # check for use of yield()
7292 if ($line =~ /\byield\s*\(\s*\)/) {
7294 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7297 # check for comparisons against true and false
7298 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7306 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7308 my $type = lc($otype);
7309 if ($type =~ /^(?:true|false)$/) {
7310 if (("$test" eq "==" && "$type" eq "true") ||
7311 ("$test" eq "!=" && "$type" eq "false")) {
7315 CHK("BOOL_COMPARISON",
7316 "Using comparison to $otype is error prone\n" . $herecurr);
7318 ## maybe suggesting a correct construct would better
7319 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7324 # check for semaphores initialized locked
7325 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7326 WARN("CONSIDER_COMPLETION",
7327 "consider using a completion\n" . $herecurr);
7330 # recommend kstrto* over simple_strto* and strict_strto*
7331 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7332 WARN("CONSIDER_KSTRTO",
7333 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7336 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7337 if ($line =~ /^.\s*__initcall\s*\(/) {
7338 WARN("USE_DEVICE_INITCALL",
7339 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7342 # check for spin_is_locked(), suggest lockdep instead
7343 if ($line =~ /\bspin_is_locked\(/) {
7345 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7348 # check for deprecated apis
7349 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7350 my $deprecated_api = $1;
7351 my $new_api = $deprecated_apis{$deprecated_api};
7352 WARN("DEPRECATED_API",
7353 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7356 # check for various structs that are normally const (ops, kgdb, device_tree)
7357 # and avoid what seem like struct definitions 'struct foo {'
7358 if (defined($const_structs) &&
7359 $line !~ /\bconst\b/ &&
7360 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7361 WARN("CONST_STRUCT",
7362 "struct $1 should normally be const\n" . $herecurr);
7365 # use of NR_CPUS is usually wrong
7366 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7367 # ignore designated initializers using NR_CPUS
7368 if ($line =~ /\bNR_CPUS\b/ &&
7369 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7370 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7371 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7372 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7373 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7374 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7377 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7380 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7381 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7382 ERROR("DEFINE_ARCH_HAS",
7383 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7386 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7387 if ($perl_version_ok &&
7388 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7389 WARN("LIKELY_MISUSE",
7390 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7393 # return sysfs_emit(foo, fmt, ...) fmt without newline
7394 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7395 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7396 my $offset = $+[6] - 1;
7397 if (WARN("SYSFS_EMIT",
7398 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7400 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7404 # nested likely/unlikely calls
7405 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7406 WARN("LIKELY_MISUSE",
7407 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7410 # whine mightly about in_atomic
7411 if ($line =~ /\bin_atomic\s*\(/) {
7412 if ($realfile =~ m@^drivers/@) {
7414 "do not use in_atomic in drivers\n" . $herecurr);
7415 } elsif ($realfile !~ m@^kernel/@) {
7417 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7421 # check for lockdep_set_novalidate_class
7422 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7423 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7424 if ($realfile !~ m@^kernel/lockdep@ &&
7425 $realfile !~ m@^include/linux/lockdep@ &&
7426 $realfile !~ m@^drivers/base/core@) {
7428 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7432 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7433 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7434 WARN("EXPORTED_WORLD_WRITABLE",
7435 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7438 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7439 # and whether or not function naming is typical and if
7440 # DEVICE_ATTR permissions uses are unusual too
7441 if ($perl_version_ok &&
7443 $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*\)/) {
7448 my $octal_perms = perms_to_octal($perms);
7449 if ($show =~ /^${var}_show$/ &&
7450 $store =~ /^${var}_store$/ &&
7451 $octal_perms eq "0644") {
7452 if (WARN("DEVICE_ATTR_RW",
7453 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7455 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7457 } elsif ($show =~ /^${var}_show$/ &&
7458 $store =~ /^NULL$/ &&
7459 $octal_perms eq "0444") {
7460 if (WARN("DEVICE_ATTR_RO",
7461 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7463 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7465 } elsif ($show =~ /^NULL$/ &&
7466 $store =~ /^${var}_store$/ &&
7467 $octal_perms eq "0200") {
7468 if (WARN("DEVICE_ATTR_WO",
7469 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7471 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7473 } elsif ($octal_perms eq "0644" ||
7474 $octal_perms eq "0444" ||
7475 $octal_perms eq "0200") {
7476 my $newshow = "$show";
7477 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7478 my $newstore = $store;
7479 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7481 if ($show ne $newshow) {
7482 $rename .= " '$show' to '$newshow'";
7484 if ($store ne $newstore) {
7485 $rename .= " '$store' to '$newstore'";
7487 WARN("DEVICE_ATTR_FUNCTIONS",
7488 "Consider renaming function(s)$rename\n" . $herecurr);
7490 WARN("DEVICE_ATTR_PERMS",
7491 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7495 # Mode permission misuses where it seems decimal should be octal
7496 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7497 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7498 # specific definition of not visible in sysfs.
7499 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7500 # use the default permissions
7501 if ($perl_version_ok &&
7503 $line =~ /$mode_perms_search/) {
7504 foreach my $entry (@mode_permission_funcs) {
7505 my $func = $entry->[0];
7506 my $arg_pos = $entry->[1];
7508 my $lc = $stat =~ tr@\n@@;
7509 $lc = $lc + $linenr;
7510 my $stat_real = get_stat_real($linenr, $lc);
7515 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7517 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7518 if ($stat =~ /$test/) {
7520 $val = $6 if ($skip_args ne "");
7521 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7522 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7523 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7524 ERROR("NON_OCTAL_PERMISSIONS",
7525 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7527 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7528 ERROR("EXPORTED_WORLD_WRITABLE",
7529 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7535 # check for uses of S_<PERMS> that could be octal for readability
7536 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7538 my $octal = perms_to_octal($oval);
7539 if (WARN("SYMBOLIC_PERMS",
7540 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7542 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7546 # validate content of MODULE_LICENSE against list from include/linux/module.h
7547 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7548 my $extracted_string = get_quoted_string($line, $rawline);
7549 my $valid_licenses = qr{
7552 GPL\ and\ additional\ rights|
7558 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7559 WARN("MODULE_LICENSE",
7560 "unknown module license " . $extracted_string . "\n" . $herecurr);
7562 if (!$file && $extracted_string eq '"GPL v2"') {
7563 if (WARN("MODULE_LICENSE",
7564 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7566 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7571 # check for sysctl duplicate constants
7572 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7573 WARN("DUPLICATED_SYSCTL_CONST",
7574 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7578 # If we have no input at all, then there is nothing to report on
7579 # so just keep quiet.
7580 if ($#rawlines == -1) {
7584 # In mailback mode only produce a report in the negative, for
7585 # things that appear to be patches.
7586 if ($mailback && ($clean == 1 || !$is_patch)) {
7590 # This is not a patch, and we are in 'no-patch' mode so
7592 if (!$chk_patch && !$is_patch) {
7596 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7597 ERROR("NOT_UNIFIED_DIFF",
7598 "Does not appear to be a unified-diff format patch\n");
7600 if ($is_patch && $has_commit_log && $chk_signoff) {
7601 if ($signoff == 0) {
7602 ERROR("MISSING_SIGN_OFF",
7603 "Missing Signed-off-by: line(s)\n");
7604 } elsif ($authorsignoff != 1) {
7605 # authorsignoff values:
7606 # 0 -> missing sign off
7607 # 1 -> sign off identical
7608 # 2 -> names and addresses match, comments mismatch
7609 # 3 -> addresses match, names different
7610 # 4 -> names match, addresses different
7611 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7613 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7615 if ($authorsignoff == 0) {
7616 ERROR("NO_AUTHOR_SIGN_OFF",
7617 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7618 } elsif ($authorsignoff == 2) {
7619 CHK("FROM_SIGN_OFF_MISMATCH",
7620 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7621 } elsif ($authorsignoff == 3) {
7622 WARN("FROM_SIGN_OFF_MISMATCH",
7623 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7624 } elsif ($authorsignoff == 4) {
7625 WARN("FROM_SIGN_OFF_MISMATCH",
7626 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7627 } elsif ($authorsignoff == 5) {
7628 WARN("FROM_SIGN_OFF_MISMATCH",
7629 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7634 print report_dump();
7635 if ($summary && !($clean == 1 && $quiet == 1)) {
7636 print "$filename " if ($summary_file);
7637 print "total: $cnt_error errors, $cnt_warn warnings, " .
7638 (($check)? "$cnt_chk checks, " : "") .
7639 "$cnt_lines lines checked\n";
7643 # If there were any defects found and not already fixing them
7644 if (!$clean and !$fix) {
7647 NOTE: For some of the reported defects, checkpatch may be able to
7648 mechanically convert to the typical style using --fix or --fix-inplace.
7651 # If there were whitespace errors which cleanpatch can fix
7652 # then suggest that.
7653 if ($rpt_cleaners) {
7657 NOTE: Whitespace errors detected.
7658 You may wish to use scripts/cleanpatch or scripts/cleanfile
7663 if ($clean == 0 && $fix &&
7664 ("@rawlines" ne "@fixed" ||
7665 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7666 my $newfile = $filename;
7667 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7671 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7673 open($f, '>', $newfile)
7674 or die "$P: Can't open $newfile for write\n";
7675 foreach my $fixed_line (@fixed) {
7678 if ($linecount > 3) {
7679 $fixed_line =~ s/^\+//;
7680 print $f $fixed_line . "\n";
7683 print $f $fixed_line . "\n";
7691 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7693 Do _NOT_ trust the results written to this file.
7694 Do _NOT_ submit these changes without inspecting them for correctness.
7696 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7697 No warranties, expressed or implied...
7705 print "$vname has no obvious style problems and is ready for submission.\n";
7707 print "$vname has style problems, please review.\n";