2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term
::ANSIColor
qw(:constants);
16 use Encode
qw(decode encode);
19 my $D = dirname
(abs_path
($P));
23 use Getopt
::Long
qw(:config no_auto_abbrev);
27 my %verbose_messages = ();
28 my %verbose_emitted = ();
49 my $gitroot = $ENV{'GIT_DIR'};
50 $gitroot = ".git" if !defined($gitroot);
58 my $configuration_file = ".checkpatch.conf";
59 my $max_line_length = 100;
60 my $ignore_perl_version = 0;
61 my $minimum_perl_version = 5.10.0;
62 my $min_conf_desc_length = 4;
63 my $spelling_file = "$D/spelling.txt";
65 my $codespellfile = "/usr/share/codespell/dictionary.txt";
66 my $user_codespellfile = "";
67 my $conststructsfile = "$D/const_structs.checkpatch";
69 my $docsfile = "$D/../doc/develop/checkpatch.rst";
72 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
73 # git output parsing needs US English output, so first set backtick child process LANGUAGE
74 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
76 my ${CONFIG_
} = "CONFIG_";
82 Usage
: $P [OPTION
]... [FILE
]...
87 -v
, --verbose verbose mode
88 --no-tree run without a kernel tree
89 --no-signoff
do not check
for 'Signed-off-by' line
90 --patch treat FILE as patchfile
(default)
91 --emacs emacs compile window format
92 --terse one line per report
93 --showfile emit diffed file position
, not input file position
94 -g
, --git treat FILE as a single commit
or git revision range
95 single git commit with
:
99 multiple git commits with
:
103 git merges are ignored
104 -f
, --file treat FILE as regular source file
105 --subjective
, --strict enable more subjective tests
106 --list
-types list the possible message types
107 --types TYPE
(,TYPE2
...) show only these comma separated message types
108 --ignore TYPE
(,TYPE2
...) ignore various comma separated message types
109 --show
-types show the specific message type
in the output
110 --max
-line
-length=n set the maximum line
length, (default $max_line_length)
111 if exceeded
, warn on patches
112 requires
--strict
for use with
--file
113 --min
-conf
-desc
-length=n set the min description
length, if shorter
, warn
114 --tab
-size
=n set the number of spaces
for tab
(default $tabsize)
115 --root
=PATH PATH to the kernel tree root
116 --no-summary suppress the per
-file summary
117 --mailback only produce a report
in case of warnings
/errors
118 --summary
-file include the filename
in summary
119 --debug KEY
=[0|1] turn on
/off debugging of KEY
, where KEY is one of
120 'values', 'possible', 'type', and 'attr' (default
122 --test
-only
=WORD report only warnings
/errors containing WORD
124 --fix EXPERIMENTAL
- may create horrible results
125 If correctable single
-line errors exist
, create
126 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
127 with potential errors corrected to the preferred
129 --fix
-inplace EXPERIMENTAL
- may create horrible results
130 Is the same as
--fix
, but overwrites the input
131 file
. It
's your fault if there's
no backup
or git
132 --ignore
-perl
-version override checking of perl version
. expect
134 --codespell Use the codespell dictionary
for spelling
/typos
135 (default:$codespellfile)
136 --codespellfile Use this codespell dictionary
137 --typedefsfile Read additional types from this file
138 --color
[=WHEN
] Use colors
'always', 'never', or only
when output
139 is a terminal
('auto'). Default is
'auto'.
140 --u
-boot Run additional checks
for U
-Boot
141 --kconfig
-prefix
=WORD
use WORD as a prefix
for Kconfig symbols
(default
143 -h
, --help
, --version display this help
and exit
145 When FILE is
- read standard input
.
153 return grep { !$seen{$_}++ } @_;
163 open(my $script, '<', abs_path
($P)) or
164 die "$P: Can't read '$P' $!\n";
166 my $text = <$script>;
170 # Also catch when type or level is passed through a variable
171 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
173 if (exists($types{$2})) {
174 $types{$2} .= ",$1" if ($types{$2} ne $1);
179 $types{$2} = "UNDETERMINED";
183 print("#\tMessage type\n\n");
185 print(" ( Color coding: ");
186 print(RED
. "ERROR" . RESET
);
188 print(YELLOW
. "WARNING" . RESET
);
190 print(GREEN
. "CHECK" . RESET
);
192 print("Multiple levels / Undetermined");
196 foreach my $type (sort keys %types) {
197 my $orig_type = $type;
199 my $level = $types{$type};
200 if ($level eq "ERROR") {
201 $type = RED
. $type . RESET
;
202 } elsif ($level eq "WARN") {
203 $type = YELLOW
. $type . RESET
;
204 } elsif ($level eq "CHK") {
205 $type = GREEN
. $type . RESET
;
208 print(++$count . "\t" . $type . "\n");
209 if ($verbose && exists($verbose_messages{$orig_type})) {
210 my $message = $verbose_messages{$orig_type};
211 $message =~ s/\n/\n\t/g;
212 print("\t" . $message . "\n\n");
219 my $conf = which_conf
($configuration_file);
222 open(my $conffile, '<', "$conf")
223 or warn "$P: Can't find a readable $configuration_file file $!\n";
225 while (<$conffile>) {
228 $line =~ s/\s*\n?$//g;
232 next if ($line =~ m/^\s*#/);
233 next if ($line =~ m/^\s*$/);
235 my @words = split(" ", $line);
236 foreach my $word (@words) {
237 last if ($word =~ m/^#/);
238 push (@conf_args, $word);
242 unshift(@ARGV, @conf_args) if @conf_args;
246 open(my $docs, '<', "$docsfile")
247 or warn "$P: Can't read the documentation file $docsfile $!\n";
258 if ($line =~ /^\s*\*\*(.+)\*\*$/) {
260 $verbose_messages{$type} = trim
($desc);
266 if ($line =~ /^(?:\s{4,}|$)/) {
271 $verbose_messages{$type} = trim
($desc);
280 $verbose_messages{$type} = trim
($desc);
285 # Perl's Getopt::Long allows options to take optional arguments after a space.
286 # Prevent --color by itself from consuming other arguments
288 if ($_ eq "--color" || $_ eq "-color") {
289 $_ = "--color=$color";
294 'q|quiet+' => \
$quiet,
295 'v|verbose!' => \
$verbose,
297 'signoff!' => \
$chk_signoff,
298 'patch!' => \
$chk_patch,
301 'showfile!' => \
$showfile,
304 'subjective!' => \
$check,
305 'strict!' => \
$check,
306 'ignore=s' => \
@ignore,
308 'show-types!' => \
$show_types,
309 'list-types!' => \
$list_types,
310 'max-line-length=i' => \
$max_line_length,
311 'min-conf-desc-length=i' => \
$min_conf_desc_length,
312 'tab-size=i' => \
$tabsize,
314 'summary!' => \
$summary,
315 'mailback!' => \
$mailback,
316 'summary-file!' => \
$summary_file,
318 'fix-inplace!' => \
$fix_inplace,
319 'ignore-perl-version!' => \
$ignore_perl_version,
320 'debug=s' => \
%debug,
321 'test-only=s' => \
$tst_only,
322 'codespell!' => \
$codespell,
323 'codespellfile=s' => \
$user_codespellfile,
324 'typedefsfile=s' => \
$typedefsfile,
325 'u-boot' => \
$u_boot,
326 'color=s' => \
$color,
327 'no-color' => \
$color, #keep old behaviors of -nocolor
328 'nocolor' => \
$color, #keep old behaviors of -nocolor
329 'kconfig-prefix=s' => \
${CONFIG_
},
334 if ($user_codespellfile) {
335 # Use the user provided codespell file unconditionally
336 $codespellfile = $user_codespellfile;
337 } elsif (!(-f
$codespellfile)) {
338 # If /usr/share/codespell/dictionary.txt is not present, try to find it
339 # under codespell's install directory: <codespell_root>/data/dictionary.txt
340 if (($codespell || $help) && which
("codespell") ne "" && which
("python") ne "") {
341 my $python_codespell_dict = << "EOF";
345 codespell_dir
= op
.dirname
(codespell_lib
.__file__
)
346 codespell_file
= op
.join(codespell_dir
, 'data', 'dictionary.txt')
347 print(codespell_file
, end
='')
350 my $codespell_dict = `python -c "$python_codespell_dict" 2> /dev/null`;
351 $codespellfile = $codespell_dict if (-f
$codespell_dict);
355 # $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
356 # $help is 2 if invalid option is passed - exitcode: 1
357 help
($help - 1) if ($help);
359 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
360 die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
362 if ($color =~ /^[01]$/) {
364 } elsif ($color =~ /^always$/i) {
366 } elsif ($color =~ /^never$/i) {
368 } elsif ($color =~ /^auto$/i) {
369 $color = (-t STDOUT
);
371 die "$P: Invalid color mode: $color\n";
374 load_docs
() if ($verbose);
375 list_types
(0) if ($list_types);
377 $fix = 1 if ($fix_inplace);
378 $check_orig = $check;
382 my $perl_version_ok = 1;
383 if ($^V
&& $^V
lt $minimum_perl_version) {
384 $perl_version_ok = 0;
385 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
386 exit(1) if (!$ignore_perl_version);
389 #if no filenames are given, push '-' to read patch from stdin
394 # skip TAB size 1 to avoid additional checks on $tabsize - 1
395 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
397 sub hash_save_array_words
{
398 my ($hashRef, $arrayRef) = @_;
400 my @array = split(/,/, join(',', @
$arrayRef));
401 foreach my $word (@array) {
402 $word =~ s/\s*\n?$//g;
405 $word =~ tr/[a-z]/[A-Z]/;
407 next if ($word =~ m/^\s*#/);
408 next if ($word =~ m/^\s*$/);
414 sub hash_show_words
{
415 my ($hashRef, $prefix) = @_;
417 if (keys %$hashRef) {
418 print "\nNOTE: $prefix message types:";
419 foreach my $word (sort keys %$hashRef) {
426 hash_save_array_words
(\
%ignore_type, \
@ignore);
427 hash_save_array_words
(\
%use_type, \
@use);
430 my $dbg_possible = 0;
433 for my $key (keys %debug) {
435 eval "\${dbg_$key} = '$debug{$key}';";
439 my $rpt_cleaners = 0;
448 if (!top_of_kernel_tree
($root)) {
449 die "$P: $root: --root does not point at a valid tree\n";
452 if (top_of_kernel_tree
('.')) {
454 } elsif ($0 =~ m@
(.*)/scripts/[^/]*$@
&&
455 top_of_kernel_tree
($1)) {
460 if (!defined $root) {
461 print "Must be run from the top-level dir. of a kernel tree\n";
466 my $emitted_corrupt = 0;
469 [A
-Za
-z_
][A
-Za
-z\d_
]*
470 (?
:\s
*\#\#\s
*[A
-Za
-z_
][A
-Za
-z\d_
]*)*
472 our $Storage = qr{extern|static|asmlinkage};
486 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
487 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
488 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
489 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
490 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
492 # Notes to $Attribute:
493 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
516 ____cacheline_aligned
|
517 ____cacheline_aligned_in_smp
|
518 ____cacheline_internodealigned_in_smp
|
520 __alloc_size\s
*\
(\s
*\d
+\s
*(?
:,\s
*\d
+\s
*)?\
)
523 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
524 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
525 our $Lval = qr{$Ident(?:$Member)*};
527 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
528 our $Binary = qr{(?i)0b[01]+$Int_type?};
529 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
530 our $Int = qr{[0-9]+$Int_type?};
531 our $Octal = qr{0[0-7]+$Int_type?};
532 our $String = qr{(?:\b[Lu])?"[X\t]*"};
533 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
534 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
535 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
536 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
537 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
538 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
539 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
540 our $Arithmetic = qr{\+|-|\*|\/|%};
544 &&|\
|\
||,|\
^|\
+\
+|--|&|\
||$Arithmetic
547 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
551 our $NonptrTypeMisordered;
552 our $NonptrTypeWithAttr;
556 our $DeclareMisordered;
558 our $NON_ASCII_UTF8 = qr{
559 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
560 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
561 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
562 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
563 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
564 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
565 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
569 [\x09\x0A\x0D\x20-\x7E] # ASCII
573 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
574 our $typeOtherOSTypedefs = qr{(?x
:
575 u_
(?
:char
|short
|int|long
) | # bsd
576 u
(?
:nchar
|short
|int|long
) # sysv
578 our $typeKernelTypedefs = qr{(?x
:
579 (?
:__
)?
(?
:u
|s
|be
|le)(?
:8|16|32|64)|
582 our $typeTypedefs = qr{(?x
:
584 $typeOtherOSTypedefs\b|
585 $typeKernelTypedefs\b
588 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
590 our $logFunctions = qr{(?x
:
591 printk
(?
:_ratelimited
|_once
|_deferred_once
|_deferred
|)|
592 (?
:[a
-z0
-9]+_
){1,2}(?
:printk
|emerg
|alert
|crit
|err
|warning
|warn|notice
|info
|debug
|dbg
|vdbg
|devel
|cont
|WARN
)(?
:_ratelimited
|_once
|)|
594 WARN
(?
:_RATELIMIT
|_ONCE
|)|
599 seq_vprintf
|seq_printf
|seq_puts
602 our $allocFunctions = qr{(?x
:
604 (?
:kv
|k
|v
)[czm
]alloc
(?
:_array
)?
(?
:_node
)?
|
607 (?
:\w
+)?alloc_skb
(?
:_ip_align
)?
|
608 # dev_alloc_skb/netdev_alloc_skb, et al
612 our $signature_tags = qr{(?xi
:
624 our $tracing_logging_tags = qr{(?xi
:
648 sub edit_distance_min
{
650 my $len = scalar @arr;
651 if ((scalar @arr) < 1) {
652 # if underflow, return
656 for my $i (0 .. ($len-1)) {
657 if ($arr[$i] < $min) {
664 sub get_edit_distance
{
665 my ($str1, $str2) = @_;
670 my $len1 = length($str1);
671 my $len2 = length($str2);
672 # two dimensional array storing minimum edit distance
674 for my $i (0 .. $len1) {
675 for my $j (0 .. $len2) {
677 $distance[$i][$j] = $j;
679 $distance[$i][$j] = $i;
680 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
681 $distance[$i][$j] = $distance[$i - 1][$j - 1];
683 my $dist1 = $distance[$i][$j - 1]; #insert distance
684 my $dist2 = $distance[$i - 1][$j]; # remove
685 my $dist3 = $distance[$i - 1][$j - 1]; #replace
686 $distance[$i][$j] = 1 + edit_distance_min
($dist1, $dist2, $dist3);
690 return $distance[$len1][$len2];
693 sub find_standard_signature
{
695 my @standard_signature_tags = (
696 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
697 'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
699 foreach my $signature (@standard_signature_tags) {
700 return $signature if (get_edit_distance
($sign_off, $signature) <= 2);
706 our @typeListMisordered = (
707 qr{char\s+(?:un)?signed},
708 qr{int\s+(?:(?:un)?signed\s+)?short\s},
709 qr{int\s+short(?:\s+(?:un)?signed)},
710 qr{short\s+int(?:\s+(?:un)?signed)},
711 qr{(?:un)?signed\s+int\s+short},
712 qr{short\s+(?:un)?signed},
713 qr{long\s+int\s+(?:un)?signed},
714 qr{int\s+long\s+(?:un)?signed},
715 qr{long\s+(?:un)?signed\s+int},
716 qr{int\s+(?:un)?signed\s+long},
717 qr{int\s+(?:un)?signed},
718 qr{int\s+long\s+long\s+(?:un)?signed},
719 qr{long\s+long\s+int\s+(?:un)?signed},
720 qr{long\s+long\s+(?:un)?signed\s+int},
721 qr{long\s+long\s+(?:un)?signed},
722 qr{long\s+(?:un)?signed},
727 qr{(?:(?:un)?signed\s+)?char},
728 qr{(?:(?:un)?signed\s+)?short\s+int},
729 qr{(?:(?:un)?signed\s+)?short},
730 qr{(?:(?:un)?signed\s+)?int},
731 qr{(?:(?:un)?signed\s+)?long\s+int},
732 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
733 qr{(?:(?:un)?signed\s+)?long\s+long},
734 qr{(?:(?:un)?signed\s+)?long},
743 qr{${Ident}_handler
},
744 qr{${Ident}_handler_fn
},
748 our $C90_int_types = qr{(?x
:
749 long\s
+long\s
+int\s
+(?
:un
)?signed
|
750 long\s
+long\s
+(?
:un
)?signed\s
+int|
751 long\s
+long\s
+(?
:un
)?signed
|
752 (?
:(?
:un
)?signed\s
+)?long\s
+long\s
+int|
753 (?
:(?
:un
)?signed\s
+)?long\s
+long
|
754 int\s
+long\s
+long\s
+(?
:un
)?signed
|
755 int\s
+(?
:(?
:un
)?signed\s
+)?long\s
+long
|
757 long\s
+int\s
+(?
:un
)?signed
|
758 long\s
+(?
:un
)?signed\s
+int|
759 long\s
+(?
:un
)?signed
|
760 (?
:(?
:un
)?signed\s
+)?long\s
+int|
761 (?
:(?
:un
)?signed\s
+)?long
|
762 int\s
+long\s
+(?
:un
)?signed
|
763 int\s
+(?
:(?
:un
)?signed\s
+)?long
|
766 (?
:(?
:un
)?signed\s
+)?
int
769 our @typeListFile = ();
770 our @typeListWithAttr = (
772 qr{struct\s+$InitAttribute\s+$Ident},
773 qr{union\s+$InitAttribute\s+$Ident},
776 our @modifierList = (
779 our @modifierListFile = ();
781 our @mode_permission_funcs = (
783 ["module_param_(?:array|named|string)", 4],
784 ["module_param_array_named", 5],
785 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
786 ["proc_create(?:_data|)", 2],
787 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
788 ["IIO_DEV_ATTR_[A-Z_]+", 1],
789 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
790 ["SENSOR_TEMPLATE(?:_2|)", 3],
794 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
796 #Create a search pattern for all these functions to speed up a loop below
797 our $mode_perms_search = "";
798 foreach my $entry (@mode_permission_funcs) {
799 $mode_perms_search .= '|' if ($mode_perms_search ne "");
800 $mode_perms_search .= $entry->[0];
802 $mode_perms_search = "(?:${mode_perms_search})";
804 our %deprecated_apis = (
805 "synchronize_rcu_bh" => "synchronize_rcu",
806 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
807 "call_rcu_bh" => "call_rcu",
808 "rcu_barrier_bh" => "rcu_barrier",
809 "synchronize_sched" => "synchronize_rcu",
810 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
811 "call_rcu_sched" => "call_rcu",
812 "rcu_barrier_sched" => "rcu_barrier",
813 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
814 "cond_synchronize_sched" => "cond_synchronize_rcu",
817 #Create a search pattern for all these strings to speed up a loop below
818 our $deprecated_apis_search = "";
819 foreach my $entry (keys %deprecated_apis) {
820 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
821 $deprecated_apis_search .= $entry;
823 $deprecated_apis_search = "(?:${deprecated_apis_search})";
825 our $mode_perms_world_writable = qr{
833 our %mode_permission_string_types = (
852 #Create a search pattern for all these strings to speed up a loop below
853 our $mode_perms_string_search = "";
854 foreach my $entry (keys %mode_permission_string_types) {
855 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
856 $mode_perms_string_search .= $entry;
858 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
859 our $multi_mode_perms_string_search = qr{
860 ${single_mode_perms_string_search
}
861 (?
:\s
*\
|\s
*${single_mode_perms_string_search
})*
867 return trim
($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
874 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
875 $curpos = pos($string);
878 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
880 $to |= $mode_permission_string_types{$match};
881 $val .= '\s*\|\s*' if ($val ne "");
885 $oval =~ s/^\s*\|\s*//;
886 $oval =~ s/\s*\|\s*$//;
887 return sprintf("%04o", $to);
890 our $allowed_asm_includes = qr{(?x
:
896 # memory.h: ARM has a custom one
898 # Load common spelling mistakes and build regular expression list.
902 if (open(my $spelling, '<', $spelling_file)) {
903 while (<$spelling>) {
906 $line =~ s/\s*\n?$//g;
909 next if ($line =~ m/^\s*#/);
910 next if ($line =~ m/^\s*$/);
912 my ($suspect, $fix) = split(/\|\|/, $line);
914 $spelling_fix{$suspect} = $fix;
918 warn "No typos will be found - file '$spelling_file': $!\n";
922 if (open(my $spelling, '<', $codespellfile)) {
923 while (<$spelling>) {
926 $line =~ s/\s*\n?$//g;
929 next if ($line =~ m/^\s*#/);
930 next if ($line =~ m/^\s*$/);
931 next if ($line =~ m/, disabled/i);
935 my ($suspect, $fix) = split(/->/, $line);
937 $spelling_fix{$suspect} = $fix;
941 warn "No codespell typos will be found - file '$codespellfile': $!\n";
945 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
948 my ($wordsRef, $file) = @_;
950 if (open(my $words, '<', $file)) {
954 $line =~ s/\s*\n?$//g;
957 next if ($line =~ m/^\s*#/);
958 next if ($line =~ m/^\s*$/);
960 print("$file: '$line' invalid - ignored\n");
964 $$wordsRef .= '|' if (defined $$wordsRef);
975 if (show_type
("CONST_STRUCT")) {
976 read_words
(\
$const_structs, $conststructsfile)
977 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
980 if (defined($typedefsfile)) {
981 my $typeOtherTypedefs;
982 read_words
(\
$typeOtherTypedefs, $typedefsfile)
983 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
984 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
988 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
989 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
990 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
991 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
992 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
998 (?
:$Modifier\s
+|const\s
+)*
1000 (?
:typeof
|__typeof__
)\s
*\
([^\
)]*\
)|
1001 (?
:$typeTypedefs\b)|
1004 (?
:\s
+$Modifier|\s
+const
)*
1006 $NonptrTypeMisordered = qr{
1007 (?
:$Modifier\s
+|const\s
+)*
1011 (?
:\s
+$Modifier|\s
+const
)*
1013 $NonptrTypeWithAttr = qr{
1014 (?
:$Modifier\s
+|const\s
+)*
1016 (?
:typeof
|__typeof__
)\s
*\
([^\
)]*\
)|
1017 (?
:$typeTypedefs\b)|
1018 (?
:${allWithAttr
}\b)
1020 (?
:\s
+$Modifier|\s
+const
)*
1024 (?
:(?
:\s
|\
*|\
[\
])+\s
*const
|(?
:\s
|\
*\s
*(?
:const\s
*)?
|\
[\
])+|(?
:\s
*\
[\s
*\
])+){0,4}
1025 (?
:\s
+$Inline|\s
+$Modifier)*
1027 $TypeMisordered = qr{
1028 $NonptrTypeMisordered
1029 (?
:(?
:\s
|\
*|\
[\
])+\s
*const
|(?
:\s
|\
*\s
*(?
:const\s
*)?
|\
[\
])+|(?
:\s
*\
[\s
*\
])+){0,4}
1030 (?
:\s
+$Inline|\s
+$Modifier)*
1032 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1033 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1037 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s
*};
1039 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
1040 # requires at least perl version v5.10.0
1041 # Any use must be runtime checked with $^V
1043 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1044 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s
*};
1045 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1047 our $declaration_macros = qr{(?x
:
1048 (?
:$Storage\s
+)?
(?
:[A
-Z_
][A
-Z0
-9]*_
){0,2}(?
:DEFINE
|DECLARE
)(?
:_
[A
-Z0
-9]+){1,6}\s
*\
(|
1049 (?
:$Storage\s
+)?
[HLP
]?LIST_HEAD\s
*\
(|
1050 (?
:SKCIPHER_REQUEST
|SHASH_DESC
|AHASH_REQUEST
)_ON_STACK\s
*\
(
1053 our %allow_repeated_words = (
1060 sub deparenthesize
{
1062 return "" if (!defined($string));
1064 while ($string =~ /^\s*\(.*\)\s*$/) {
1065 $string =~ s@
^\s
*\
(\s
*@@
;
1066 $string =~ s@\s
*\
)\s
*$@@
;
1069 $string =~ s@\s
+@
@g;
1074 sub seed_camelcase_file
{
1077 return if (!(-f
$file));
1081 open(my $include_file, '<', "$file")
1082 or warn "$P: Can't read '$file' $!\n";
1083 my $text = <$include_file>;
1084 close($include_file);
1086 my @lines = split('\n', $text);
1088 foreach my $line (@lines) {
1089 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1090 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1092 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1094 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1100 our %maintained_status = ();
1102 sub is_maintained_obsolete
{
1103 my ($filename) = @_;
1105 return 0 if (!$tree || !(-e
"$root/scripts/get_maintainer.pl"));
1107 if (!exists($maintained_status{$filename})) {
1108 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1111 return $maintained_status{$filename} =~ /obsolete/i;
1114 sub is_SPDX_License_valid
{
1117 return 1 if (!$tree || which
("python3") eq "" || !(-x
"$root/scripts/spdxcheck.py") || !(-e
"$gitroot"));
1119 my $root_path = abs_path
($root);
1120 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1121 return 0 if ($status ne "");
1125 my $camelcase_seeded = 0;
1126 sub seed_camelcase_includes
{
1127 return if ($camelcase_seeded);
1130 my $camelcase_cache = "";
1131 my @include_files = ();
1133 $camelcase_seeded = 1;
1135 if (-e
"$gitroot") {
1136 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1137 chomp $git_last_include_commit;
1138 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1140 my $last_mod_date = 0;
1141 $files = `find $root/include -name "*.h"`;
1142 @include_files = split('\n', $files);
1143 foreach my $file (@include_files) {
1144 my $date = POSIX
::strftime
("%Y%m%d%H%M",
1145 localtime((stat $file)[9]));
1146 $last_mod_date = $date if ($last_mod_date < $date);
1148 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1151 if ($camelcase_cache ne "" && -f
$camelcase_cache) {
1152 open(my $camelcase_file, '<', "$camelcase_cache")
1153 or warn "$P: Can't read '$camelcase_cache' $!\n";
1154 while (<$camelcase_file>) {
1158 close($camelcase_file);
1163 if (-e
"$gitroot") {
1164 $files = `${git_command} ls-files "include/*.h"`;
1165 @include_files = split('\n', $files);
1168 foreach my $file (@include_files) {
1169 seed_camelcase_file
($file);
1172 if ($camelcase_cache ne "") {
1173 unlink glob ".checkpatch-camelcase.*";
1174 open(my $camelcase_file, '>', "$camelcase_cache")
1175 or warn "$P: Can't write '$camelcase_cache' $!\n";
1176 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1177 print $camelcase_file ("$_\n");
1179 close($camelcase_file);
1183 sub git_is_single_file
{
1184 my ($filename) = @_;
1186 return 0 if ((which
("git") eq "") || !(-e
"$gitroot"));
1188 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1189 my $count = $output =~ tr/\n//;
1190 return $count eq 1 && $output =~ m{^${filename}$};
1193 sub git_commit_info
{
1194 my ($commit, $id, $desc) = @_;
1196 return ($id, $desc) if ((which
("git") eq "") || !(-e
"$gitroot"));
1198 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1199 $output =~ s/^\s*//gm;
1200 my @lines = split("\n", $output);
1202 return ($id, $desc) if ($#lines < 0);
1204 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1205 # Maybe one day convert this block of bash into something that returns
1206 # all matching commit ids, but it's very slow...
1208 # echo "checking commits $1..."
1209 # git rev-list --remotes | grep -i "^$1" |
1210 # while read line ; do
1211 # git log --format='%H %s' -1 $line |
1212 # echo "commit $(cut -c 1-12,41-)"
1214 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1215 $lines[0] =~ /^fatal: bad object $commit/) {
1218 $id = substr($lines[0], 0, 12);
1219 $desc = substr($lines[0], 41);
1222 return ($id, $desc);
1225 $chk_signoff = 0 if ($file);
1230 my @fixed_inserted = ();
1231 my @fixed_deleted = ();
1234 # If input is git commits, extract all commits from the commit expressions.
1235 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1236 die "$P: No git repository found\n" if ($git && !-e
"$gitroot");
1240 foreach my $commit_expr (@ARGV) {
1242 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1243 $git_range = "-$2 $1";
1244 } elsif ($commit_expr =~ m/\.\./) {
1245 $git_range = "$commit_expr";
1247 $git_range = "-1 $commit_expr";
1249 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1250 foreach my $line (split(/\n/, $lines)) {
1251 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1252 next if (!defined($1) || !defined($2));
1255 unshift(@commits, $sha1);
1256 $git_commits{$sha1} = $subject;
1259 die "$P: no git commits after extraction!\n" if (@commits == 0);
1264 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1265 for my $filename (@ARGV) {
1267 my $is_git_file = git_is_single_file
($filename);
1268 my $oldfile = $file;
1269 $file = 1 if ($is_git_file);
1271 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1272 die "$P: $filename: git format-patch failed - $!\n";
1274 open($FILE, '-|', "diff -u /dev/null $filename") ||
1275 die "$P: $filename: diff failed - $!\n";
1276 } elsif ($filename eq '-') {
1277 open($FILE, '<&STDIN');
1279 open($FILE, '<', "$filename") ||
1280 die "$P: $filename: open failed - $!\n";
1282 if ($filename eq '-') {
1283 $vname = 'Your patch';
1285 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1291 push(@rawlines, $_);
1292 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1296 if ($#ARGV > 0 && $quiet == 0) {
1297 print '-' x
length($vname) . "\n";
1299 print '-' x
length($vname) . "\n";
1302 if (!process
($filename)) {
1308 @fixed_inserted = ();
1309 @fixed_deleted = ();
1311 @modifierListFile = ();
1314 $file = $oldfile if ($is_git_file);
1318 hash_show_words
(\
%use_type, "Used");
1319 hash_show_words
(\
%ignore_type, "Ignored");
1321 if (!$perl_version_ok) {
1324 NOTE
: perl
$^V is
not modern enough to detect all possible issues
.
1325 An upgrade to at least perl
$minimum_perl_version is suggested
.
1331 NOTE
: If any of the errors are false positives
, please report
1332 them to the maintainer
, see CHECKPATCH
in MAINTAINERS
.
1339 sub top_of_kernel_tree
{
1343 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1344 "README", "Documentation", "arch", "include", "drivers",
1345 "fs", "init", "ipc", "kernel", "lib", "scripts",
1348 foreach my $check (@tree_check) {
1349 if (! -e
$root . '/' . $check) {
1357 my ($formatted_email) = @_;
1361 my $name_comment = "";
1365 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1368 $comment = $3 if defined $3;
1369 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1371 $comment = $2 if defined $2;
1372 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1374 $comment = $2 if defined $2;
1375 $formatted_email =~ s/\Q$address\E.*$//;
1376 $name = $formatted_email;
1377 $name = trim
($name);
1378 $name =~ s/^\"|\"$//g;
1379 # If there's a name left after stripping spaces and
1380 # leading quotes, and the address doesn't have both
1381 # leading and trailing angle brackets, the address
1383 # "joe smith joe@smith.com" bad
1384 # "joe smith <joe@smith.com" bad
1385 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1392 # Extract comments from names excluding quoted parts
1393 # "John D. (Doe)" - Do not extract
1394 if ($name =~ s/\"(.+)\"//) {
1397 while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1398 $name_comment .= trim
($1);
1400 $name =~ s/^[ \"]+|[ \"]+$//g;
1401 $name = trim
("$quoted $name");
1403 $address = trim
($address);
1404 $address =~ s/^\<|\>$//g;
1405 $comment = trim
($comment);
1407 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1408 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1409 $name = "\"$name\"";
1412 return ($name, $name_comment, $address, $comment);
1416 my ($name, $name_comment, $address, $comment) = @_;
1418 my $formatted_email;
1420 $name =~ s/^[ \"]+|[ \"]+$//g;
1421 $address = trim
($address);
1422 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1424 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1425 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1426 $name = "\"$name\"";
1429 $name_comment = trim
($name_comment);
1430 $name_comment = " $name_comment" if ($name_comment ne "");
1431 $comment = trim
($comment);
1432 $comment = " $comment" if ($comment ne "");
1434 if ("$name" eq "") {
1435 $formatted_email = "$address";
1437 $formatted_email = "$name$name_comment <$address>";
1439 $formatted_email .= "$comment";
1440 return $formatted_email;
1443 sub reformat_email
{
1446 my ($email_name, $name_comment, $email_address, $comment) = parse_email
($email);
1447 return format_email
($email_name, $name_comment, $email_address, $comment);
1450 sub same_email_addresses
{
1451 my ($email1, $email2) = @_;
1453 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email
($email1);
1454 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email
($email2);
1456 return $email1_name eq $email2_name &&
1457 $email1_address eq $email2_address &&
1458 $name1_comment eq $name2_comment &&
1459 $comment1 eq $comment2;
1465 foreach my $path (split(/:/, $ENV{PATH
})) {
1466 if (-e
"$path/$bin") {
1467 return "$path/$bin";
1477 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1478 if (-e
"$path/$conf") {
1479 return "$path/$conf";
1491 for my $c (split(//, $str)) {
1495 for (; ($n % $tabsize) != 0; $n++) {
1507 (my $res = shift) =~ tr/\t/ /c;
1514 # Drop the diff line leader and expand tabs
1516 $line = expand_tabs
($line);
1518 # Pick the indent from the front of the line.
1519 my ($white) = ($line =~ /^(\s*)/);
1521 return (length($line), length($white));
1524 my $sanitise_quote = '';
1526 sub sanitise_line_reset
{
1527 my ($in_comment) = @_;
1530 $sanitise_quote = '*/';
1532 $sanitise_quote = '';
1545 # Always copy over the diff marker.
1546 $res = substr($line, 0, 1);
1548 for ($off = 1; $off < length($line); $off++) {
1549 $c = substr($line, $off, 1);
1551 # Comments we are whacking completely including the begin
1552 # and end, all to $;.
1553 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1554 $sanitise_quote = '*/';
1556 substr($res, $off, 2, "$;$;");
1560 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1561 $sanitise_quote = '';
1562 substr($res, $off, 2, "$;$;");
1566 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1567 $sanitise_quote = '//';
1569 substr($res, $off, 2, $sanitise_quote);
1574 # A \ in a string means ignore the next character.
1575 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1577 substr($res, $off, 2, 'XX');
1582 if ($c eq "'" || $c eq '"') {
1583 if ($sanitise_quote eq '') {
1584 $sanitise_quote = $c;
1586 substr($res, $off, 1, $c);
1588 } elsif ($sanitise_quote eq $c) {
1589 $sanitise_quote = '';
1593 #print "c<$c> SQ<$sanitise_quote>\n";
1594 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1595 substr($res, $off, 1, $;);
1596 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1597 substr($res, $off, 1, $;);
1598 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1599 substr($res, $off, 1, 'X');
1601 substr($res, $off, 1, $c);
1605 if ($sanitise_quote eq '//') {
1606 $sanitise_quote = '';
1609 # The pathname on a #include may be surrounded by '<' and '>'.
1610 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1611 my $clean = 'X' x
length($1);
1612 $res =~ s@\
<.*\
>@
<$clean>@
;
1614 # The whole of a #error is a string.
1615 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1616 my $clean = 'X' x
length($1);
1617 $res =~ s@
(\#\s
*(?
:error
|warning
)\s
+).*@
$1$clean@
;
1620 if ($allow_c99_comments && $res =~ m@
(//.*$)@
) {
1622 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1628 sub get_quoted_string
{
1629 my ($line, $rawline) = @_;
1631 return "" if (!defined($line) || !defined($rawline));
1632 return "" if ($line !~ m/($String)/g);
1633 return substr($rawline, $-[0], $+[0] - $-[0]);
1636 sub ctx_statement_block
{
1637 my ($linenr, $remain, $off) = @_;
1638 my $line = $linenr - 1;
1641 my $coff = $off - 1;
1655 @stack = (['', 0]) if ($#stack == -1);
1657 #warn "CSB: blk<$blk> remain<$remain>\n";
1658 # If we are about to drop off the end, pull in more
1661 for (; $remain > 0; $line++) {
1662 last if (!defined $lines[$line]);
1663 next if ($lines[$line] =~ /^-/);
1666 $blk .= $lines[$line] . "\n";
1667 $len = length($blk);
1671 # Bail if there is no further context.
1672 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1676 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1682 $c = substr($blk, $off, 1);
1683 $remainder = substr($blk, $off);
1685 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1687 # Handle nested #if/#else.
1688 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1689 push(@stack, [ $type, $level ]);
1690 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1691 ($type, $level) = @
{$stack[$#stack - 1]};
1692 } elsif ($remainder =~ /^#\s*endif\b/) {
1693 ($type, $level) = @
{pop(@stack)};
1696 # Statement ends at the ';' or a close '}' at the
1698 if ($level == 0 && $c eq ';') {
1702 # An else is really a conditional as long as its not else if
1703 if ($level == 0 && $coff_set == 0 &&
1704 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1705 $remainder =~ /^(else)(?:\s|{)/ &&
1706 $remainder !~ /^else\s+if\b/) {
1707 $coff = $off + length($1) - 1;
1709 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1710 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1713 if (($type eq '' || $type eq '(') && $c eq '(') {
1717 if ($type eq '(' && $c eq ')') {
1719 $type = ($level != 0)?
'(' : '';
1721 if ($level == 0 && $coff < $soff) {
1724 #warn "CSB: mark coff<$coff>\n";
1727 if (($type eq '' || $type eq '{') && $c eq '{') {
1731 if ($type eq '{' && $c eq '}') {
1733 $type = ($level != 0)?
'{' : '';
1736 if (substr($blk, $off + 1, 1) eq ';') {
1742 # Preprocessor commands end at the newline unless escaped.
1743 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1751 # We are truly at the end, so shuffle to the next line.
1758 my $statement = substr($blk, $soff, $off - $soff + 1);
1759 my $condition = substr($blk, $soff, $coff - $soff + 1);
1761 #warn "STATEMENT<$statement>\n";
1762 #warn "CONDITION<$condition>\n";
1764 #print "coff<$coff> soff<$off> loff<$loff>\n";
1766 return ($statement, $condition,
1767 $line, $remain + 1, $off - $loff + 1, $level);
1770 sub statement_lines
{
1773 # Strip the diff line prefixes and rip blank lines at start and end.
1774 $stmt =~ s/(^|\n)./$1/g;
1778 my @stmt_lines = ($stmt =~ /\n/g);
1780 return $#stmt_lines + 2;
1783 sub statement_rawlines
{
1786 my @stmt_lines = ($stmt =~ /\n/g);
1788 return $#stmt_lines + 2;
1791 sub statement_block_size
{
1794 $stmt =~ s/(^|\n)./$1/g;
1800 my @stmt_lines = ($stmt =~ /\n/g);
1801 my @stmt_statements = ($stmt =~ /;/g);
1803 my $stmt_lines = $#stmt_lines + 2;
1804 my $stmt_statements = $#stmt_statements + 1;
1806 if ($stmt_lines > $stmt_statements) {
1809 return $stmt_statements;
1813 sub ctx_statement_full
{
1814 my ($linenr, $remain, $off) = @_;
1815 my ($statement, $condition, $level);
1819 # Grab the first conditional/block pair.
1820 ($statement, $condition, $linenr, $remain, $off, $level) =
1821 ctx_statement_block
($linenr, $remain, $off);
1822 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1823 push(@chunks, [ $condition, $statement ]);
1824 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1825 return ($level, $linenr, @chunks);
1828 # Pull in the following conditional/block pairs and see if they
1829 # could continue the statement.
1831 ($statement, $condition, $linenr, $remain, $off, $level) =
1832 ctx_statement_block
($linenr, $remain, $off);
1833 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1834 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1836 push(@chunks, [ $condition, $statement ]);
1839 return ($level, $linenr, @chunks);
1843 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1845 my $start = $linenr - 1;
1852 my @stack = ($level);
1853 for ($line = $start; $remain > 0; $line++) {
1854 next if ($rawlines[$line] =~ /^-/);
1857 $blk .= $rawlines[$line];
1859 # Handle nested #if/#else.
1860 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1861 push(@stack, $level);
1862 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1863 $level = $stack[$#stack - 1];
1864 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1865 $level = pop(@stack);
1868 foreach my $c (split(//, $lines[$line])) {
1869 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1875 if ($c eq $close && $level > 0) {
1877 last if ($level == 0);
1878 } elsif ($c eq $open) {
1883 if (!$outer || $level <= 1) {
1884 push(@res, $rawlines[$line]);
1887 last if ($level == 0);
1890 return ($level, @res);
1892 sub ctx_block_outer
{
1893 my ($linenr, $remain) = @_;
1895 my ($level, @r) = ctx_block_get
($linenr, $remain, 1, '{', '}', 0);
1899 my ($linenr, $remain) = @_;
1901 my ($level, @r) = ctx_block_get
($linenr, $remain, 0, '{', '}', 0);
1905 my ($linenr, $remain, $off) = @_;
1907 my ($level, @r) = ctx_block_get
($linenr, $remain, 0, '(', ')', $off);
1910 sub ctx_block_level
{
1911 my ($linenr, $remain) = @_;
1913 return ctx_block_get
($linenr, $remain, 0, '{', '}', 0);
1915 sub ctx_statement_level
{
1916 my ($linenr, $remain, $off) = @_;
1918 return ctx_block_get
($linenr, $remain, 0, '(', ')', $off);
1921 sub ctx_locate_comment
{
1922 my ($first_line, $end_line) = @_;
1924 # If c99 comment on the current line, or the line before or after
1925 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@
^\
+.*(//.*$)@
);
1926 return $current_comment if (defined $current_comment);
1927 ($current_comment) = ($rawlines[$end_line - 2] =~ m@
^[\
+ ].*(//.*$)@
);
1928 return $current_comment if (defined $current_comment);
1929 ($current_comment) = ($rawlines[$end_line] =~ m@
^[\
+ ].*(//.*$)@
);
1930 return $current_comment if (defined $current_comment);
1932 # Catch a comment on the end of the line itself.
1933 ($current_comment) = ($rawlines[$end_line - 1] =~ m@
.*(/\*.*\*/)\s
*(?
:\\\s
*)?
$@
);
1934 return $current_comment if (defined $current_comment);
1936 # Look through the context and try and figure out if there is a
1939 $current_comment = '';
1940 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1941 my $line = $rawlines[$linenr - 1];
1943 if ($linenr == $first_line and $line =~ m@
^.\s
*\
*@
) {
1946 if ($line =~ m@
/\
*@
) {
1949 if (!$in_comment && $current_comment ne '') {
1950 $current_comment = '';
1952 $current_comment .= $line . "\n" if ($in_comment);
1953 if ($line =~ m@\
*/@
) {
1958 chomp($current_comment);
1959 return($current_comment);
1961 sub ctx_has_comment
{
1962 my ($first_line, $end_line) = @_;
1963 my $cmt = ctx_locate_comment
($first_line, $end_line);
1965 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1966 ##print "CMMT: $cmt\n";
1968 return ($cmt ne '');
1972 my ($linenr, $cnt) = @_;
1974 my $offset = $linenr - 1;
1979 $line = $rawlines[$offset++];
1980 next if (defined($line) && $line =~ /^-/);
1988 my ($linenr, $lc) = @_;
1990 my $stat_real = raw_line
($linenr, 0);
1991 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1992 $stat_real = $stat_real . "\n" . raw_line
($count, 0);
1999 my ($linenr, $cnt, $here) = @_;
2001 my $herectx = $here . "\n";
2002 for (my $n = 0; $n < $cnt; $n++) {
2003 $herectx .= raw_line
($linenr, $n) . "\n";
2014 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2017 $coded = sprintf("^%c", unpack('C', $2) + 64);
2026 my $av_preprocessor = 0;
2031 sub annotate_reset
{
2032 $av_preprocessor = 0;
2034 @av_paren_type = ('E');
2035 $av_pend_colon = 'O';
2038 sub annotate_values
{
2039 my ($stream, $type) = @_;
2042 my $var = '_' x
length($stream);
2045 print "$stream\n" if ($dbg_values > 1);
2047 while (length($cur)) {
2048 @av_paren_type = ('E') if ($#av_paren_type < 0);
2049 print " <" . join('', @av_paren_type) .
2050 "> <$type> <$av_pending>" if ($dbg_values > 1);
2051 if ($cur =~ /^(\s+)/o) {
2052 print "WS($1)\n" if ($dbg_values > 1);
2053 if ($1 =~ /\n/ && $av_preprocessor) {
2054 $type = pop(@av_paren_type);
2055 $av_preprocessor = 0;
2058 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2059 print "CAST($1)\n" if ($dbg_values > 1);
2060 push(@av_paren_type, $type);
2063 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2064 print "DECLARE($1)\n" if ($dbg_values > 1);
2067 } elsif ($cur =~ /^($Modifier)\s*/) {
2068 print "MODIFIER($1)\n" if ($dbg_values > 1);
2071 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2072 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2073 $av_preprocessor = 1;
2074 push(@av_paren_type, $type);
2080 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2081 print "UNDEF($1)\n" if ($dbg_values > 1);
2082 $av_preprocessor = 1;
2083 push(@av_paren_type, $type);
2085 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2086 print "PRE_START($1)\n" if ($dbg_values > 1);
2087 $av_preprocessor = 1;
2089 push(@av_paren_type, $type);
2090 push(@av_paren_type, $type);
2093 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2094 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2095 $av_preprocessor = 1;
2097 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2101 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2102 print "PRE_END($1)\n" if ($dbg_values > 1);
2104 $av_preprocessor = 1;
2106 # Assume all arms of the conditional end as this
2107 # one does, and continue as if the #endif was not here.
2108 pop(@av_paren_type);
2109 push(@av_paren_type, $type);
2112 } elsif ($cur =~ /^(\\\n)/o) {
2113 print "PRECONT($1)\n" if ($dbg_values > 1);
2115 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2116 print "ATTR($1)\n" if ($dbg_values > 1);
2117 $av_pending = $type;
2120 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2121 print "SIZEOF($1)\n" if ($dbg_values > 1);
2127 } elsif ($cur =~ /^(if|while|for)\b/o) {
2128 print "COND($1)\n" if ($dbg_values > 1);
2132 } elsif ($cur =~/^(case)/o) {
2133 print "CASE($1)\n" if ($dbg_values > 1);
2134 $av_pend_colon = 'C';
2137 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2138 print "KEYWORD($1)\n" if ($dbg_values > 1);
2141 } elsif ($cur =~ /^(\()/o) {
2142 print "PAREN('$1')\n" if ($dbg_values > 1);
2143 push(@av_paren_type, $av_pending);
2147 } elsif ($cur =~ /^(\))/o) {
2148 my $new_type = pop(@av_paren_type);
2149 if ($new_type ne '_') {
2151 print "PAREN('$1') -> $type\n"
2152 if ($dbg_values > 1);
2154 print "PAREN('$1')\n" if ($dbg_values > 1);
2157 } elsif ($cur =~ /^($Ident)\s*\(/o) {
2158 print "FUNC($1)\n" if ($dbg_values > 1);
2162 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2163 if (defined $2 && $type eq 'C' || $type eq 'T') {
2164 $av_pend_colon = 'B';
2165 } elsif ($type eq 'E') {
2166 $av_pend_colon = 'L';
2168 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2171 } elsif ($cur =~ /^($Ident|$Constant)/o) {
2172 print "IDENT($1)\n" if ($dbg_values > 1);
2175 } elsif ($cur =~ /^($Assignment)/o) {
2176 print "ASSIGN($1)\n" if ($dbg_values > 1);
2179 } elsif ($cur =~/^(;|{|})/) {
2180 print "END($1)\n" if ($dbg_values > 1);
2182 $av_pend_colon = 'O';
2184 } elsif ($cur =~/^(,)/) {
2185 print "COMMA($1)\n" if ($dbg_values > 1);
2188 } elsif ($cur =~ /^(\?)/o) {
2189 print "QUESTION($1)\n" if ($dbg_values > 1);
2192 } elsif ($cur =~ /^(:)/o) {
2193 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2195 substr($var, length($res), 1, $av_pend_colon);
2196 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2201 $av_pend_colon = 'O';
2203 } elsif ($cur =~ /^(\[)/o) {
2204 print "CLOSE($1)\n" if ($dbg_values > 1);
2207 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2210 print "OPV($1)\n" if ($dbg_values > 1);
2217 substr($var, length($res), 1, $variant);
2220 } elsif ($cur =~ /^($Operators)/o) {
2221 print "OP($1)\n" if ($dbg_values > 1);
2222 if ($1 ne '++' && $1 ne '--') {
2226 } elsif ($cur =~ /(^.)/o) {
2227 print "C($1)\n" if ($dbg_values > 1);
2230 $cur = substr($cur, length($1));
2231 $res .= $type x
length($1);
2235 return ($res, $var);
2239 my ($possible, $line) = @_;
2240 my $notPermitted = qr{(?
:
2257 ^(?
:typedef
|struct
|enum
)\b
2259 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2260 if ($possible !~ $notPermitted) {
2261 # Check for modifiers.
2262 $possible =~ s/\s*$Storage\s*//g;
2263 $possible =~ s/\s*$Sparse\s*//g;
2264 if ($possible =~ /^\s*$/) {
2266 } elsif ($possible =~ /\s/) {
2267 $possible =~ s/\s*$Type\s*//g;
2268 for my $modifier (split(' ', $possible)) {
2269 if ($modifier !~ $notPermitted) {
2270 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2271 push(@modifierListFile, $modifier);
2276 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2277 push(@typeListFile, $possible);
2281 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2290 $type =~ tr/[a-z]/[A-Z]/;
2292 return defined $use_type{$type} if (scalar keys %use_type > 0);
2294 return !defined $ignore_type{$type};
2298 my ($level, $type, $msg) = @_;
2300 if (!show_type
($type) ||
2301 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2306 if ($level eq 'ERROR') {
2308 } elsif ($level eq 'WARNING') {
2314 $output .= $prefix . $level . ':';
2316 $output .= BLUE
if ($color);
2317 $output .= "$type:";
2319 $output .= RESET
if ($color);
2320 $output .= ' ' . $msg . "\n";
2323 my @lines = split("\n", $output, -1);
2324 splice(@lines, 1, 1);
2325 $output = join("\n", @lines);
2329 $output = (split('\n', $output))[0] . "\n";
2332 if ($verbose && exists($verbose_messages{$type}) &&
2333 !exists($verbose_emitted{$type})) {
2334 $output .= $verbose_messages{$type} . "\n\n";
2335 $verbose_emitted{$type} = 1;
2338 push(our @report, $output);
2347 sub fixup_current_range
{
2348 my ($lineRef, $offset, $length) = @_;
2350 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2353 my $no = $o + $offset;
2354 my $nl = $l + $length;
2355 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2359 sub fix_inserted_deleted_lines
{
2360 my ($linesRef, $insertedRef, $deletedRef) = @_;
2362 my $range_last_linenr = 0;
2363 my $delta_offset = 0;
2368 my $next_insert = 0;
2369 my $next_delete = 0;
2373 my $inserted = @
{$insertedRef}[$next_insert++];
2374 my $deleted = @
{$deletedRef}[$next_delete++];
2376 foreach my $old_line (@
{$linesRef}) {
2378 my $line = $old_line; #don't modify the array
2379 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2381 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2382 $range_last_linenr = $new_linenr;
2383 fixup_current_range
(\
$line, $delta_offset, 0);
2386 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2387 $deleted = @
{$deletedRef}[$next_delete++];
2389 fixup_current_range
(\
$lines[$range_last_linenr], $delta_offset--, -1);
2392 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2393 push(@lines, ${$inserted}{'LINE'});
2394 $inserted = @
{$insertedRef}[$next_insert++];
2396 fixup_current_range
(\
$lines[$range_last_linenr], $delta_offset++, 1);
2400 push(@lines, $line);
2410 sub fix_insert_line
{
2411 my ($linenr, $line) = @_;
2417 push(@fixed_inserted, $inserted);
2420 sub fix_delete_line
{
2421 my ($linenr, $line) = @_;
2428 push(@fixed_deleted, $deleted);
2432 my ($type, $msg) = @_;
2434 if (report
("ERROR", $type, $msg)) {
2442 my ($type, $msg) = @_;
2444 if (report
("WARNING", $type, $msg)) {
2452 my ($type, $msg) = @_;
2454 if ($check && report
("CHECK", $type, $msg)) {
2462 sub check_absolute_file
{
2463 my ($absolute, $herecurr) = @_;
2464 my $file = $absolute;
2466 ##print "absolute<$absolute>\n";
2468 # See if any suffix of this path is a path within the tree.
2469 while ($file =~ s@
^[^/]*/@@
) {
2470 if (-f
"$root/$file") {
2471 ##print "file<$file>\n";
2479 # It is, so see if the prefix is acceptable.
2480 my $prefix = $absolute;
2481 substr($prefix, -length($file)) = '';
2483 ##print "prefix<$prefix>\n";
2484 if ($prefix ne ".../") {
2485 WARN
("USE_RELATIVE_PATH",
2486 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2493 $string =~ s/^\s+|\s+$//g;
2501 $string =~ s/^\s+//;
2509 $string =~ s/\s+$//;
2514 sub string_find_replace
{
2515 my ($string, $find, $replace) = @_;
2517 $string =~ s/$find/$replace/g;
2525 my $source_indent = $tabsize;
2526 my $max_spaces_before_tab = $source_indent - 1;
2527 my $spaces_to_tab = " " x
$source_indent;
2529 #convert leading spaces to tabs
2530 1 while $leading =~ s@
^([\t]*)$spaces_to_tab@
$1\t@g;
2531 #Remove spaces before a tab
2532 1 while $leading =~ s@
^([\t]*)( {1,$max_spaces_before_tab})\t@
$1\t@g;
2537 sub pos_last_openparen
{
2542 my $opens = $line =~ tr/\(/\(/;
2543 my $closes = $line =~ tr/\)/\)/;
2545 my $last_openparen = 0;
2547 if (($opens == 0) || ($closes >= $opens)) {
2551 my $len = length($line);
2553 for ($pos = 0; $pos < $len; $pos++) {
2554 my $string = substr($line, $pos);
2555 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2556 $pos += length($1) - 1;
2557 } elsif (substr($line, $pos, 1) eq '(') {
2558 $last_openparen = $pos;
2559 } elsif (index($string, '(') == -1) {
2564 return length(expand_tabs
(substr($line, 0, $last_openparen))) + 1;
2567 sub get_raw_comment
{
2568 my ($line, $rawline) = @_;
2571 for my $i (0 .. (length($line) - 1)) {
2572 if (substr($line, $i, 1) eq "$;") {
2573 $comment .= substr($rawline, $i, 1);
2581 # line: Patch line to check
2582 # auto: Auto variable name, e.g. "per_child_auto"
2583 # suffix: Suffix to expect on member, e.g. "_priv"
2584 # warning: Warning name, e.g. "PRIV_AUTO"
2585 sub u_boot_struct_name
{
2586 my ($line, $auto, $suffix, $warning, $herecurr) = @_;
2588 # Use _priv as a suffix for the device-private data struct
2589 if ($line =~ /^\+\s*\.${auto}\s*=\s*sizeof\(struct\((\w+)\).*/) {
2590 my $struct_name = $1;
2591 if ($struct_name !~ /^\w+${suffix}/) {
2593 "struct \'$struct_name\' should have a ${suffix} suffix\n"
2599 # Checks specific to U-Boot
2601 my ($realfile, $line, $rawline, $herecurr) = @_;
2603 # ask for a test if a new uclass ID is added
2604 if ($realfile =~ /uclass-id.h/ && $line =~ /^\+/) {
2606 "Possible new uclass - make sure to add a sandbox driver, plus a test in test/dm/<name>.c\n" . $herecurr);
2609 # try to get people to use the livetree API, except when changing tooling
2610 if ($line =~ /^\+.*fdtdec_/ && $realfile !~ /^tools\//) {
2612 "Use the livetree API (dev_read_...)\n" . $herecurr);
2615 # add tests for new commands
2616 if ($line =~ /^\+.*do_($Ident)\(struct cmd_tbl.*/) {
2618 "Possible new command - make sure you add a test\n" . $herecurr);
2621 # use if instead of #if
2622 if ($realfile =~ /\.c$/ && $line =~ /^\+#if.*CONFIG.*/) {
2624 "Use 'if (IS_ENABLED(CONFIG...))' instead of '#if or #ifdef' where possible\n" . $herecurr);
2627 # prefer strl(cpy|cat) over strn(cpy|cat)
2628 if ($line =~ /\bstrn(cpy|cat)\s*\(/) {
2630 "strl$1 is preferred over strn$1 because it always produces a nul-terminated string\n" . $herecurr);
2633 # use Kconfig for all CONFIG symbols
2634 if ($line =~ /\+\s*#\s*(define|undef)\s+(CONFIG_\w*)\b/) {
2635 ERROR
("DEFINE_CONFIG_SYM",
2636 "All CONFIG symbols are managed by Kconfig\n" . $herecurr);
2639 # Don't put dm.h in header files
2640 if ($realfile =~ /\.h$/ && $rawline =~ /^\+#include\s*<dm\.h>*/) {
2641 ERROR
("BARRED_INCLUDE_IN_HDR",
2642 "Avoid including common.h and dm.h in header files\n" . $herecurr);
2645 # Don't add common.h to files
2646 if ($rawline =~ /^\+#include\s*<common\.h>*/) {
2647 ERROR
("BARRED_INCLUDE_COMMON_H",
2648 "Do not add common.h to files\n" . $herecurr);
2651 # Do not disable fdt / initrd relocation
2652 if ($rawline =~ /^\+.*(fdt|initrd)_high=0xffffffff/) {
2653 ERROR
("DISABLE_FDT_OR_INITRD_RELOC",
2654 "fdt or initrd relocation disabled at boot time\n" . $herecurr);
2657 # make sure 'skip_board_fixup' is not
2658 if ($rawline =~ /.*skip_board_fixup.*/) {
2659 ERROR
("SKIP_BOARD_FIXUP",
2660 "Avoid setting skip_board_fixup env variable\n" . $herecurr);
2663 # Do not use CONFIG_ prefix in CONFIG_IS_ENABLED() calls
2664 if ($line =~ /^\+.*CONFIG_IS_ENABLED\(CONFIG_\w*\).*/) {
2665 ERROR
("CONFIG_IS_ENABLED_CONFIG",
2666 "CONFIG_IS_ENABLED() takes values without the CONFIG_ prefix\n" . $herecurr);
2669 # Use _priv as a suffix for the device-private data struct
2670 if ($line =~ /^\+\s*\.priv_auto\s*=\s*sizeof\(struct\((\w+)\).*/) {
2671 my $struct_name = $1;
2672 if ($struct_name !~ /^\w+_priv/) {
2673 WARN
("PRIV_AUTO", "struct \'$struct_name\' should have a _priv suffix");
2677 # Check struct names for the 'auto' members of struct driver
2678 u_boot_struct_name
($line, "priv_auto", "_priv", "PRIV_AUTO", $herecurr);
2679 u_boot_struct_name
($line, "plat_auto", "_plat", "PLAT_AUTO", $herecurr);
2680 u_boot_struct_name
($line, "per_child_auto", "_priv", "CHILD_PRIV_AUTO", $herecurr);
2681 u_boot_struct_name
($line, "per_child_plat_auto", "_plat",
2682 "CHILD_PLAT_AUTO", $herecurr);
2684 # Now the ones for struct uclass, skipping those in common with above
2685 u_boot_struct_name
($line, "per_device_auto", "_priv",
2686 "DEVICE_PRIV_AUTO", $herecurr);
2687 u_boot_struct_name
($line, "per_device_plat_auto", "_plat",
2688 "DEVICE_PLAT_AUTO", $herecurr);
2690 # Avoid using the pre-schema driver model tags
2691 if ($line =~ /^\+.*u-boot,dm-.*/) {
2693 "Driver model schema uses 'bootph-...' tags now\n" . $herecurr);
2697 sub exclude_global_initialisers
{
2698 my ($realfile) = @_;
2700 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2701 return $realfile =~ m@
^tools
/testing
/selftests
/bpf
/progs/.*\
.c
$@
||
2702 $realfile =~ m@
^samples
/bpf/.*_kern\
.c
$@
||
2703 $realfile =~ m@
/bpf/.*\
.bpf\
.c
$@
;
2707 my $filename = shift;
2713 my $stashrawline="";
2723 my $authorsignoff = 0;
2724 my $author_sob = '';
2726 my $is_binding_patch = -1;
2727 my $in_header_lines = $file ?
0 : 1;
2728 my $in_commit_log = 0; #Scanning lines before patch
2729 my $has_patch_separator = 0; #Found a --- line
2730 my $has_commit_log = 0; #Encountered lines before patch
2731 my $commit_log_lines = 0; #Number of commit log lines
2732 my $commit_log_possible_stack_dump = 0;
2733 my $commit_log_long_line = 0;
2734 my $commit_log_has_diff = 0;
2735 my $reported_maintainer_file = 0;
2736 my $non_utf8_charset = 0;
2738 my $last_git_commit_id_linenr = -1;
2740 my $last_blank_line = 0;
2741 my $last_coalesced_string_linenr = -1;
2749 # Trace the real file/line as we go.
2754 my $context_function; #undef'd unless there's a known function
2756 my $comment_edge = 0;
2760 my $prev_values = 'E';
2763 my %suppress_ifbraces;
2764 my %suppress_whiletrailers;
2765 my %suppress_export;
2766 my $suppress_statement = 0;
2768 my %signatures = ();
2770 # Pre-scan the patch sanitizing the lines.
2771 # Pre-scan the patch looking for any __setup documentation.
2773 my @setup_docs = ();
2776 my $camelcase_file_seeded = 0;
2778 my $checklicenseline = 1;
2780 sanitise_line_reset
();
2782 foreach my $rawline (@rawlines) {
2786 push(@fixed, $rawline) if ($fix);
2788 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2790 if ($1 =~ m
@Documentation/admin-guide/kernel
-parameters
.txt
$@
) {
2795 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2804 # Guestimate if this is a continuing comment. Run
2805 # the context looking for a comment "edge". If this
2806 # edge is a close comment then we must be in a comment
2810 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2811 next if (defined $rawlines[$ln - 1] &&
2812 $rawlines[$ln - 1] =~ /^-/);
2814 #print "RAW<$rawlines[$ln - 1]>\n";
2815 last if (!defined $rawlines[$ln - 1]);
2816 if ($rawlines[$ln - 1] =~ m@
(/\*|\*/)@
&&
2817 $rawlines[$ln - 1] !~ m@
"[^"]*(?
:/\*|\*/)[^"]*"@
) {
2822 if (defined $edge && $edge eq '*/') {
2826 # Guestimate if this is a continuing comment. If this
2827 # is the start of a diff block and this line starts
2828 # ' *' then it is very likely a comment.
2829 if (!defined $edge &&
2830 $rawlines[$linenr] =~ m@
^.\s
*(?
:\
*\
*+| \
*)(?
:\s
|$)@
)
2835 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2836 sanitise_line_reset
($in_comment);
2838 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2839 # Standardise the strings and chars within the input to
2840 # simplify matching -- only bother with positive lines.
2841 $line = sanitise_line
($rawline);
2843 push(@lines, $line);
2846 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2851 #print "==>$rawline\n";
2852 #print "-->$line\n";
2854 if ($setup_docs && $line =~ /^\+/) {
2855 push(@setup_docs, $line);
2864 foreach my $line (@lines) {
2867 my $sline = $line; #copy of $line
2868 $sline =~ s/$;/ /g; #with comments as spaces
2870 my $rawline = $rawlines[$linenr - 1];
2871 my $raw_comment = get_raw_comment
($line, $rawline);
2873 # check if it's a mode change, rename or start of a patch
2874 if (!$in_commit_log &&
2875 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2876 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2877 $line =~ /^diff --git a\/[\w\
/\.\_\-]+ b\/\S
+\s
*$/))) {
2881 #extract the line range in the file after the patch is applied
2882 if (!$in_commit_log &&
2883 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2886 $first_line = $linenr + 1;
2896 %suppress_ifbraces = ();
2897 %suppress_whiletrailers = ();
2898 %suppress_export = ();
2899 $suppress_statement = 0;
2900 if ($context =~ /\b(\w+)\s*\(/) {
2901 $context_function = $1;
2903 undef $context_function;
2907 # track the line number as we move through the hunk, note that
2908 # new versions of GNU diff omit the leading space on completely
2909 # blank context lines so we need to count that too.
2910 } elsif ($line =~ /^( |\+|$)/) {
2912 $realcnt-- if ($realcnt != 0);
2914 # Measure the line length and indent.
2915 ($length, $indent) = line_stats
($rawline);
2917 # Track the previous line.
2918 ($prevline, $stashline) = ($stashline, $line);
2919 ($previndent, $stashindent) = ($stashindent, $indent);
2920 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2922 #warn "line<$line>\n";
2924 } elsif ($realcnt == 1) {
2928 my $hunk_line = ($realcnt != 0);
2930 $here = "#$linenr: " if (!$file);
2931 $here = "#$realline: " if ($file);
2934 # extract the filename as it passes
2935 if ($line =~ /^diff --git.*?(\S+)$/) {
2937 $realfile =~ s@
^([^/]*)/@@
if (!$file);
2940 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2942 $realfile =~ s@
^([^/]*)/@@
if (!$file);
2946 if (!$file && $tree && $p1_prefix ne '' &&
2947 -e
"$root/$p1_prefix") {
2948 WARN
("PATCH_PREFIX",
2949 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2952 if ($realfile =~ m@
^include
/asm/@
) {
2953 ERROR
("MODIFIED_INCLUDE_ASM",
2954 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2959 #make up the handle for any error we report on this line
2961 $prefix = "$realfile:$realline: "
2964 $prefix = "$filename:$realline: ";
2966 $prefix = "$filename:$linenr: ";
2971 if (is_maintained_obsolete
($realfile)) {
2973 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2975 if ($realfile =~ m@
^(?
:drivers
/net
/|net
/|drivers
/staging/)@
) {
2978 $check = $check_orig;
2980 $checklicenseline = 1;
2982 if ($realfile !~ /^MAINTAINERS/) {
2983 my $last_binding_patch = $is_binding_patch;
2985 $is_binding_patch = () = $realfile =~ m@
^(?
:Documentation
/devicetree/|include
/dt-bindings/)@
;
2987 if (($last_binding_patch != -1) &&
2988 ($last_binding_patch ^ $is_binding_patch)) {
2989 WARN
("DT_SPLIT_BINDING_PATCH",
2990 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2997 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2999 my $hereline = "$here\n$rawline\n";
3000 my $herecurr = "$here\n$rawline\n";
3001 my $hereprev = "$here\n$prevrawline\n$rawline\n";
3003 $cnt_lines++ if ($realcnt != 0);
3005 # Verify the existence of a commit log if appropriate
3006 # 2 is used because a $signature is counted in $commit_log_lines
3007 if ($in_commit_log) {
3008 if ($line !~ /^\s*$/) {
3009 $commit_log_lines++; #could be a $signature
3011 } elsif ($has_commit_log && $commit_log_lines < 2) {
3012 WARN
("COMMIT_MESSAGE",
3013 "Missing commit description - Add an appropriate one\n");
3014 $commit_log_lines = 2; #warn only once
3017 # Check if the commit log has what seems like a diff which can confuse patch
3018 if ($in_commit_log && !$commit_log_has_diff &&
3019 (($line =~ m@
^\s
+diff
\b.*a
/([\w/]+)@
&&
3020 $line =~ m@
^\s
+diff
\b.*a
/[\w/]+\s
+b
/$1\b@
) ||
3021 $line =~ m@
^\s
*(?
:\
-\
-\
-\s
+a
/|\+\+\+\s+b/)@
||
3022 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
3023 ERROR
("DIFF_IN_COMMIT_MSG",
3024 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
3025 $commit_log_has_diff = 1;
3028 # Check for incorrect file permissions
3029 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
3030 my $permhere = $here . "FILE: $realfile\n";
3031 if ($realfile !~ m
@scripts/@
&&
3032 $realfile !~ /\.(py|pl|awk|sh)$/) {
3033 ERROR
("EXECUTE_PERMISSIONS",
3034 "do not set execute permissions for source files\n" . $permhere);
3038 # Check the patch for a From:
3039 if (decode
("MIME-Header", $line) =~ /^From:\s*(.*)/) {
3041 my $curline = $linenr;
3042 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
3045 $author = encode
("utf8", $author) if ($line =~ /=\?utf-8\?/i);
3047 $author = reformat_email
($author);
3050 # Check the patch for a signoff:
3051 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
3054 if ($author ne '' && $authorsignoff != 1) {
3055 if (same_email_addresses
($1, $author)) {
3059 my ($email_name, $email_comment, $email_address, $comment1) = parse_email
($ctx);
3060 my ($author_name, $author_comment, $author_address, $comment2) = parse_email
($author);
3062 if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
3065 } elsif (lc $email_address eq lc $author_address) {
3068 } elsif ($email_name eq $author_name) {
3072 my $address1 = $email_address;
3073 my $address2 = $author_address;
3075 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
3078 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
3081 if ($address1 eq $address2) {
3089 # Check for patch separator
3090 if ($line =~ /^---$/) {
3091 $has_patch_separator = 1;
3095 # Check if MAINTAINERS is being updated. If so, there's probably no need to
3096 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
3097 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3098 $reported_maintainer_file = 1;
3101 # Check signature styles
3102 if (!$in_header_lines &&
3103 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3104 my $space_before = $1;
3106 my $space_after = $3;
3108 my $ucfirst_sign_off = ucfirst(lc($sign_off));
3110 if ($sign_off !~ /$signature_tags/) {
3111 my $suggested_signature = find_standard_signature
($sign_off);
3112 if ($suggested_signature eq "") {
3113 WARN
("BAD_SIGN_OFF",
3114 "Non-standard signature: $sign_off\n" . $herecurr);
3116 if (WARN
("BAD_SIGN_OFF",
3117 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3119 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3123 if (defined $space_before && $space_before ne "") {
3124 if (WARN
("BAD_SIGN_OFF",
3125 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3127 $fixed[$fixlinenr] =
3128 "$ucfirst_sign_off $email";
3131 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3132 if (WARN
("BAD_SIGN_OFF",
3133 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3135 $fixed[$fixlinenr] =
3136 "$ucfirst_sign_off $email";
3140 if (!defined $space_after || $space_after ne " ") {
3141 if (WARN
("BAD_SIGN_OFF",
3142 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3144 $fixed[$fixlinenr] =
3145 "$ucfirst_sign_off $email";
3149 my ($email_name, $name_comment, $email_address, $comment) = parse_email
($email);
3150 my $suggested_email = format_email
(($email_name, $name_comment, $email_address, $comment));
3151 if ($suggested_email eq "") {
3152 ERROR
("BAD_SIGN_OFF",
3153 "Unrecognized email address: '$email'\n" . $herecurr);
3155 my $dequoted = $suggested_email;
3156 $dequoted =~ s/^"//;
3157 $dequoted =~ s/" </ </;
3158 # Don't force email to have quotes
3159 # Allow just an angle bracketed address
3160 if (!same_email_addresses
($email, $suggested_email)) {
3161 if (WARN
("BAD_SIGN_OFF",
3162 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3164 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3168 # Address part shouldn't have comments
3169 my $stripped_address = $email_address;
3170 $stripped_address =~ s/\([^\(\)]*\)//g;
3171 if ($email_address ne $stripped_address) {
3172 if (WARN
("BAD_SIGN_OFF",
3173 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3175 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3179 # Only one name comment should be allowed
3180 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3181 if ($comment_count > 1) {
3182 WARN
("BAD_SIGN_OFF",
3183 "Use a single name comment in email: '$email'\n" . $herecurr);
3187 # stable@vger.kernel.org or stable@kernel.org shouldn't
3188 # have an email name. In addition comments should strictly
3190 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3191 if (($comment ne "" && $comment !~ /^#.+/) ||
3192 ($email_name ne "")) {
3193 my $cur_name = $email_name;
3194 my $new_comment = $comment;
3195 $cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3197 # Remove brackets enclosing comment text
3198 # and # from start of comments to get comment text
3199 $new_comment =~ s/^\((.*)\)$/$1/;
3200 $new_comment =~ s/^\[(.*)\]$/$1/;
3201 $new_comment =~ s/^[\s\#]+|\s+$//g;
3203 $new_comment = trim
("$new_comment $cur_name") if ($cur_name ne $new_comment);
3204 $new_comment = " # $new_comment" if ($new_comment ne "");
3205 my $new_email = "$email_address$new_comment";
3207 if (WARN
("BAD_STABLE_ADDRESS_STYLE",
3208 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3210 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3213 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3214 my $new_comment = $comment;
3216 # Extract comment text from within brackets or
3217 # c89 style /*...*/ comments
3218 $new_comment =~ s/^\[(.*)\]$/$1/;
3219 $new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3221 $new_comment = trim
($new_comment);
3222 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3223 $new_comment = "($new_comment)" if ($new_comment ne "");
3224 my $new_email = format_email
($email_name, $name_comment, $email_address, $new_comment);
3226 if (WARN
("BAD_SIGN_OFF",
3227 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3229 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3234 # Check for duplicate signatures
3235 my $sig_nospace = $line;
3236 $sig_nospace =~ s/\s//g;
3237 $sig_nospace = lc($sig_nospace);
3238 if (defined $signatures{$sig_nospace}) {
3239 WARN
("BAD_SIGN_OFF",
3240 "Duplicate signature\n" . $herecurr);
3242 $signatures{$sig_nospace} = 1;
3245 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3246 if ($sign_off =~ /^co-developed-by:$/i) {
3247 if ($email eq $author) {
3248 WARN
("BAD_SIGN_OFF",
3249 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
3251 if (!defined $lines[$linenr]) {
3252 WARN
("BAD_SIGN_OFF",
3253 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
3254 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
3255 WARN
("BAD_SIGN_OFF",
3256 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3257 } elsif ($1 ne $email) {
3258 WARN
("BAD_SIGN_OFF",
3259 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
3264 # Check email subject for common tools that don't need to be mentioned
3265 if ($in_header_lines &&
3266 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3267 WARN
("EMAIL_SUBJECT",
3268 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3271 # Check for Gerrit Change-Ids not in any patch context
3272 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3273 if (ERROR
("GERRIT_CHANGE_ID",
3274 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3276 fix_delete_line
($fixlinenr, $rawline);
3280 # Check if the commit log is in a possible stack dump
3281 if ($in_commit_log && !$commit_log_possible_stack_dump &&
3282 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3283 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3285 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3286 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3287 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3288 # stack dump address styles
3289 $commit_log_possible_stack_dump = 1;
3292 # Check for line lengths > 75 in commit log, warn once
3293 if ($in_commit_log && !$commit_log_long_line &&
3294 length($line) > 75 &&
3295 !($line =~ /^\s*[a-zA-Z0-9_\/\
.]+\s
+\
|\s
+\d
+/ ||
3296 # file delta changes
3297 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\
.\
-]+:/ ||
3299 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i ||
3300 # A Fixes: or Link: line or signature tag line
3301 $commit_log_possible_stack_dump)) {
3302 WARN
("COMMIT_LOG_LONG_LINE",
3303 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
3304 $commit_log_long_line = 1;
3307 # Reset possible stack dump if a blank line is found
3308 if ($in_commit_log && $commit_log_possible_stack_dump &&
3310 $commit_log_possible_stack_dump = 0;
3313 # Check for lines starting with a #
3314 if ($in_commit_log && $line =~ /^#/) {
3315 if (WARN
("COMMIT_COMMENT_SYMBOL",
3316 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3318 $fixed[$fixlinenr] =~ s/^/ /;
3322 # Check for git id commit length and improperly formed commit descriptions
3323 # A correctly formed commit description is:
3324 # commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3325 # with the commit subject '("' prefix and '")' suffix
3326 # This is a fairly compilicated block as it tests for what appears to be
3327 # bare SHA-1 hash with minimum length of 5. It also avoids several types of
3328 # possible SHA-1 matches.
3329 # A commit match can span multiple lines so this block attempts to find a
3330 # complete typical commit on a maximum of 3 lines
3331 if ($perl_version_ok &&
3332 $in_commit_log && !$commit_log_possible_stack_dump &&
3333 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3334 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3335 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3336 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3337 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3338 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3339 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3340 my $init_char = "c";
3341 my $orig_commit = "";
3346 my $id = '0123456789ab';
3347 my $orig_desc = "commit description";
3348 my $description = "";
3349 my $herectx = $herecurr;
3354 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3355 for (my $n = 0; $n < 2; $n++) {
3356 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3359 # Always strip leading/trailing parens then double quotes if existing
3360 $orig_desc = substr($orig_desc, 1, -1);
3361 if ($orig_desc =~ /^".*"$/) {
3362 $orig_desc = substr($orig_desc, 1, -1);
3367 last if ($#lines < $linenr + $n);
3368 $input .= " " . trim
($rawlines[$linenr + $n]);
3369 $herectx .= "$rawlines[$linenr + $n]\n";
3371 $herectx = $herecurr if (!$has_parens);
3374 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3376 $orig_commit = lc($2);
3377 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3378 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3379 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3380 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3381 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3382 $orig_commit = lc($1);
3385 ($id, $description) = git_commit_info
($orig_commit,
3389 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3390 $last_git_commit_id_linenr != $linenr - 1) {
3391 ERROR
("GIT_COMMIT_ID",
3392 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3394 #don't report the next line if this line ends in commit and the sha1 hash is the next line
3395 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3398 # Check for added, moved or deleted files
3399 if (!$reported_maintainer_file && !$in_commit_log &&
3400 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3401 $line =~ /^rename (?:from|to) [\w\/\
.\
-]+\s
*$/ ||
3402 ($line =~ /\{\s*([\w\/\
.\
-]*)\s
*\
=\
>\s
*([\w\
/\.\-]*)\s*\}/ &&
3403 (defined($1) || defined($2))))) {
3405 $reported_maintainer_file = 1;
3406 WARN
("FILE_PATH_CHANGES",
3407 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3410 # Check for adding new DT bindings not in schema format
3411 if (!$in_commit_log &&
3412 ($line =~ /^new file mode\s*\d+\s*$/) &&
3413 ($realfile =~ m@
^Documentation
/devicetree/bindings
/.*\
.txt
$@
)) {
3414 WARN
("DT_SCHEMA_BINDING_PATCH",
3415 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3418 # Check for wrappage within a valid hunk of the file
3419 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3420 ERROR
("CORRUPTED_PATCH",
3421 "patch seems to be corrupt (line wrapped?)\n" .
3422 $herecurr) if (!$emitted_corrupt++);
3425 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3426 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3427 $rawline !~ m/^$UTF8*$/) {
3428 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3430 my $blank = copy_spacing
($rawline);
3431 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3432 my $hereptr = "$hereline$ptr\n";
3435 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3438 # Check if it's the start of a commit log
3439 # (not a header line and we haven't seen the patch filename)
3440 if ($in_header_lines && $realfile =~ /^$/ &&
3441 !($rawline =~ /^\s+(?:\S|$)/ ||
3442 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3443 $in_header_lines = 0;
3445 $has_commit_log = 1;
3448 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3449 # declined it, i.e defined some charset where it is missing.
3450 if ($in_header_lines &&
3451 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3453 $non_utf8_charset = 1;
3456 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3457 $rawline =~ /$NON_ASCII_UTF8/) {
3458 WARN
("UTF8_BEFORE_PATCH",
3459 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3462 # Check for absolute kernel paths in commit message
3463 if ($tree && $in_commit_log) {
3464 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3467 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3468 check_absolute_file
($1, $herecurr)) {
3471 check_absolute_file
($file, $herecurr);
3476 # Check for various typo / spelling mistakes
3477 if (defined($misspellings) &&
3478 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3479 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3481 my $blank = copy_spacing
($rawline);
3482 my $ptr = substr($blank, 0, $-[1]) . "^" x
length($typo);
3483 my $hereptr = "$hereline$ptr\n";
3484 my $typo_fix = $spelling_fix{lc($typo)};
3485 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3486 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3487 my $msg_level = \
&WARN
;
3488 $msg_level = \
&CHK
if ($file);
3489 if (&{$msg_level}("TYPO_SPELLING",
3490 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3492 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3497 # check for invalid commit id
3498 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3501 ($id, $description) = git_commit_info
($2, undef, undef);
3502 if (!defined($id)) {
3503 WARN
("UNKNOWN_COMMIT_ID",
3504 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3508 # check for repeated words separated by a single space
3509 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3510 if (($rawline =~ /^\+/ || $in_commit_log) &&
3511 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3512 pos($rawline) = 1 if (!$in_commit_log);
3513 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3517 my $start_pos = $-[1];
3518 my $end_pos = $+[2];
3519 if ($first =~ /(?:struct|union|enum)/) {
3520 pos($rawline) += length($first) + length($second) + 1;
3524 next if (lc($first) ne lc($second));
3525 next if ($first eq 'long');
3527 # check for character before and after the word matches
3528 my $start_char = '';
3530 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ?
0 : 1));
3531 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3533 next if ($start_char =~ /^\S$/);
3534 next if (index(" \t.,;?!", $end_char) == -1);
3536 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3537 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3538 next if (!exists($allow_repeated_words{lc($first)}));
3541 if (WARN
("REPEATED_WORD",
3542 "Possible repeated word: '$first'\n" . $herecurr) &&
3544 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3548 # if it's a repeated word on consecutive lines in a comment block
3549 if ($prevline =~ /$;+\s*$/ &&
3550 $prevrawline =~ /($word_pattern)\s*$/) {
3552 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3553 if (WARN
("REPEATED_WORD",
3554 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3556 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3562 # ignore non-hunk lines and lines being removed
3563 next if (!$hunk_line || $line =~ /^-/);
3565 #trailing whitespace
3566 if ($line =~ /^\+.*\015/) {
3567 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
3568 if (ERROR
("DOS_LINE_ENDINGS",
3569 "DOS line endings\n" . $herevet) &&
3571 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3573 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3574 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
3575 if (ERROR
("TRAILING_WHITESPACE",
3576 "trailing whitespace\n" . $herevet) &&
3578 $fixed[$fixlinenr] =~ s/\s+$//;
3584 # Check for FSF mailing addresses.
3585 if ($rawline =~ /\bwrite to the Free/i ||
3586 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3587 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3588 $rawline =~ /\b51\s+Franklin\s+St/i) {
3589 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
3590 my $msg_level = \
&ERROR
;
3591 $msg_level = \
&CHK
if ($file);
3592 &{$msg_level}("FSF_MAILING_ADDRESS",
3593 "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
3596 # check for Kconfig help text having a real description
3597 # Only applies when adding the entry originally, after that we do not have
3598 # sufficient context to determine whether it is indeed long enough.
3599 if ($realfile =~ /Kconfig/ &&
3600 # 'choice' is usually the last thing on the line (though
3601 # Kconfig supports named choices), so use a word boundary
3602 # (\b) rather than a whitespace character (\s)
3603 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3606 my $ln = $linenr + 1;
3610 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3611 $f = $lines[$ln - 1];
3612 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3613 $is_end = $lines[$ln - 1] =~ /^\+/;
3615 next if ($f =~ /^-/);
3616 last if (!$file && $f =~ /^\@\@/);
3618 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3620 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3627 next if ($f =~ /^$/);
3629 # This only checks context lines in the patch
3630 # and so hopefully shouldn't trigger false
3631 # positives, even though some of these are
3632 # common words in help texts
3633 if ($f =~ /^\s
*(?
:config
|menuconfig
|choice
|endchoice
|
3634 if|endif
|menu
|endmenu
|source
)\b/x
) {
3640 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3641 WARN
("CONFIG_DESCRIPTION",
3642 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3644 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3647 # check MAINTAINERS entries
3648 if ($realfile =~ /^MAINTAINERS$/) {
3649 # check MAINTAINERS entries for the right form
3650 if ($rawline =~ /^\+[A-Z]:/ &&
3651 $rawline !~ /^\+[A-Z]:\t\S/) {
3652 if (WARN
("MAINTAINERS_STYLE",
3653 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3655 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3658 # check MAINTAINERS entries for the right ordering too
3659 my $preferred_order = 'MRLSWQBCPTFXNK';
3660 if ($rawline =~ /^\+[A-Z]:/ &&
3661 $prevrawline =~ /^[\+ ][A-Z]:/) {
3662 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3665 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3668 my $curindex = index($preferred_order, $cur);
3669 my $previndex = index($preferred_order, $prev);
3670 if ($curindex < 0) {
3671 WARN
("MAINTAINERS_STYLE",
3672 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3674 if ($previndex >= 0 && $curindex < $previndex) {
3675 WARN
("MAINTAINERS_STYLE",
3676 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3677 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3678 ($prev eq 'X' && $cur eq 'X')) &&
3679 ($prevval cmp $curval) > 0) {
3680 WARN
("MAINTAINERS_STYLE",
3681 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3687 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3688 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3691 'EXTRA_AFLAGS' => 'asflags-y',
3692 'EXTRA_CFLAGS' => 'ccflags-y',
3693 'EXTRA_CPPFLAGS' => 'cppflags-y',
3694 'EXTRA_LDFLAGS' => 'ldflags-y',
3697 WARN
("DEPRECATED_VARIABLE",
3698 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3701 # check for DT compatible documentation
3702 if (defined $root &&
3703 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3704 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3706 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3708 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3709 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3711 foreach my $compat (@compats) {
3712 my $compat2 = $compat;
3713 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3714 my $compat3 = $compat;
3715 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3716 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3718 WARN
("UNDOCUMENTED_DT_STRING",
3719 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3722 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3724 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3726 WARN
("UNDOCUMENTED_DT_STRING",
3727 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3732 # check for using SPDX license tag at beginning of files
3733 if ($realline == $checklicenseline) {
3734 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3735 $checklicenseline = 2;
3736 } elsif ($rawline =~ /^\+/) {
3738 if ($realfile =~ /\.(h|s|S)$/) {
3740 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3742 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3744 } elsif ($realfile =~ /\.rst$/) {
3748 # check SPDX comment style for .[chsS] files
3749 if ($realfile =~ /\.[chsS]$/ &&
3750 $rawline =~ /SPDX-License-Identifier:/ &&
3751 $rawline !~ m@
^\
+\s
*\Q
$comment\E\s
*@
) {
3752 WARN
("SPDX_LICENSE_TAG",
3753 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3756 if ($comment !~ /^$/ &&
3757 $rawline !~ m@
^\
+\Q
$comment\E SPDX
-License
-Identifier
: @
) {
3758 WARN
("SPDX_LICENSE_TAG",
3759 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3760 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3761 my $spdx_license = $1;
3762 if (!is_SPDX_License_valid
($spdx_license)) {
3763 WARN
("SPDX_LICENSE_TAG",
3764 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3766 if ($realfile =~ m@
^Documentation
/devicetree/bindings
/@
&&
3767 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3768 my $msg_level = \
&WARN
;
3769 $msg_level = \
&CHK
if ($file);
3770 if (&{$msg_level}("SPDX_LICENSE_TAG",
3772 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3774 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3781 # check for embedded filenames
3782 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3783 WARN
("EMBEDDED_FILENAME",
3784 "It's generally not useful to have the filename in the file\n" . $herecurr);
3787 # check we are in a valid source file if not then ignore this hunk
3788 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3790 # check for using SPDX-License-Identifier on the wrong line number
3791 if ($realline != $checklicenseline &&
3792 $rawline =~ /\bSPDX-License-Identifier:/ &&
3793 substr($line, @
-, @
+ - @
-) eq "$;" x
(@
+ - @
-)) {
3794 WARN
("SPDX_LICENSE_TAG",
3795 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3798 # line length limit (with some exclusions)
3800 # There are a few types of lines that may extend beyond $max_line_length:
3801 # logging functions like pr_info that end in a string
3802 # lines with a single string
3803 # #defines that are a single string
3804 # lines with an RFC3986 like URL
3806 # There are 3 different line length message types:
3807 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3808 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3809 # LONG_LINE all other lines longer than $max_line_length
3811 # if LONG_LINE is ignored, the other 2 types are also ignored
3814 if ($line =~ /^\+/ && $length > $max_line_length) {
3815 my $msg_type = "LONG_LINE";
3817 # Check the allowed long line types first
3819 # logging functions that end in a string that starts
3820 # before $max_line_length
3821 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3822 length(expand_tabs
(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3825 # lines with only strings (w/ possible termination)
3826 # #defines with only strings
3827 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3828 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3831 # More special cases
3832 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3833 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3836 # URL ($rawline is used in case the URL is in a comment)
3837 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\
/\S+/i) {
3840 # Otherwise set the alternate message types
3842 # a comment starts before $max_line_length
3843 } elsif ($line =~ /($;[\s$;]*)$/ &&
3844 length(expand_tabs
(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3845 $msg_type = "LONG_LINE_COMMENT"
3847 # a quoted string starts before $max_line_length
3848 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3849 length(expand_tabs
(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3850 $msg_type = "LONG_LINE_STRING"
3853 if ($msg_type ne "" &&
3854 (show_type
("LONG_LINE") || show_type
($msg_type))) {
3855 my $msg_level = \
&WARN
;
3856 $msg_level = \
&CHK
if ($file);
3857 &{$msg_level}($msg_type,
3858 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3862 # check for adding lines without a newline.
3863 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3864 if (WARN
("MISSING_EOF_NEWLINE",
3865 "adding a line without newline at end of file\n" . $herecurr) &&
3867 fix_delete_line
($fixlinenr+1, "No newline at end of file");
3871 # check for .L prefix local symbols in .S files
3872 if ($realfile =~ /\.S$/ &&
3873 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3874 WARN
("AVOID_L_PREFIX",
3875 "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);
3879 u_boot_line
($realfile, $line, $rawline, $herecurr);
3882 # check we are in a valid source file C or perl if not then ignore this hunk
3883 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3885 # at the beginning of a line any tabs must come first and anything
3886 # more than $tabsize must use tabs.
3887 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3888 $rawline =~ /^\+\s* \s*/) {
3889 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
3891 if (ERROR
("CODE_INDENT",
3892 "code indent should use tabs where possible\n" . $herevet) &&
3894 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3898 # check for space before tabs.
3899 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3900 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
3901 if (WARN
("SPACE_BEFORE_TAB",
3902 "please, no space before tabs\n" . $herevet) &&
3904 while ($fixed[$fixlinenr] =~
3905 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3906 while ($fixed[$fixlinenr] =~
3907 s/(^\+.*) +\t/$1\t/) {}
3911 # check for assignments on the start of a line
3912 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3914 if (CHK
("ASSIGNMENT_CONTINUATIONS",
3915 "Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3916 $fix && $prevrawline =~ /^\+/) {
3917 # add assignment operator to the previous line, remove from current line
3918 $fixed[$fixlinenr - 1] .= " $operator";
3919 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3923 # check for && or || at the start of a line
3924 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3926 if (CHK
("LOGICAL_CONTINUATIONS",
3927 "Logical continuations should be on the previous line\n" . $hereprev) &&
3928 $fix && $prevrawline =~ /^\+/) {
3929 # insert logical operator at last non-comment, non-whitepsace char on previous line
3930 $prevline =~ /[\s$;]*$/;
3931 my $line_end = substr($prevrawline, $-[0]);
3932 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3933 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3937 # check indentation starts on a tab stop
3938 if ($perl_version_ok &&
3939 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3940 my $indent = length($1);
3941 if ($indent % $tabsize) {
3943 "Statements should start on a tabstop\n" . $herecurr) &&
3945 $fixed[$fixlinenr] =~ s@
(^\
+\t+) +@
$1 . "\t" x
($indent/$tabsize)@e;
3950 # check multi-line statement indentation matches previous line
3951 if ($perl_version_ok &&
3952 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3953 $prevline =~ /^\+(\t*)(.*)$/;
3957 my $pos = pos_last_openparen
($rest);
3959 $line =~ /^(\+| )([ \t]*)/;
3962 my $goodtabindent = $oldindent .
3963 "\t" x
($pos / $tabsize) .
3964 " " x
($pos % $tabsize);
3965 my $goodspaceindent = $oldindent . " " x
$pos;
3967 if ($newindent ne $goodtabindent &&
3968 $newindent ne $goodspaceindent) {
3970 if (CHK
("PARENTHESIS_ALIGNMENT",
3971 "Alignment should match open parenthesis\n" . $hereprev) &&
3972 $fix && $line =~ /^\+/) {
3973 $fixed[$fixlinenr] =~
3974 s/^\+[ \t]*/\+$goodtabindent/;
3980 # check for space after cast like "(int) foo" or "(struct foo) bar"
3981 # avoid checking a few false positives:
3982 # "sizeof(<type>)" or "__alignof__(<type>)"
3983 # function pointer declarations like "(*foo)(int) = bar;"
3984 # structure definitions like "(struct foo) { 0 };"
3985 # multiline macros that define functions
3986 # known attributes or the __attribute__ keyword
3987 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3988 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3990 "No space is necessary after a cast\n" . $herecurr) &&
3992 $fixed[$fixlinenr] =~
3993 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3997 # Block comment styles
3998 # Networking with an initial /*
3999 if ($realfile =~ m@
^(drivers
/net
/|net
/)@
&&
4000 $prevrawline =~ /^\+[ \t]*\/\
*[ \t]*$/ &&
4001 $rawline =~ /^\+[ \t]*\*/ &&
4002 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
4003 WARN
("NETWORKING_BLOCK_COMMENT_STYLE",
4004 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
4007 # Block comments use * on subsequent lines
4008 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4009 $prevrawline =~ /^\+.*?\/\
*/ && #starting /*
4010 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
4011 $rawline =~ /^\+/ && #line is new
4012 $rawline !~ /^\+[ \t]*\*/) { #no leading *
4013 WARN
("BLOCK_COMMENT_STYLE",
4014 "Block comments use * on subsequent lines\n" . $hereprev);
4017 # Block comments use */ on trailing lines
4018 if ($rawline !~ m@
^\
+[ \t]*\
*/[ \t]*$@ && #trailing */
4019 $rawline !~ m@
^\
+.*/\*.*\*/[ \t]*$@
&& #inline /*...*/
4020 $rawline !~ m@
^\
+.*\
*{2,}/[ \t]*$@ && #trailing **/
4021 $rawline =~ m@
^\
+[ \t]*.+\
*\
/[ \t]*$@) { #non blank */
4022 WARN
("BLOCK_COMMENT_STYLE",
4023 "Block comments use a trailing */ on a separate line\n" . $herecurr);
4026 # Block comment * alignment
4027 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
4028 $line =~ /^\+[ \t]*$;/ && #leading comment
4029 $rawline =~ /^\+[ \t]*\*/ && #leading *
4030 (($prevrawline =~ /^\+.*?\/\
*/ && #leading /*
4031 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
4032 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
4034 $prevrawline =~ m@
^\
+([ \t]*/?
)\
*@
;
4036 $oldindent = expand_tabs
($1);
4038 $prevrawline =~ m@
^\
+(.*/?
)\
*@
;
4039 $oldindent = expand_tabs
($1);
4041 $rawline =~ m@
^\
+([ \t]*)\
*@
;
4043 $newindent = expand_tabs
($newindent);
4044 if (length($oldindent) ne length($newindent)) {
4045 WARN
("BLOCK_COMMENT_STYLE",
4046 "Block comments should align the * on each line\n" . $hereprev);
4050 # check for missing blank lines after struct/union declarations
4051 # with exceptions for various attributes and macros
4052 if ($prevline =~ /^[\+ ]};?\s*$/ &&
4054 !($line =~ /^\+\s*$/ ||
4055 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
4056 $line =~ /^\+\s*MODULE_/i ||
4057 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4058 $line =~ /^\+[a-z_]*init/ ||
4059 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4060 $line =~ /^\+\s*DECLARE/ ||
4061 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4062 $line =~ /^\+\s*__setup/)) {
4063 if (CHK
("LINE_SPACING",
4064 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4066 fix_insert_line
($fixlinenr, "\+");
4070 # check for multiple consecutive blank lines
4071 if ($prevline =~ /^[\+ ]\s*$/ &&
4072 $line =~ /^\+\s*$/ &&
4073 $last_blank_line != ($linenr - 1)) {
4074 if (CHK
("LINE_SPACING",
4075 "Please don't use multiple blank lines\n" . $hereprev) &&
4077 fix_delete_line
($fixlinenr, $rawline);
4080 $last_blank_line = $linenr;
4083 # check for missing blank lines after declarations
4084 # (declarations must have the same indentation and not be at the start of line)
4085 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4089 # remove $Attribute/$Sparse uses to simplify comparisons
4090 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4091 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4092 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4093 # function pointer declarations
4094 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4095 # foo bar; where foo is some local typedef or #define
4096 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4097 # known declaration macros
4098 $pl =~ /^\+\s+$declaration_macros/) &&
4099 # for "else if" which can look like "$Ident $Ident"
4100 !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4101 # other possible extensions of declaration lines
4102 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4103 # not starting a section or a macro "\" extended line
4104 $pl =~ /(?:\{\s*|\\)$/) &&
4105 # looks like a declaration
4106 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4107 # function pointer declarations
4108 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4109 # foo bar; where foo is some local typedef or #define
4110 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4111 # known declaration macros
4112 $sl =~ /^\+\s+$declaration_macros/ ||
4113 # start of struct or union or enum
4114 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4115 # start or end of block or continuation of declaration
4116 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4117 # bitfield continuation
4118 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4119 # other possible extensions of declaration lines
4120 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4121 if (WARN
("LINE_SPACING",
4122 "Missing a blank line after declarations\n" . $hereprev) &&
4124 fix_insert_line
($fixlinenr, "\+");
4129 # check for spaces at the beginning of a line.
4131 # 1) within comments
4132 # 2) indented preprocessor commands
4134 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
4135 my $herevet = "$here\n" . cat_vet
($rawline) . "\n";
4136 if (WARN
("LEADING_SPACE",
4137 "please, no spaces at the start of a line\n" . $herevet) &&
4139 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4143 # check we are in a valid C source file if not then ignore this hunk
4144 next if ($realfile !~ /\.(h|c)$/);
4146 # check for unusual line ending [ or (
4147 if ($line =~ /^\+.*([\[\(])\s*$/) {
4148 CHK
("OPEN_ENDED_LINE",
4149 "Lines should not end with a '$1'\n" . $herecurr);
4152 # check if this appears to be the start function declaration, save the name
4153 if ($sline =~ /^\+\{\s*$/ &&
4154 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4155 $context_function = $1;
4158 # check if this appears to be the end of function declaration
4159 if ($sline =~ /^\+\}\s*$/) {
4160 undef $context_function;
4163 # check indentation of any line with a bare else
4164 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
4165 # if the previous line is a break or return and is indented 1 tab more...
4166 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4167 my $tabs = length($1) + 1;
4168 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4169 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4170 defined $lines[$linenr] &&
4171 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4172 WARN
("UNNECESSARY_ELSE",
4173 "else is not generally useful after a break or return\n" . $hereprev);
4177 # check indentation of a line with a break;
4178 # if the previous line is a goto, return or break
4179 # and is indented the same # of tabs
4180 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4182 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4183 if (WARN
("UNNECESSARY_BREAK",
4184 "break is not useful after a $1\n" . $hereprev) &&
4186 fix_delete_line
($fixlinenr, $rawline);
4191 # check for RCS/CVS revision markers
4192 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4194 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4197 # check for old HOTPLUG __dev<foo> section markings
4198 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4199 WARN
("HOTPLUG_SECTION",
4200 "Using $1 is unnecessary\n" . $herecurr);
4203 # Check for potential 'bare' types
4204 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4206 #print "LINE<$line>\n";
4207 if ($linenr > $suppress_statement &&
4208 $realcnt && $sline =~ /.\s*\S/) {
4209 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4210 ctx_statement_block
($linenr, $realcnt, 0);
4211 $stat =~ s/\n./\n /g;
4212 $cond =~ s/\n./\n /g;
4214 #print "linenr<$linenr> <$stat>\n";
4215 # If this statement has no statement boundaries within
4216 # it there is no point in retrying a statement scan
4217 # until we hit end of it.
4218 my $frag = $stat; $frag =~ s/;+\s*$//;
4219 if ($frag !~ /(?:{|;)/) {
4220 #print "skip<$line_nr_next>\n";
4221 $suppress_statement = $line_nr_next;
4224 # Find the real next line.
4225 $realline_next = $line_nr_next;
4226 if (defined $realline_next &&
4227 (!defined $lines[$realline_next - 1] ||
4228 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4235 # Ignore goto labels.
4236 if ($s =~ /$Ident:\*$/s) {
4238 # Ignore functions being called
4239 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4241 } elsif ($s =~ /^.\s*else\b/s) {
4243 # declarations always start with types
4244 } 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) {
4247 possible
($type, "A:" . $s);
4249 # definitions in global scope can only start with types
4250 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4251 possible
($1, "B:" . $s);
4254 # any (foo ... *) is a pointer cast, and foo is a type
4255 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4256 possible
($1, "C:" . $s);
4259 # Check for any sort of function declaration.
4260 # int foo(something bar, other baz);
4261 # void (*store_gdt)(x86_descr_ptr *);
4262 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4263 my ($name_len) = length($1);
4266 substr($ctx, 0, $name_len + 1, '');
4267 $ctx =~ s/\)[^\)]*$//;
4269 for my $arg (split(/\s*,\s*/, $ctx)) {
4270 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4272 possible
($1, "D:" . $s);
4280 # Checks which may be anchored in the context.
4283 # Check for switch () and associated case and default
4284 # statements should be at the same indent.
4285 if ($line=~/\bswitch\s*\(.*\)/) {
4288 my @ctx = ctx_block_outer
($linenr, $realcnt);
4290 for my $ctx (@ctx) {
4291 my ($clen, $cindent) = line_stats
($ctx);
4292 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4293 $indent != $cindent) {
4294 $err .= "$sep$ctx\n";
4301 ERROR
("SWITCH_CASE_INDENT_LEVEL",
4302 "switch and case should be at the same indent\n$hereline$err");
4306 # if/while/etc brace do not go on next line, unless defining a do while loop,
4307 # or if that brace on the next line is for something else
4308 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4309 my $pre_ctx = "$1$2";
4311 my ($level, @ctx) = ctx_statement_level
($linenr, $realcnt, 0);
4313 if ($line =~ /^\+\t{6,}/) {
4314 WARN
("DEEP_INDENTATION",
4315 "Too many leading tabs - consider code refactoring\n" . $herecurr);
4318 my $ctx_cnt = $realcnt - $#ctx - 1;
4319 my $ctx = join("\n", @ctx);
4321 my $ctx_ln = $linenr;
4322 my $ctx_skip = $realcnt;
4324 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4325 defined $lines[$ctx_ln - 1] &&
4326 $lines[$ctx_ln - 1] =~ /^-/)) {
4327 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4328 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4332 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4333 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4335 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4337 "that open brace { should be on the previous line\n" .
4338 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4340 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4341 $ctx =~ /\)\s*\;\s*$/ &&
4342 defined $lines[$ctx_ln - 1])
4344 my ($nlength, $nindent) = line_stats
($lines[$ctx_ln - 1]);
4345 if ($nindent > $indent) {
4346 WARN
("TRAILING_SEMICOLON",
4347 "trailing semicolon indicates no statements, indent implies otherwise\n" .
4348 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4353 # Check relative indent for conditionals and blocks.
4354 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4355 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4356 ctx_statement_block
($linenr, $realcnt, 0)
4357 if (!defined $stat);
4358 my ($s, $c) = ($stat, $cond);
4360 substr($s, 0, length($c), '');
4362 # remove inline comments
4366 # Find out how long the conditional actually is.
4367 my @newlines = ($c =~ /\n/gs);
4368 my $cond_lines = 1 + $#newlines;
4370 # Make sure we remove the line prefixes as we have
4371 # none on the first line, and are going to readd them
4374 while ($s =~ /\n\s+\\\n/) {
4375 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4378 # We want to check the first line inside the block
4379 # starting at the end of the conditional, so remove:
4380 # 1) any blank line termination
4381 # 2) any opening brace { on end of the line
4383 my $continuation = 0;
4385 $s =~ s/^.*\bdo\b//;
4387 if ($s =~ s/^\s*\\//) {
4390 if ($s =~ s/^\s*?\n//) {
4395 # Also ignore a loop construct at the end of a
4396 # preprocessor statement.
4397 if (($prevline =~ /^.\s*#\s*define\s/ ||
4398 $prevline =~ /\\\s*$/) && $continuation == 0) {
4404 while ($cond_ptr != $cond_lines) {
4405 $cond_ptr = $cond_lines;
4407 # If we see an #else/#elif then the code
4409 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4414 # 1) blank lines, they should be at 0,
4415 # 2) preprocessor lines, and
4417 if ($continuation ||
4419 $s =~ /^\s*#\s*?/ ||
4420 $s =~ /^\s*$Ident\s*:/) {
4421 $continuation = ($s =~ /^.*?\\\n/) ?
1 : 0;
4422 if ($s =~ s/^.*?\n//) {
4428 my (undef, $sindent) = line_stats
("+" . $s);
4429 my $stat_real = raw_line
($linenr, $cond_lines);
4431 # Check if either of these lines are modified, else
4432 # this is not this patch's fault.
4433 if (!defined($stat_real) ||
4434 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4437 if (defined($stat_real) && $cond_lines > 1) {
4438 $stat_real = "[...]\n$stat_real";
4441 #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";
4443 if ($check && $s ne '' &&
4444 (($sindent % $tabsize) != 0 ||
4445 ($sindent < $indent) ||
4446 ($sindent == $indent &&
4447 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4448 ($sindent > $indent + $tabsize))) {
4449 WARN
("SUSPECT_CODE_INDENT",
4450 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4454 # Track the 'values' across context and added lines.
4455 my $opline = $line; $opline =~ s/^./ /;
4456 my ($curr_values, $curr_vars) =
4457 annotate_values
($opline . "\n", $prev_values);
4458 $curr_values = $prev_values . $curr_values;
4460 my $outline = $opline; $outline =~ s/\t/ /g;
4461 print "$linenr > .$outline\n";
4462 print "$linenr > $curr_values\n";
4463 print "$linenr > $curr_vars\n";
4465 $prev_values = substr($curr_values, -1);
4467 #ignore lines not being added
4468 next if ($line =~ /^[^\+]/);
4470 # check for self assignments used to avoid compiler warnings
4471 # e.g.: int foo = foo, *bar = NULL;
4472 # struct foo bar = *(&(bar));
4473 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4475 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4476 WARN
("SELF_ASSIGNMENT",
4477 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4481 # check for dereferences that span multiple lines
4482 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4483 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4484 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4486 $line =~ /^.\s*($Lval)/;
4489 WARN
("MULTILINE_DEREFERENCE",
4490 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4493 # check for declarations of signed or unsigned without int
4494 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4497 $var = "" if (!defined $var);
4498 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4502 $pointer = "" if (!defined $pointer);
4504 if (WARN
("UNSPECIFIED_INT",
4505 "Prefer '" . trim
($sign) . " int" . rtrim
($pointer) . "' to bare use of '$sign" . rtrim
($pointer) . "'\n" . $herecurr) &&
4507 my $decl = trim
($sign) . " int ";
4508 my $comp_pointer = $pointer;
4509 $comp_pointer =~ s/\s//g;
4510 $decl .= $comp_pointer;
4511 $decl = rtrim
($decl) if ($var eq "");
4512 $fixed[$fixlinenr] =~ s@
\b$sign\s
*\Q
$pointer\E\s
*$var\b@
$decl$var@
;
4517 # TEST: allow direct testing of the type matcher.
4519 if ($line =~ /^.\s*$Declare\s*$/) {
4521 "TEST: is type\n" . $herecurr);
4522 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4523 ERROR
("TEST_NOT_TYPE",
4524 "TEST: is not type ($1 is)\n". $herecurr);
4528 # TEST: allow direct testing of the attribute matcher.
4530 if ($line =~ /^.\s*$Modifier\s*$/) {
4532 "TEST: is attr\n" . $herecurr);
4533 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4534 ERROR
("TEST_NOT_ATTR",
4535 "TEST: is not attr ($1 is)\n". $herecurr);
4540 # check for initialisation to aggregates open brace on the next line
4541 if ($line =~ /^.\s*{/ &&
4542 $prevline =~ /(?:^|[^=])=\s*$/) {
4543 if (ERROR
("OPEN_BRACE",
4544 "that open brace { should be on the previous line\n" . $hereprev) &&
4545 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4546 fix_delete_line
($fixlinenr - 1, $prevrawline);
4547 fix_delete_line
($fixlinenr, $rawline);
4548 my $fixedline = $prevrawline;
4549 $fixedline =~ s/\s*=\s*$/ = {/;
4550 fix_insert_line
($fixlinenr, $fixedline);
4552 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4553 fix_insert_line
($fixlinenr, $fixedline);
4558 # Checks which are anchored on the added line.
4561 # check for malformed paths in #include statements (uses RAW line)
4562 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4564 if ($path =~ m{//}) {
4565 ERROR
("MALFORMED_INCLUDE",
4566 "malformed #include filename\n" . $herecurr);
4568 if ($path =~ "^uapi/" && $realfile =~ m@
\binclude
/uapi
/@
) {
4569 ERROR
("UAPI_INCLUDE",
4570 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4574 # no C99 // comments
4575 if ($line =~ m{//}) {
4576 if (ERROR
("C99_COMMENTS",
4577 "do not use C99 // comments\n" . $herecurr) &&
4579 my $line = $fixed[$fixlinenr];
4580 if ($line =~ /\/\
/(.*)$/) {
4581 my $comment = trim
($1);
4582 $fixed[$fixlinenr] =~ s@\
/\/(.*)$@
/\* $comment \*/@
;
4586 # Remove C99 comments.
4588 $opline =~ s@
//.*@@
;
4590 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4591 # the whole statement.
4592 #print "APW <$lines[$realline_next - 1]>\n";
4593 if (defined $realline_next &&
4594 exists $lines[$realline_next - 1] &&
4595 !defined $suppress_export{$realline_next} &&
4596 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4597 # Handle definitions which produce identifiers with
4600 # EXPORT_SYMBOL(something_foo);
4602 $name =~ s/^\s*($Ident).*/$1/;
4603 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4604 $name =~ /^${Ident}_$2/) {
4605 #print "FOO C name<$name>\n";
4606 $suppress_export{$realline_next} = 1;
4608 } elsif ($stat !~ /(?
:
4610 ^.DEFINE_
$Ident\
(\Q
$name\E\
)|
4611 ^.DECLARE_
$Ident\
(\Q
$name\E\
)|
4612 ^.LIST_HEAD\
(\Q
$name\E\
)|
4613 ^.(?
:$Storage\s
+)?
$Type\s
*\
(\s
*\
*\s
*\Q
$name\E\s
*\
)\s
*\
(|
4614 \b\Q
$name\E
(?
:\s
+$Attribute)*\s
*(?
:;|=|\
[|\
()
4616 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4617 $suppress_export{$realline_next} = 2;
4619 $suppress_export{$realline_next} = 1;
4622 if (!defined $suppress_export{$linenr} &&
4623 $prevline =~ /^.\s*$/ &&
4624 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4625 #print "FOO B <$lines[$linenr - 1]>\n";
4626 $suppress_export{$linenr} = 2;
4628 if (defined $suppress_export{$linenr} &&
4629 $suppress_export{$linenr} == 2) {
4630 WARN
("EXPORT_SYMBOL",
4631 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4634 # check for global initialisers.
4635 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4636 !exclude_global_initialisers
($realfile)) {
4637 if (ERROR
("GLOBAL_INITIALISERS",
4638 "do not initialise globals to $1\n" . $herecurr) &&
4640 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4643 # check for static initialisers.
4644 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4645 if (ERROR
("INITIALISED_STATIC",
4646 "do not initialise statics to $1\n" .
4649 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4653 # check for misordered declarations of char/short/int/long with signed/unsigned
4654 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4656 WARN
("MISORDERED_TYPE",
4657 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4660 # check for unnecessary <signed> int declarations of short/long/long long
4661 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4662 my $type = trim
($1);
4663 next if ($type !~ /\bint\b/);
4664 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4665 my $new_type = $type;
4666 $new_type =~ s/\b\s*int\s*\b/ /;
4667 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4668 $new_type =~ s/^const\s+//;
4669 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4670 $new_type = "const $new_type" if ($type =~ /^const\b/);
4671 $new_type =~ s/\s+/ /g;
4672 $new_type = trim
($new_type);
4673 if (WARN
("UNNECESSARY_INT",
4674 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4676 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4680 # check for static const char * arrays.
4681 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4682 WARN
("STATIC_CONST_CHAR_ARRAY",
4683 "static const char * array should probably be static const char * const\n" .
4687 # check for initialized const char arrays that should be static const
4688 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4689 if (WARN
("STATIC_CONST_CHAR_ARRAY",
4690 "const array should probably be static const\n" . $herecurr) &&
4692 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4696 # check for static char foo[] = "bar" declarations.
4697 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4698 WARN
("STATIC_CONST_CHAR_ARRAY",
4699 "static char array declaration should probably be static const char\n" .
4703 # check for const <foo> const where <foo> is not a pointer or array type
4704 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4706 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4708 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4709 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4711 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4715 # check for const static or static <non ptr type> const declarations
4716 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4717 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4718 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4719 if (WARN
("STATIC_CONST",
4720 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4722 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4723 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4727 # check for non-global char *foo[] = {"bar", ...} declarations.
4728 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4729 WARN
("STATIC_CONST_CHAR_ARRAY",
4730 "char * array declaration might be better as static const\n" .
4734 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4735 if ($line =~ m@
\bsizeof\s
*\
(\s
*($Lval)\s
*\
)@
) {
4737 if ($line =~ m@
\b(sizeof\s
*\
(\s
*\Q
$array\E\s
*\
)\s
*/\s
*sizeof\s
*\
(\s
*\Q
$array\E\s
*\
[\s
*0\s
*\
]\s
*\
))@
) {
4739 if (WARN
("ARRAY_SIZE",
4740 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4742 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4747 # check for function declarations without arguments like "int foo()"
4748 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4749 if (ERROR
("FUNCTION_WITHOUT_ARGS",
4750 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4752 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4756 # check for new typedefs, only function parameters and sparse annotations
4758 if ($line =~ /\btypedef\s/ &&
4759 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4760 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4761 $line !~ /\b$typeTypedefs\b/ &&
4762 $line !~ /\b__bitwise\b/) {
4763 WARN
("NEW_TYPEDEFS",
4764 "do not add new typedefs\n" . $herecurr);
4767 # * goes on variable not on type
4769 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4771 my ($ident, $from, $to) = ($1, $2, $2);
4773 # Should start with a space.
4774 $to =~ s/^(\S)/ $1/;
4775 # Should not end with a space.
4777 # '*'s should not have spaces between.
4778 while ($to =~ s/\*\s+\*/\*\*/) {
4781 ## print "1: from<$from> to<$to> ident<$ident>\n";
4783 if (ERROR
("POINTER_LOCATION",
4784 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4786 my $sub_from = $ident;
4787 my $sub_to = $ident;
4788 $sub_to =~ s/\Q$from\E/$to/;
4789 $fixed[$fixlinenr] =~
4790 s@\Q
$sub_from\E@
$sub_to@
;
4794 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4796 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4798 # Should start with a space.
4799 $to =~ s/^(\S)/ $1/;
4800 # Should not end with a space.
4802 # '*'s should not have spaces between.
4803 while ($to =~ s/\*\s+\*/\*\*/) {
4805 # Modifiers should have spaces.
4806 $to =~ s/(\b$Modifier$)/$1 /;
4808 ## print "2: from<$from> to<$to> ident<$ident>\n";
4809 if ($from ne $to && $ident !~ /^$Modifier$/) {
4810 if (ERROR
("POINTER_LOCATION",
4811 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4814 my $sub_from = $match;
4815 my $sub_to = $match;
4816 $sub_to =~ s/\Q$from\E/$to/;
4817 $fixed[$fixlinenr] =~
4818 s@\Q
$sub_from\E@
$sub_to@
;
4823 # avoid BUG() or BUG_ON()
4824 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4825 my $msg_level = \
&WARN
;
4826 $msg_level = \
&CHK
if ($file);
4827 &{$msg_level}("AVOID_BUG",
4828 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4831 # avoid LINUX_VERSION_CODE
4832 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4833 WARN
("LINUX_VERSION_CODE",
4834 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4837 # check for uses of printk_ratelimit
4838 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4839 WARN
("PRINTK_RATELIMITED",
4840 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4843 # printk should use KERN_* levels
4844 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4845 WARN
("PRINTK_WITHOUT_KERN_LEVEL",
4846 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4849 # prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4850 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4854 $modifier = "" if (!defined($modifier));
4855 my $level = lc($orig);
4856 $level = "warn" if ($level eq "warning");
4857 my $level2 = $level;
4858 $level2 = "dbg" if ($level eq "debug");
4859 $level .= $modifier;
4860 $level2 .= $modifier;
4861 WARN
("PREFER_PR_LEVEL",
4862 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr);
4865 # prefer dev_<level> to dev_printk(KERN_<LEVEL>
4866 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4868 my $level = lc($orig);
4869 $level = "warn" if ($level eq "warning");
4870 $level = "dbg" if ($level eq "debug");
4871 WARN
("PREFER_DEV_LEVEL",
4872 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4875 # trace_printk should not be used in production code.
4876 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4877 WARN
("TRACE_PRINTK",
4878 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4881 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4882 # number of false positives, but assembly files are not checked, so at
4883 # least the arch entry code will not trigger this warning.
4884 if ($line =~ /\bENOSYS\b/) {
4886 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4889 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4890 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4891 # Similarly to ENOSYS warning a small number of false positives is expected.
4892 if (!$file && $line =~ /\bENOTSUPP\b/) {
4893 if (WARN
("ENOTSUPP",
4894 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4896 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4900 # function brace can't be on same line, except for #defines of do while,
4901 # or if closed on same line
4902 if ($perl_version_ok &&
4903 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4904 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4906 if (ERROR
("OPEN_BRACE",
4907 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4909 fix_delete_line
($fixlinenr, $rawline);
4910 my $fixed_line = $rawline;
4911 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4914 fix_insert_line
($fixlinenr, ltrim
($line1));
4915 fix_insert_line
($fixlinenr, "\+{");
4916 if ($line2 !~ /^\s*$/) {
4917 fix_insert_line
($fixlinenr, "\+\t" . trim
($line2));
4922 # open braces for enum, union and struct go on the same line.
4923 if ($line =~ /^.\s*{/ &&
4924 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4925 if (ERROR
("OPEN_BRACE",
4926 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4927 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4928 fix_delete_line
($fixlinenr - 1, $prevrawline);
4929 fix_delete_line
($fixlinenr, $rawline);
4930 my $fixedline = rtrim
($prevrawline) . " {";
4931 fix_insert_line
($fixlinenr, $fixedline);
4932 $fixedline = $rawline;
4933 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4934 if ($fixedline !~ /^\+\s*$/) {
4935 fix_insert_line
($fixlinenr, $fixedline);
4940 # missing space after union, struct or enum definition
4941 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4943 "missing space after $1 definition\n" . $herecurr) &&
4945 $fixed[$fixlinenr] =~
4946 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4950 # Function pointer declarations
4951 # check spacing between type, funcptr, and args
4952 # canonical declaration is "type (*funcptr)(args...)"
4953 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4955 my $pre_pointer_space = $2;
4956 my $post_pointer_space = $3;
4958 my $post_funcname_space = $5;
4959 my $pre_args_space = $6;
4961 # the $Declare variable will capture all spaces after the type
4962 # so check it for a missing trailing missing space but pointer return types
4963 # don't need a space so don't warn for those.
4964 my $post_declare_space = "";
4965 if ($declare =~ /(\s+)$/) {
4966 $post_declare_space = $1;
4967 $declare = rtrim
($declare);
4969 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4971 "missing space after return type\n" . $herecurr);
4972 $post_declare_space = " ";
4975 # unnecessary space "type (*funcptr)(args...)"
4976 # This test is not currently implemented because these declarations are
4978 # int foo(int bar, ...)
4979 # and this is form shouldn't/doesn't generate a checkpatch warning.
4981 # elsif ($declare =~ /\s{2,}$/) {
4983 # "Multiple spaces after return type\n" . $herecurr);
4986 # unnecessary space "type ( *funcptr)(args...)"
4987 if (defined $pre_pointer_space &&
4988 $pre_pointer_space =~ /^\s/) {
4990 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4993 # unnecessary space "type (* funcptr)(args...)"
4994 if (defined $post_pointer_space &&
4995 $post_pointer_space =~ /^\s/) {
4997 "Unnecessary space before function pointer name\n" . $herecurr);
5000 # unnecessary space "type (*funcptr )(args...)"
5001 if (defined $post_funcname_space &&
5002 $post_funcname_space =~ /^\s/) {
5004 "Unnecessary space after function pointer name\n" . $herecurr);
5007 # unnecessary space "type (*funcptr) (args...)"
5008 if (defined $pre_args_space &&
5009 $pre_args_space =~ /^\s/) {
5011 "Unnecessary space before function pointer arguments\n" . $herecurr);
5014 if (show_type
("SPACING") && $fix) {
5015 $fixed[$fixlinenr] =~
5016 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5020 # check for spacing round square brackets; allowed:
5021 # 1. with a type on the left -- int [] a;
5022 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5023 # 3. inside a curly brace -- = { [0...10] = 5 }
5024 while ($line =~ /(.*?\s)\[/g) {
5025 my ($where, $prefix) = ($-[1], $1);
5026 if ($prefix !~ /$Type\s+$/ &&
5027 ($where != 0 || $prefix !~ /^.\s+$/) &&
5028 $prefix !~ /[{,:]\s+$/) {
5029 if (ERROR
("BRACKET_SPACE",
5030 "space prohibited before open square bracket '['\n" . $herecurr) &&
5032 $fixed[$fixlinenr] =~
5033 s/^(\+.*?)\s+\[/$1\[/;
5038 # check for spaces between functions and their parentheses.
5039 while ($line =~ /($Ident)\s+\(/g) {
5041 my $ctx_before = substr($line, 0, $-[1]);
5042 my $ctx = "$ctx_before$name";
5044 # Ignore those directives where spaces _are_ permitted.
5046 if|for|while|switch
|return|case
|
5047 volatile
|__volatile__
|
5048 __attribute__
|format
|__extension__
|
5051 # cpp #define statements have non-optional spaces, ie
5052 # if there is a space between the name and the open
5053 # parenthesis it is simply not a parameter group.
5054 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5056 # cpp #elif statement condition may start with a (
5057 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5059 # If this whole things ends with a type its most
5060 # likely a typedef for a function.
5061 } elsif ($ctx =~ /$Type$/) {
5065 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5067 $fixed[$fixlinenr] =~
5068 s/\b$name\s+\(/$name\(/;
5073 # Check operator spacing.
5074 if (!($line=~/\#\s*include/)) {
5075 my $fixed_line = "";
5079 <<=|>>=|<=|>=|==|!=|
5080 \
+=|-=|\
*=|\
/=|%=|\
^=|\
|=|&=|
5081 =>|->|<<|>>|<|>|=|!|~|
5082 &&|\
|\
||,|\
^|\
+\
+|--|&|\
||\
+|-|\
*|\
/|%|
5085 my @elements = split(/($ops|;)/, $opline);
5087 ## print("element count: <" . $#elements . ">\n");
5088 ## foreach my $el (@elements) {
5089 ## print("el: <$el>\n");
5092 my @fix_elements = ();
5095 foreach my $el (@elements) {
5096 push(@fix_elements, substr($rawline, $off, length($el)));
5097 $off += length($el);
5102 my $blank = copy_spacing
($opline);
5103 my $last_after = -1;
5105 for (my $n = 0; $n < $#elements; $n += 2) {
5107 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5109 ## print("n: <$n> good: <$good>\n");
5111 $off += length($elements[$n]);
5113 # Pick up the preceding and succeeding characters.
5114 my $ca = substr($opline, 0, $off);
5116 if (length($opline) >= ($off + length($elements[$n + 1]))) {
5117 $cc = substr($opline, $off + length($elements[$n + 1]));
5119 my $cb = "$ca$;$cc";
5122 $a = 'V' if ($elements[$n] ne '');
5123 $a = 'W' if ($elements[$n] =~ /\s$/);
5124 $a = 'C' if ($elements[$n] =~ /$;$/);
5125 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5126 $a = 'O' if ($elements[$n] eq '');
5127 $a = 'E' if ($ca =~ /^\s*$/);
5129 my $op = $elements[$n + 1];
5132 if (defined $elements[$n + 2]) {
5133 $c = 'V' if ($elements[$n + 2] ne '');
5134 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
5135 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
5136 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5137 $c = 'O' if ($elements[$n + 2] eq '');
5138 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5143 my $ctx = "${a}x${c}";
5145 my $at = "(ctx:$ctx)";
5147 my $ptr = substr($blank, 0, $off) . "^";
5148 my $hereptr = "$hereline$ptr\n";
5150 # Pull out the value of this operator.
5151 my $op_type = substr($curr_values, $off + 1, 1);
5153 # Get the full operator variant.
5154 my $opv = $op . substr($curr_vars, $off, 1);
5156 # Ignore operators passed as parameters.
5157 if ($op_type ne 'V' &&
5158 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5161 # } elsif ($op =~ /^$;+$/) {
5163 # ; should have either the end of line or a space or \ after it
5164 } elsif ($op eq ';') {
5165 if ($ctx !~ /.x[WEBC]/ &&
5166 $cc !~ /^\\/ && $cc !~ /^;/) {
5167 if (ERROR
("SPACING",
5168 "space required after that '$op' $at\n" . $hereptr)) {
5169 $good = $fix_elements[$n] . trim
($fix_elements[$n + 1]) . " ";
5175 } elsif ($op eq '//') {
5177 # : when part of a bitfield
5178 } elsif ($opv eq ':B') {
5179 # skip the bitfield test for now
5183 } elsif ($op eq '->') {
5184 if ($ctx =~ /Wx.|.xW/) {
5185 if (ERROR
("SPACING",
5186 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5187 $good = rtrim
($fix_elements[$n]) . trim
($fix_elements[$n + 1]);
5188 if (defined $fix_elements[$n + 2]) {
5189 $fix_elements[$n + 2] =~ s/^\s+//;
5195 # , must not have a space before and must have a space on the right.
5196 } elsif ($op eq ',') {
5197 my $rtrim_before = 0;
5198 my $space_after = 0;
5199 if ($ctx =~ /Wx./) {
5200 if (ERROR
("SPACING",
5201 "space prohibited before that '$op' $at\n" . $hereptr)) {
5206 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5207 if (ERROR
("SPACING",
5208 "space required after that '$op' $at\n" . $hereptr)) {
5214 if ($rtrim_before || $space_after) {
5215 if ($rtrim_before) {
5216 $good = rtrim
($fix_elements[$n]) . trim
($fix_elements[$n + 1]);
5218 $good = $fix_elements[$n] . trim
($fix_elements[$n + 1]);
5225 # '*' as part of a type definition -- reported already.
5226 } elsif ($opv eq '*_') {
5227 #warn "'*' is part of type\n";
5229 # unary operators should have a space before and
5230 # none after. May be left adjacent to another
5231 # unary operator, or a cast
5232 } elsif ($op eq '!' || $op eq '~' ||
5233 $opv eq '*U' || $opv eq '-U' ||
5234 $opv eq '&U' || $opv eq '&&U') {
5235 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5236 if (ERROR
("SPACING",
5237 "space required before that '$op' $at\n" . $hereptr)) {
5238 if ($n != $last_after + 2) {
5239 $good = $fix_elements[$n] . " " . ltrim
($fix_elements[$n + 1]);
5244 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5245 # A unary '*' may be const
5247 } elsif ($ctx =~ /.xW/) {
5248 if (ERROR
("SPACING",
5249 "space prohibited after that '$op' $at\n" . $hereptr)) {
5250 $good = $fix_elements[$n] . rtrim
($fix_elements[$n + 1]);
5251 if (defined $fix_elements[$n + 2]) {
5252 $fix_elements[$n + 2] =~ s/^\s+//;
5258 # unary ++ and unary -- are allowed no space on one side.
5259 } elsif ($op eq '++' or $op eq '--') {
5260 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5261 if (ERROR
("SPACING",
5262 "space required one side of that '$op' $at\n" . $hereptr)) {
5263 $good = $fix_elements[$n] . trim
($fix_elements[$n + 1]) . " ";
5267 if ($ctx =~ /Wx[BE]/ ||
5268 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5269 if (ERROR
("SPACING",
5270 "space prohibited before that '$op' $at\n" . $hereptr)) {
5271 $good = rtrim
($fix_elements[$n]) . trim
($fix_elements[$n + 1]);
5275 if ($ctx =~ /ExW/) {
5276 if (ERROR
("SPACING",
5277 "space prohibited after that '$op' $at\n" . $hereptr)) {
5278 $good = $fix_elements[$n] . trim
($fix_elements[$n + 1]);
5279 if (defined $fix_elements[$n + 2]) {
5280 $fix_elements[$n + 2] =~ s/^\s+//;
5286 # << and >> may either have or not have spaces both sides
5287 } elsif ($op eq '<<' or $op eq '>>' or
5288 $op eq '&' or $op eq '^' or $op eq '|' or
5289 $op eq '+' or $op eq '-' or
5290 $op eq '*' or $op eq '/' or
5294 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5296 "spaces preferred around that '$op' $at\n" . $hereptr)) {
5297 $good = rtrim
($fix_elements[$n]) . " " . trim
($fix_elements[$n + 1]) . " ";
5298 $fix_elements[$n + 2] =~ s/^\s+//;
5301 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5303 "space preferred before that '$op' $at\n" . $hereptr)) {
5304 $good = rtrim
($fix_elements[$n]) . " " . trim
($fix_elements[$n + 1]);
5308 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5309 if (ERROR
("SPACING",
5310 "need consistent spacing around '$op' $at\n" . $hereptr)) {
5311 $good = rtrim
($fix_elements[$n]) . " " . trim
($fix_elements[$n + 1]) . " ";
5312 if (defined $fix_elements[$n + 2]) {
5313 $fix_elements[$n + 2] =~ s/^\s+//;
5319 # A colon needs no spaces before when it is
5320 # terminating a case value or a label.
5321 } elsif ($opv eq ':C' || $opv eq ':L') {
5322 if ($ctx =~ /Wx./ and $realfile !~ m@
.*\
.lds\
.h
$@
) {
5323 if (ERROR
("SPACING",
5324 "space prohibited before that '$op' $at\n" . $hereptr)) {
5325 $good = rtrim
($fix_elements[$n]) . trim
($fix_elements[$n + 1]);
5330 # All the others need spaces both sides.
5331 } elsif ($ctx !~ /[EWC]x[CWE]/) {
5334 # Ignore email addresses <foo@bar>
5336 $cc =~ /^\S+\@\S+>/) ||
5338 $ca =~ /<\S+\@\S+$/))
5343 # for asm volatile statements
5344 # ignore a colon with another
5345 # colon immediately before or after
5347 ($ca =~ /:$/ || $cc =~ /^:/)) {
5351 # messages are ERROR, but ?: are CHK
5353 my $msg_level = \
&ERROR
;
5354 $msg_level = \
&CHK
if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5356 if (&{$msg_level}("SPACING",
5357 "spaces required around that '$op' $at\n" . $hereptr)) {
5358 $good = rtrim
($fix_elements[$n]) . " " . trim
($fix_elements[$n + 1]) . " ";
5359 if (defined $fix_elements[$n + 2]) {
5360 $fix_elements[$n + 2] =~ s/^\s+//;
5366 $off += length($elements[$n + 1]);
5368 ## print("n: <$n> GOOD: <$good>\n");
5370 $fixed_line = $fixed_line . $good;
5373 if (($#elements % 2) == 0) {
5374 $fixed_line = $fixed_line . $fix_elements[$#elements];
5377 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5378 $fixed[$fixlinenr] = $fixed_line;
5384 # check for whitespace before a non-naked semicolon
5385 if ($line =~ /^\+.*\S\s+;\s*$/) {
5387 "space prohibited before semicolon\n" . $herecurr) &&
5389 1 while $fixed[$fixlinenr] =~
5390 s/^(\+.*\S)\s+;/$1;/;
5394 # check for multiple assignments
5395 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5396 CHK
("MULTIPLE_ASSIGNMENTS",
5397 "multiple assignments should be avoided\n" . $herecurr);
5400 ## # check for multiple declarations, allowing for a function declaration
5402 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5403 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5405 ## # Remove any bracketed sections to ensure we do not
5406 ## # falsely report the parameters of functions.
5408 ## while ($ln =~ s/\([^\(\)]*\)//g) {
5410 ## if ($ln =~ /,/) {
5411 ## WARN("MULTIPLE_DECLARATION",
5412 ## "declaring multiple variables together should be avoided\n" . $herecurr);
5416 #need space before brace following if, while, etc
5417 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5418 $line =~ /\b(?:else|do)\{/) {
5419 if (ERROR
("SPACING",
5420 "space required before the open brace '{'\n" . $herecurr) &&
5422 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5426 ## # check for blank lines before declarations
5427 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5428 ## $prevrawline =~ /^.\s*$/) {
5430 ## "No blank lines before declarations\n" . $hereprev);
5434 # closing brace should have a space following it when it has anything
5436 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5437 if (ERROR
("SPACING",
5438 "space required after that close brace '}'\n" . $herecurr) &&
5440 $fixed[$fixlinenr] =~
5441 s/}((?!(?:,|;|\)))\S)/} $1/;
5445 # check spacing on square brackets
5446 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5447 if (ERROR
("SPACING",
5448 "space prohibited after that open square bracket '['\n" . $herecurr) &&
5450 $fixed[$fixlinenr] =~
5454 if ($line =~ /\s\]/) {
5455 if (ERROR
("SPACING",
5456 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5458 $fixed[$fixlinenr] =~
5463 # check spacing on parentheses
5464 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5465 $line !~ /for\s*\(\s+;/) {
5466 if (ERROR
("SPACING",
5467 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5469 $fixed[$fixlinenr] =~
5473 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5474 $line !~ /for\s*\(.*;\s+\)/ &&
5475 $line !~ /:\s+\)/) {
5476 if (ERROR
("SPACING",
5477 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5479 $fixed[$fixlinenr] =~
5484 # check unnecessary parentheses around addressof/dereference single $Lvals
5485 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5487 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5489 if (CHK
("UNNECESSARY_PARENTHESES",
5490 "Unnecessary parentheses around $var\n" . $herecurr) &&
5492 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5496 # check for unnecessary parentheses around function pointer uses
5497 # ie: (foo->bar)(); should be foo->bar();
5498 # but not "if (foo->bar) (" to avoid some false positives
5499 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5501 if (CHK
("UNNECESSARY_PARENTHESES",
5502 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5504 my $var2 = deparenthesize
($var);
5506 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5510 # check for unnecessary parentheses around comparisons in if uses
5511 # when !drivers/staging or command-line uses --strict
5512 if (($realfile !~ m@
^(?
:drivers
/staging/)@
|| $check_orig) &&
5513 $perl_version_ok && defined($stat) &&
5514 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5516 my $test = substr($2, 1, -1);
5518 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5520 # avoid parentheses around potential macro args
5521 next if ($match =~ /^\s*\w+\s*$/);
5522 if (!defined($herectx)) {
5523 $herectx = $here . "\n";
5524 my $cnt = statement_rawlines
($if_stat);
5525 for (my $n = 0; $n < $cnt; $n++) {
5526 my $rl = raw_line
($linenr, $n);
5527 $herectx .= $rl . "\n";
5528 last if $rl =~ /^[ \+].*\{/;
5531 CHK
("UNNECESSARY_PARENTHESES",
5532 "Unnecessary parentheses around '$match'\n" . $herectx);
5536 # check that goto labels aren't indented (allow a single space indentation)
5537 # and ignore bitfield definitions like foo:1
5538 # Strictly, labels can have whitespace after the identifier and before the :
5539 # but this is not allowed here as many ?: uses would appear to be labels
5540 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5541 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5542 $sline !~ /^.\s+default:/) {
5543 if (WARN
("INDENTED_LABEL",
5544 "labels should not be indented\n" . $herecurr) &&
5546 $fixed[$fixlinenr] =~
5551 # check if a statement with a comma should be two statements like:
5552 # foo = bar(), /* comma should be semicolon */
5554 if (defined($stat) &&
5555 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5556 my $cnt = statement_rawlines
($stat);
5557 my $herectx = get_stat_here
($linenr, $cnt, $here);
5558 WARN
("SUSPECT_COMMA_SEMICOLON",
5559 "Possible comma where semicolon could be used\n" . $herectx);
5562 # return is not a function
5563 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5565 if ($perl_version_ok &&
5566 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5568 $value = deparenthesize
($value);
5569 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5570 ERROR
("RETURN_PARENTHESES",
5571 "return is not a function, parentheses are not required\n" . $herecurr);
5573 } elsif ($spacing !~ /\s+/) {
5575 "space required before the open parenthesis '('\n" . $herecurr);
5579 # unnecessary return in a void function
5580 # at end-of-function, with the previous line a single leading tab, then return;
5581 # and the line before that not a goto label target like "out:"
5582 if ($sline =~ /^[ \+]}\s*$/ &&
5583 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5585 $lines[$linenr - 3] =~ /^[ +]/ &&
5586 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5588 "void function return statements are not generally useful\n" . $hereprev);
5591 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5592 if ($perl_version_ok &&
5593 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5594 my $openparens = $1;
5595 my $count = $openparens =~ tr@\
(@\
(@
;
5597 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5598 my $comp = $4; #Not $1 because of $LvalOrFunc
5599 $msg = " - maybe == should be = ?" if ($comp eq "==");
5600 WARN
("UNNECESSARY_PARENTHESES",
5601 "Unnecessary parentheses$msg\n" . $herecurr);
5605 # comparisons with a constant or upper case identifier on the left
5606 # avoid cases like "foo + BAR < baz"
5607 # only fix matches surrounded by parentheses to avoid incorrect
5608 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5609 if ($perl_version_ok &&
5610 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5615 my $newcomp = $comp;
5616 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5617 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5618 WARN
("CONSTANT_COMPARISON",
5619 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5623 } elsif ($comp eq "<=") {
5625 } elsif ($comp eq ">") {
5627 } elsif ($comp eq ">=") {
5630 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5634 # Return of what appears to be an errno should normally be negative
5635 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5637 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5638 WARN
("USE_NEGATIVE_ERRNO",
5639 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5643 # Need a space before open parenthesis after if, while etc
5644 if ($line =~ /\b(if|while|for|switch)\(/) {
5645 if (ERROR
("SPACING",
5646 "space required before the open parenthesis '('\n" . $herecurr) &&
5648 $fixed[$fixlinenr] =~
5649 s/\b(if|while|for|switch)\(/$1 \(/;
5653 # Check for illegal assignment in if conditional -- and check for trailing
5654 # statements after the conditional.
5655 if ($line =~ /do\s*(?!{)/) {
5656 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5657 ctx_statement_block
($linenr, $realcnt, 0)
5658 if (!defined $stat);
5659 my ($stat_next) = ctx_statement_block
($line_nr_next,
5660 $remain_next, $off_next);
5661 $stat_next =~ s/\n./\n /g;
5662 ##print "stat<$stat> stat_next<$stat_next>\n";
5664 if ($stat_next =~ /^\s*while\b/) {
5665 # If the statement carries leading newlines,
5666 # then count those as offsets.
5668 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5670 statement_rawlines
($whitespace) - 1;
5672 $suppress_whiletrailers{$line_nr_next +
5676 if (!defined $suppress_whiletrailers{$linenr} &&
5677 defined($stat) && defined($cond) &&
5678 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5679 my ($s, $c) = ($stat, $cond);
5681 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5682 if (ERROR
("ASSIGN_IN_IF",
5683 "do not use assignment in if condition\n" . $herecurr) &&
5684 $fix && $perl_version_ok) {
5685 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5693 fix_delete_line
($fixlinenr, $rawline);
5694 fix_insert_line
($fixlinenr, "$space$statement;");
5695 my $newline = "${space}if (";
5696 $newline .= '!' if defined($not);
5697 $newline .= '(' if (defined $not && defined($test) && defined($against));
5698 $newline .= "$assigned";
5699 $newline .= " $test $against" if (defined($test) && defined($against));
5700 $newline .= ')' if (defined $not && defined($test) && defined($against));
5702 $newline .= " {" if (defined($brace));
5703 fix_insert_line
($fixlinenr + 1, $newline);
5708 # Find out what is on the end of the line after the
5710 substr($s, 0, length($c), '');
5712 $s =~ s/$;//g; # Remove any comments
5713 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5714 $c !~ /}\s*while\s*/)
5716 # Find out how long the conditional actually is.
5717 my @newlines = ($c =~ /\n/gs);
5718 my $cond_lines = 1 + $#newlines;
5721 $stat_real = raw_line
($linenr, $cond_lines)
5722 . "\n" if ($cond_lines);
5723 if (defined($stat_real) && $cond_lines > 1) {
5724 $stat_real = "[...]\n$stat_real";
5727 ERROR
("TRAILING_STATEMENTS",
5728 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5732 # Check for bitwise tests written as boolean
5744 WARN
("HEXADECIMAL_BOOLEAN_TEST",
5745 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5748 # if and else should not have general statements after it
5749 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5751 $s =~ s/$;//g; # Remove any comments
5752 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5753 ERROR
("TRAILING_STATEMENTS",
5754 "trailing statements should be on next line\n" . $herecurr);
5757 # if should not continue a brace
5758 if ($line =~ /}\s*if\b/) {
5759 ERROR
("TRAILING_STATEMENTS",
5760 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5763 # case and default should not have general statements after them
5764 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5766 (?
:\s
*$;*)(?
:\s
*{)?
(?
:\s
*$;*)(?
:\s
*\\)?\s
*$|
5770 ERROR
("TRAILING_STATEMENTS",
5771 "trailing statements should be on next line\n" . $herecurr);
5774 # Check for }<nl>else {, these must be at the same
5775 # indent level to be relevant to each other.
5776 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5777 $previndent == $indent) {
5778 if (ERROR
("ELSE_AFTER_BRACE",
5779 "else should follow close brace '}'\n" . $hereprev) &&
5780 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5781 fix_delete_line
($fixlinenr - 1, $prevrawline);
5782 fix_delete_line
($fixlinenr, $rawline);
5783 my $fixedline = $prevrawline;
5784 $fixedline =~ s/}\s*$//;
5785 if ($fixedline !~ /^\+\s*$/) {
5786 fix_insert_line
($fixlinenr, $fixedline);
5788 $fixedline = $rawline;
5789 $fixedline =~ s/^(.\s*)else/$1} else/;
5790 fix_insert_line
($fixlinenr, $fixedline);
5794 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5795 $previndent == $indent) {
5796 my ($s, $c) = ctx_statement_block
($linenr, $realcnt, 0);
5798 # Find out what is on the end of the line after the
5800 substr($s, 0, length($c), '');
5803 if ($s =~ /^\s*;/) {
5804 if (ERROR
("WHILE_AFTER_BRACE",
5805 "while should follow close brace '}'\n" . $hereprev) &&
5806 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5807 fix_delete_line
($fixlinenr - 1, $prevrawline);
5808 fix_delete_line
($fixlinenr, $rawline);
5809 my $fixedline = $prevrawline;
5810 my $trailing = $rawline;
5811 $trailing =~ s/^\+//;
5812 $trailing = trim
($trailing);
5813 $fixedline =~ s/}\s*$/} $trailing/;
5814 fix_insert_line
($fixlinenr, $fixedline);
5819 #Specific variable tests
5820 while ($line =~ m{($Constant|$Lval)}g) {
5824 if ($var !~ /^$Constant$/ &&
5825 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5826 #Ignore some autogenerated defines and enum values
5827 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5828 #Ignore Page<foo> variants
5829 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5830 #Ignore SI style variants like nS, mV and dB
5831 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5832 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5833 #Ignore some three character SI units explicitly, like MiB and KHz
5834 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5835 while ($var =~ m{($Ident)}g) {
5837 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5839 seed_camelcase_includes
();
5840 if (!$file && !$camelcase_file_seeded) {
5841 seed_camelcase_file
($realfile);
5842 $camelcase_file_seeded = 1;
5845 if (!defined $camelcase{$word}) {
5846 $camelcase{$word} = 1;
5848 "Avoid CamelCase: <$word>\n" . $herecurr);
5854 #no spaces allowed after \ in define
5855 if ($line =~ /\#\s*define.*\\\s+$/) {
5856 if (WARN
("WHITESPACE_AFTER_LINE_CONTINUATION",
5857 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5859 $fixed[$fixlinenr] =~ s/\s+$//;
5863 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5864 # itself <asm/foo.h> (uses RAW line)
5865 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5867 my $checkfile = "include/linux/$file";
5868 if (-f
"$root/$checkfile" &&
5869 $realfile ne $checkfile &&
5870 $1 !~ /$allowed_asm_includes/)
5872 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5873 if ($asminclude > 0) {
5874 if ($realfile =~ m{^arch/}) {
5875 CHK
("ARCH_INCLUDE_LINUX",
5876 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5878 WARN
("INCLUDE_LINUX",
5879 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5885 # multi-statement macros should be enclosed in a do while loop, grab the
5886 # first statement and ensure its the whole macro if its not enclosed
5887 # in a known good container
5888 if ($realfile !~ m@
/vmlinux
.lds
.h
$@
&&
5889 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5892 my ($off, $dstat, $dcond, $rest);
5894 my $has_flow_statement = 0;
5895 my $has_arg_concat = 0;
5896 ($dstat, $dcond, $ln, $cnt, $off) =
5897 ctx_statement_block
($linenr, $realcnt, 0);
5899 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5900 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5902 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5903 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5905 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5906 my $define_args = $1;
5907 my $define_stmt = $dstat;
5910 if (defined $define_args && $define_args ne "") {
5911 $define_args = substr($define_args, 1, length($define_args) - 2);
5912 $define_args =~ s/\s*//g;
5913 $define_args =~ s/\\\+?//g;
5914 @def_args = split(",", $define_args);
5918 $dstat =~ s/\\\n.//g;
5919 $dstat =~ s/^\s*//s;
5920 $dstat =~ s/\s*$//s;
5922 # Flatten any parentheses and braces
5923 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5924 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5925 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5929 # Flatten any obvious string concatenation.
5930 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5931 $dstat =~ s/$Ident\s*($String)/$1/)
5935 # Make asm volatile uses seem like a generic function
5936 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5938 my $exceptions = qr{
5951 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5954 my $stmt_cnt = statement_rawlines
($ctx);
5955 my $herectx = get_stat_here
($linenr, $stmt_cnt, $here);
5958 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5959 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5960 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5961 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5962 $dstat !~ /$exceptions/ &&
5963 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5964 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5965 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5966 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5967 $dstat !~ /^for\s*$Constant$/ && # for (...)
5968 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5969 $dstat !~ /^do\s*{/ && # do {...
5970 $dstat !~ /^\(\{/ && # ({...
5971 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5973 if ($dstat =~ /^\s*if\b/) {
5974 ERROR
("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5975 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5976 } elsif ($dstat =~ /;/) {
5977 ERROR
("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5978 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5980 ERROR
("COMPLEX_MACRO",
5981 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5986 # Make $define_stmt single line, comment-free, etc
5987 my @stmt_array = split('\n', $define_stmt);
5990 foreach my $l (@stmt_array) {
5995 } elsif ($l =~ /^[\+ ]/) {
5996 $define_stmt .= substr($l, 1);
5999 $define_stmt =~ s/$;//g;
6000 $define_stmt =~ s/\s+/ /g;
6001 $define_stmt = trim
($define_stmt);
6003 # check if any macro arguments are reused (ignore '...' and 'type')
6004 foreach my $arg (@def_args) {
6005 next if ($arg =~ /\.\.\./);
6006 next if ($arg =~ /^type$/i);
6007 my $tmp_stmt = $define_stmt;
6008 $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;
6009 $tmp_stmt =~ s/\#+\s*$arg\b//g;
6010 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
6011 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6013 CHK
("MACRO_ARG_REUSE",
6014 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6016 # check if any macro arguments may have other precedence issues
6017 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6018 ((defined($1) && $1 ne ',') ||
6019 (defined($2) && $2 ne ','))) {
6020 CHK
("MACRO_ARG_PRECEDENCE",
6021 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6025 # check for macros with flow control, but without ## concatenation
6026 # ## concatenation is commonly a macro that defines a function so ignore those
6027 if ($has_flow_statement && !$has_arg_concat) {
6028 my $cnt = statement_rawlines
($ctx);
6029 my $herectx = get_stat_here
($linenr, $cnt, $here);
6031 WARN
("MACRO_WITH_FLOW_CONTROL",
6032 "Macros with flow control statements should be avoided\n" . "$herectx");
6035 # check for line continuations outside of #defines, preprocessor #, and asm
6038 if ($prevline !~ /^..*\\$/ &&
6039 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
6040 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
6041 $line =~ /^\+.*\\$/) {
6042 WARN
("LINE_CONTINUATIONS",
6043 "Avoid unnecessary line continuations\n" . $herecurr);
6047 # do {} while (0) macro tests:
6048 # single-statement macros do not need to be enclosed in do while (0) loop,
6049 # macro should not end with a semicolon
6050 if ($perl_version_ok &&
6051 $realfile !~ m@
/vmlinux
.lds
.h
$@
&&
6052 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6055 my ($off, $dstat, $dcond, $rest);
6057 ($dstat, $dcond, $ln, $cnt, $off) =
6058 ctx_statement_block
($linenr, $realcnt, 0);
6061 $dstat =~ s/\\\n.//g;
6064 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6069 my $cnt = statement_rawlines
($ctx);
6070 my $herectx = get_stat_here
($linenr, $cnt, $here);
6072 if (($stmts =~ tr/;/;/) == 1 &&
6073 $stmts !~ /^\s*(if|while|for|switch)\b/) {
6074 WARN
("SINGLE_STATEMENT_DO_WHILE_MACRO",
6075 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6077 if (defined $semis && $semis ne "") {
6078 WARN
("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6079 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6081 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6083 my $cnt = statement_rawlines
($ctx);
6084 my $herectx = get_stat_here
($linenr, $cnt, $here);
6086 WARN
("TRAILING_SEMICOLON",
6087 "macros should not use a trailing semicolon\n" . "$herectx");
6091 # check for redundant bracing round if etc
6092 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6093 my ($level, $endln, @chunks) =
6094 ctx_statement_full
($linenr, $realcnt, 1);
6095 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6096 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6097 if ($#chunks > 0 && $level == 0) {
6101 my $herectx = $here . "\n";
6102 my $ln = $linenr - 1;
6103 for my $chunk (@chunks) {
6104 my ($cond, $block) = @
{$chunk};
6106 # If the condition carries leading newlines, then count those as offsets.
6107 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6108 my $offset = statement_rawlines
($whitespace) - 1;
6110 $allowed[$allow] = 0;
6111 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6113 # We have looked at and allowed this specific line.
6114 $suppress_ifbraces{$ln + $offset} = 1;
6116 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6117 $ln += statement_rawlines
($block) - 1;
6119 substr($block, 0, length($cond), '');
6121 $seen++ if ($block =~ /^\s*{/);
6123 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6124 if (statement_lines
($cond) > 1) {
6125 #print "APW: ALLOWED: cond<$cond>\n";
6126 $allowed[$allow] = 1;
6128 if ($block =~/\b(?:if|for|while)\b/) {
6129 #print "APW: ALLOWED: block<$block>\n";
6130 $allowed[$allow] = 1;
6132 if (statement_block_size
($block) > 1) {
6133 #print "APW: ALLOWED: lines block<$block>\n";
6134 $allowed[$allow] = 1;
6139 my $sum_allowed = 0;
6140 foreach (@allowed) {
6143 if ($sum_allowed == 0) {
6145 "braces {} are not necessary for any arm of this statement\n" . $herectx);
6146 } elsif ($sum_allowed != $allow &&
6149 "braces {} should be used on all arms of this statement\n" . $herectx);
6154 if (!defined $suppress_ifbraces{$linenr - 1} &&
6155 $line =~ /\b(if|while|for|else)\b/) {
6158 # Check the pre-context.
6159 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6160 #print "APW: ALLOWED: pre<$1>\n";
6164 my ($level, $endln, @chunks) =
6165 ctx_statement_full
($linenr, $realcnt, $-[0]);
6167 # Check the condition.
6168 my ($cond, $block) = @
{$chunks[0]};
6169 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6170 if (defined $cond) {
6171 substr($block, 0, length($cond), '');
6173 if (statement_lines
($cond) > 1) {
6174 #print "APW: ALLOWED: cond<$cond>\n";
6177 if ($block =~/\b(?:if|for|while)\b/) {
6178 #print "APW: ALLOWED: block<$block>\n";
6181 if (statement_block_size
($block) > 1) {
6182 #print "APW: ALLOWED: lines block<$block>\n";
6185 # Check the post-context.
6186 if (defined $chunks[1]) {
6187 my ($cond, $block) = @
{$chunks[1]};
6188 if (defined $cond) {
6189 substr($block, 0, length($cond), '');
6191 if ($block =~ /^\s*\{/) {
6192 #print "APW: ALLOWED: chunk-1 block<$block>\n";
6196 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6197 my $cnt = statement_rawlines
($block);
6198 my $herectx = get_stat_here
($linenr, $cnt, $here);
6201 "braces {} are not necessary for single statement blocks\n" . $herectx);
6205 # check for single line unbalanced braces
6206 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6207 $sline =~ /^.\s*else\s*\{\s*$/) {
6208 CHK
("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6211 # check for unnecessary blank lines around braces
6212 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6214 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6215 $fix && $prevrawline =~ /^\+/) {
6216 fix_delete_line
($fixlinenr - 1, $prevrawline);
6219 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6221 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6223 fix_delete_line
($fixlinenr, $rawline);
6227 # no volatiles please
6228 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6229 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6231 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6234 # Check for user-visible strings broken across lines, which breaks the ability
6235 # to grep for the string. Make exceptions when the previous string ends in a
6236 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6237 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6238 if ($line =~ /^\+\s*$String/ &&
6239 $prevline =~ /"\s*$/ &&
6240 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6241 if (WARN
("SPLIT_STRING",
6242 "quoted string split across lines\n" . $hereprev) &&
6244 $prevrawline =~ /^\+.*"\s*$/ &&
6245 $last_coalesced_string_linenr != $linenr - 1) {
6246 my $extracted_string = get_quoted_string
($line, $rawline);
6247 my $comma_close = "";
6248 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6252 fix_delete_line
($fixlinenr - 1, $prevrawline);
6253 fix_delete_line
($fixlinenr, $rawline);
6254 my $fixedline = $prevrawline;
6255 $fixedline =~ s/"\s*$//;
6256 $fixedline .= substr($extracted_string, 1) . trim
($comma_close);
6257 fix_insert_line
($fixlinenr - 1, $fixedline);
6258 $fixedline = $rawline;
6259 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6260 if ($fixedline !~ /\+\s*$/) {
6261 fix_insert_line
($fixlinenr, $fixedline);
6263 $last_coalesced_string_linenr = $linenr;
6267 # check for missing a space in a string concatenation
6268 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6269 WARN
('MISSING_SPACE',
6270 "break quoted strings at a space character\n" . $hereprev);
6273 # check for an embedded function name in a string when the function is known
6274 # This does not work very well for -f --file checking as it depends on patch
6275 # context providing the function name or a single line form for in-file
6276 # function declarations
6277 if ($line =~ /^\+.*$String/ &&
6278 defined($context_function) &&
6279 get_quoted_string
($line, $rawline) =~ /\b$context_function\b/ &&
6280 length(get_quoted_string
($line, $rawline)) != (length($context_function) + 2)) {
6281 WARN
("EMBEDDED_FUNCTION_NAME",
6282 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6285 # check for unnecessary function tracing like uses
6286 # This does not use $logFunctions because there are many instances like
6287 # 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6288 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6289 if (WARN
("TRACING_LOGGING",
6290 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6292 fix_delete_line
($fixlinenr, $rawline);
6296 # check for spaces before a quoted newline
6297 if ($rawline =~ /^.*\".*\s\\n/) {
6298 if (WARN
("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6299 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6301 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6306 # concatenated string without spaces between elements
6307 if ($line =~ /$String[A-Z_]/ ||
6308 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6309 if (CHK
("CONCATENATED_STRING",
6310 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
6312 while ($line =~ /($String)/g) {
6313 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6314 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6315 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6320 # uncoalesced string fragments
6321 if ($line =~ /$String\s*[Lu]?"/) {
6322 if (WARN
("STRING_FRAGMENTS",
6323 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6325 while ($line =~ /($String)(?=\s*")/g) {
6326 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6327 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6332 # check for non-standard and hex prefixed decimal printf formats
6333 my $show_L = 1; #don't show the same defect twice
6335 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6336 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6337 $string =~ s/%%/__/g;
6339 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6341 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6345 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6347 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6350 # check for 0x<decimal>
6351 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6352 ERROR
("PRINTF_0XDECIMAL",
6353 "Prefixing 0x with decimal output is defective\n" . $herecurr);
6357 # check for line continuations in quoted strings with odd counts of "
6358 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6359 WARN
("LINE_CONTINUATIONS",
6360 "Avoid line continuations in quoted strings\n" . $herecurr);
6364 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6366 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6370 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6372 "Consider removing the #if 1 and its #endif\n" . $herecurr);
6375 # check for needless "if (<foo>) fn(<foo>)" uses
6376 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6377 my $tested = quotemeta($1);
6378 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6379 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6381 if (WARN
('NEEDLESS_IF',
6382 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6385 my $leading_tabs = "";
6386 my $new_leading_tabs = "";
6387 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6392 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6393 $new_leading_tabs = $1;
6394 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6401 fix_delete_line
($fixlinenr - 1, $prevrawline);
6402 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6408 # check for unnecessary "Out of Memory" messages
6409 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6410 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6411 (defined $1 || defined $3) &&
6414 my $testline = $lines[$linenr - 3];
6416 my ($s, $c) = ctx_statement_block
($linenr - 3, $realcnt, 0);
6417 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6419 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6420 $s !~ /\b__GFP_NOWARN\b/ ) {
6422 "Possible unnecessary 'out of memory' message\n" . $hereprev);
6426 # check for logging functions with KERN_<LEVEL>
6427 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6428 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6430 if (WARN
("UNNECESSARY_KERN_LEVEL",
6431 "Possible unnecessary $level\n" . $herecurr) &&
6433 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
6437 # check for logging continuations
6438 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6439 WARN
("LOGGING_CONTINUATION",
6440 "Avoid logging continuation uses where feasible\n" . $herecurr);
6443 # check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6444 if (defined $stat &&
6445 $line =~ /\b$logFunctions\s*\(/ &&
6446 index($stat, '"') >= 0) {
6447 my $lc = $stat =~ tr@
\n@@
;
6448 $lc = $lc + $linenr;
6449 my $stat_real = get_stat_real
($linenr, $lc);
6450 pos($stat_real) = index($stat_real, '"');
6451 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6454 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@
\n@@
;
6455 if (WARN
("UNNECESSARY_MODIFIER",
6456 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6457 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6460 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6465 # check for mask then right shift without a parentheses
6466 if ($perl_version_ok &&
6467 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6468 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6469 WARN
("MASK_THEN_SHIFT",
6470 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6473 # check for pointer comparisons to NULL
6474 if ($perl_version_ok) {
6475 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6478 $equal = "" if ($4 eq "!=");
6479 if (CHK
("COMPARISON_TO_NULL",
6480 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6482 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6487 # check for bad placement of section $InitAttribute (e.g.: __initdata)
6488 if ($line =~ /(\b$InitAttribute\b)/) {
6490 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6493 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6494 ERROR
("MISPLACED_INIT",
6495 "$attr should be placed after $var\n" . $herecurr)) ||
6496 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6497 WARN
("MISPLACED_INIT",
6498 "$attr should be placed after $var\n" . $herecurr))) &&
6500 $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;
6505 # check for $InitAttributeData (ie: __initdata) with const
6506 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6508 $attr =~ /($InitAttributePrefix)(.*)/;
6509 my $attr_prefix = $1;
6511 if (ERROR
("INIT_ATTRIBUTE",
6512 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6514 $fixed[$fixlinenr] =~
6515 s/$InitAttributeData/${attr_prefix}initconst/;
6519 # check for $InitAttributeConst (ie: __initconst) without const
6520 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6522 if (ERROR
("INIT_ATTRIBUTE",
6523 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6525 my $lead = $fixed[$fixlinenr] =~
6526 /(^\+\s*(?:static\s+))/;
6528 $lead = "$lead " if ($lead !~ /^\+$/);
6529 $lead = "${lead}const ";
6530 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6534 # check for __read_mostly with const non-pointer (should just be const)
6535 if ($line =~ /\b__read_mostly\b/ &&
6536 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6537 if (ERROR
("CONST_READ_MOSTLY",
6538 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6540 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6544 # don't use __constant_<foo> functions outside of include/uapi/
6545 if ($realfile !~ m@
^include
/uapi/@
&&
6546 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6547 my $constant_func = $1;
6548 my $func = $constant_func;
6549 $func =~ s/^__constant_//;
6550 if (WARN
("CONSTANT_CONVERSION",
6551 "$constant_func should be $func\n" . $herecurr) &&
6553 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6557 # prefer usleep_range over udelay
6558 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6560 # ignore udelay's < 10, however
6561 if (! ($delay < 10) ) {
6563 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6565 if ($delay > 2000) {
6567 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6571 # warn about unexpectedly long msleep's
6572 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6575 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6579 # check for comparisons of jiffies
6580 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6581 WARN
("JIFFIES_COMPARISON",
6582 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6585 # check for comparisons of get_jiffies_64()
6586 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6587 WARN
("JIFFIES_COMPARISON",
6588 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6591 # warn about #ifdefs in C files
6592 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6593 # print "#ifdef in C files should be avoided\n";
6594 # print "$herecurr";
6598 # warn about spacing in #ifdefs
6599 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6600 if (ERROR
("SPACING",
6601 "exactly one space required after that #$1\n" . $herecurr) &&
6603 $fixed[$fixlinenr] =~
6604 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6609 # check for spinlock_t definitions without a comment.
6610 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6611 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6613 if (!ctx_has_comment
($first_line, $linenr)) {
6614 CHK
("UNCOMMENTED_DEFINITION",
6615 "$1 definition without comment\n" . $herecurr);
6618 # check for memory barriers without a comment.
6625 my $barrier_stems = qr{
6633 my $all_barriers = qr{
6635 smp_
(?
:$barrier_stems)|
6636 virt_
(?
:$barrier_stems)
6639 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6640 if (!ctx_has_comment
($first_line, $linenr)) {
6641 WARN
("MEMORY_BARRIER",
6642 "memory barrier without comment\n" . $herecurr);
6646 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6648 if ($realfile !~ m@
^include
/asm-generic/@
&&
6649 $realfile !~ m@
/barrier\
.h
$@
&&
6650 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6651 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6652 WARN
("MEMORY_BARRIER",
6653 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6656 # check for waitqueue_active without a comment.
6657 if ($line =~ /\bwaitqueue_active\s*\(/) {
6658 if (!ctx_has_comment
($first_line, $linenr)) {
6659 WARN
("WAITQUEUE_ACTIVE",
6660 "waitqueue_active without comment\n" . $herecurr);
6664 # check for data_race without a comment.
6665 if ($line =~ /\bdata_race\s*\(/) {
6666 if (!ctx_has_comment
($first_line, $linenr)) {
6668 "data_race without comment\n" . $herecurr);
6672 # check of hardware specific defines
6673 if ($line =~ m@
^.\s
*\#\s
*if.*\b(__i386__
|__powerpc64__
|__sun__
|__s390x__
)\b@
&& $realfile !~ m
@include/asm
-@
) {
6675 "architecture specific defines should be avoided\n" . $herecurr);
6678 # check that the storage class is not after a type
6679 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6680 WARN
("STORAGE_CLASS",
6681 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6683 # Check that the storage class is at the beginning of a declaration
6684 if ($line =~ /\b$Storage\b/ &&
6685 $line !~ /^.\s*$Storage/ &&
6686 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6687 $1 !~ /[\,\)]\s*$/) {
6688 WARN
("STORAGE_CLASS",
6689 "storage class should be at the beginning of the declaration\n" . $herecurr);
6692 # check the location of the inline attribute, that it is between
6693 # storage class and type.
6694 if ($line =~ /\b$Type\s+$Inline\b/ ||
6695 $line =~ /\b$Inline\s+$Storage\b/) {
6696 ERROR
("INLINE_LOCATION",
6697 "inline keyword should sit between storage class and type\n" . $herecurr);
6700 # Check for __inline__ and __inline, prefer inline
6701 if ($realfile !~ m@
\binclude
/uapi/@
&&
6702 $line =~ /\b(__inline__|__inline)\b/) {
6704 "plain inline is preferred over $1\n" . $herecurr) &&
6706 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6711 # Check for compiler attributes
6712 if ($realfile !~ m@
\binclude
/uapi/@
&&
6713 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6715 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6718 "alias" => "__alias",
6719 "aligned" => "__aligned",
6720 "always_inline" => "__always_inline",
6721 "assume_aligned" => "__assume_aligned",
6723 "const" => "__attribute_const__",
6725 "designated_init" => "__designated_init",
6726 "externally_visible" => "__visible",
6727 "format" => "printf|scanf",
6728 "gnu_inline" => "__gnu_inline",
6729 "malloc" => "__malloc",
6731 "no_caller_saved_registers" => "__no_caller_saved_registers",
6732 "noclone" => "__noclone",
6733 "noinline" => "noinline",
6734 "nonstring" => "__nonstring",
6735 "noreturn" => "__noreturn",
6736 "packed" => "__packed",
6738 "section" => "__section",
6743 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6746 $params = $2 if defined($2);
6747 my $curr_attr = $orig_attr;
6748 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6749 if (exists($attr_list{$curr_attr})) {
6750 my $new = $attr_list{$curr_attr};
6751 if ($curr_attr eq "format" && $params) {
6752 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6755 $new = "$new$params";
6757 if (WARN
("PREFER_DEFINED_ATTRIBUTE_MACRO",
6758 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6760 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6761 $fixed[$fixlinenr] =~ s/$remove//;
6762 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6763 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6764 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6769 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6770 if ($attr =~ /^_*unused/) {
6771 WARN
("PREFER_DEFINED_ATTRIBUTE_MACRO",
6772 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6776 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6777 if ($perl_version_ok &&
6778 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6779 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6780 $line =~ /\b__weak\b/)) {
6781 ERROR
("WEAK_DECLARATION",
6782 "Using weak declarations can have unintended link defects\n" . $herecurr);
6785 # check for c99 types like uint8_t used outside of uapi/ and tools/
6786 if ($realfile !~ m@
\binclude
/uapi/@
&&
6787 $realfile !~ m@
\btools
/@
&&
6788 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6790 if ($type =~ /\b($typeC99Typedefs)\b/) {
6792 my $kernel_type = 'u';
6793 $kernel_type = 's' if ($type =~ /^_*[si]/);
6796 if (CHK
("PREFER_KERNEL_TYPES",
6797 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6799 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6804 # check for cast of C90 native int or longer types constants
6805 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6809 my $newconst = $const;
6810 $newconst =~ s/${Int_type}$//;
6811 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6812 if ($cast =~ /\blong\s+long\b/) {
6814 } elsif ($cast =~ /\blong\b/) {
6817 if (WARN
("TYPECAST_INT_CONSTANT",
6818 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6820 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6824 # check for sizeof(&)
6825 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6826 WARN
("SIZEOF_ADDRESS",
6827 "sizeof(& should be avoided\n" . $herecurr);
6830 # check for sizeof without parenthesis
6831 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6832 if (WARN
("SIZEOF_PARENTHESIS",
6833 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6835 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6839 # check for struct spinlock declarations
6840 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6841 WARN
("USE_SPINLOCK_T",
6842 "struct spinlock should be spinlock_t\n" . $herecurr);
6845 # check for seq_printf uses that could be seq_puts
6846 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6847 my $fmt = get_quoted_string
($line, $rawline);
6850 if (WARN
("PREFER_SEQ_PUTS",
6851 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6853 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6858 # check for vsprintf extension %p<foo> misuses
6859 if ($perl_version_ok &&
6861 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6862 $1 !~ /^_*volatile_*$/) {
6865 my $lc = $stat =~ tr@
\n@@
;
6866 $lc = $lc + $linenr;
6867 for (my $count = $linenr; $count <= $lc; $count++) {
6871 my $bad_specifier = "";
6872 my $fmt = get_quoted_string
($lines[$count - 1], raw_line
($count, 0));
6875 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6879 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6880 ($extension eq "f" &&
6881 defined $qualifier && $qualifier !~ /^w/) ||
6882 ($extension eq "4" &&
6883 defined $qualifier && $qualifier !~ /^cc/)) {
6884 $bad_specifier = $specifier;
6887 if ($extension eq "x" && !defined($stat_real)) {
6888 if (!defined($stat_real)) {
6889 $stat_real = get_stat_real
($linenr, $lc);
6891 WARN
("VSPRINTF_SPECIFIER_PX",
6892 "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");
6895 if ($bad_specifier ne "") {
6896 my $stat_real = get_stat_real
($linenr, $lc);
6897 my $ext_type = "Invalid";
6899 if ($bad_specifier =~ /p[Ff]/) {
6900 $use = " - use %pS instead";
6901 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6904 WARN
("VSPRINTF_POINTER_EXTENSION",
6905 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6910 # Check for misused memsets
6911 if ($perl_version_ok &&
6913 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6919 if ($ms_size =~ /^(0x|)0$/i) {
6921 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6922 } elsif ($ms_size =~ /^(0x|)1$/i) {
6924 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6928 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6929 # if ($perl_version_ok &&
6931 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6932 # if (WARN("PREFER_ETHER_ADDR_COPY",
6933 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6935 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6939 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6940 # if ($perl_version_ok &&
6942 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6943 # WARN("PREFER_ETHER_ADDR_EQUAL",
6944 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6947 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6948 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6949 # if ($perl_version_ok &&
6951 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6955 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6956 # if (WARN("PREFER_ETH_ZERO_ADDR",
6957 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6959 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6961 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6962 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6963 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6965 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6970 # typecasts on min/max could be min_t/max_t
6971 if ($perl_version_ok &&
6973 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6974 if (defined $2 || defined $7) {
6976 my $cast1 = deparenthesize
($2);
6978 my $cast2 = deparenthesize
($7);
6982 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6983 $cast = "$cast1 or $cast2";
6984 } elsif ($cast1 ne "") {
6990 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6994 # check usleep_range arguments
6995 if ($perl_version_ok &&
6997 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7001 WARN
("USLEEP_RANGE",
7002 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7003 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7005 WARN
("USLEEP_RANGE",
7006 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
7010 # check for naked sscanf
7011 if ($perl_version_ok &&
7013 $line =~ /\bsscanf\b/ &&
7014 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7015 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7016 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7017 my $lc = $stat =~ tr@
\n@@
;
7018 $lc = $lc + $linenr;
7019 my $stat_real = get_stat_real
($linenr, $lc);
7020 WARN
("NAKED_SSCANF",
7021 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7024 # check for simple sscanf that should be kstrto<foo>
7025 if ($perl_version_ok &&
7027 $line =~ /\bsscanf\b/) {
7028 my $lc = $stat =~ tr@
\n@@
;
7029 $lc = $lc + $linenr;
7030 my $stat_real = get_stat_real
($linenr, $lc);
7031 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7033 my $count = $format =~ tr@
%@
%@
;
7035 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7036 WARN
("SSCANF_TO_KSTRTO",
7037 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7042 # check for new externs in .h files.
7043 if ($realfile =~ /\.h$/ &&
7044 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7045 if (CHK
("AVOID_EXTERNS",
7046 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
7048 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7052 # check for new externs in .c files.
7053 if ($realfile =~ /\.c$/ && defined $stat &&
7054 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7056 my $function_name = $1;
7057 my $paren_space = $2;
7060 if (defined $cond) {
7061 substr($s, 0, length($cond), '');
7065 WARN
("AVOID_EXTERNS",
7066 "externs should be avoided in .c files\n" . $herecurr);
7069 if ($paren_space =~ /\n/) {
7070 WARN
("FUNCTION_ARGUMENTS",
7071 "arguments for function declarations should follow identifier\n" . $herecurr);
7074 } elsif ($realfile =~ /\.c$/ && defined $stat &&
7075 $stat =~ /^.\s*extern\s+/)
7077 WARN
("AVOID_EXTERNS",
7078 "externs should be avoided in .c files\n" . $herecurr);
7081 # check for function declarations that have arguments without identifier names
7082 if (defined $stat &&
7083 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7085 my $args = trim
($1);
7086 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7088 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7089 WARN
("FUNCTION_ARGUMENTS",
7090 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7095 # check for function definitions
7096 if ($perl_version_ok &&
7098 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7099 $context_function = $1;
7101 # check for multiline function definition with misplaced open brace
7103 my $cnt = statement_rawlines
($stat);
7104 my $herectx = $here . "\n";
7105 for (my $n = 0; $n < $cnt; $n++) {
7106 my $rl = raw_line
($linenr, $n);
7107 $herectx .= $rl . "\n";
7108 $ok = 1 if ($rl =~ /^[ \+]\{/);
7109 $ok = 1 if ($rl =~ /\{/ && $n == 0);
7110 last if $rl =~ /^[ \+].*\{/;
7114 "open brace '{' following function definitions go on the next line\n" . $herectx);
7118 # checks for new __setup's
7119 if ($rawline =~ /\b__setup\("([^"]*)"/) {
7122 if (!grep(/$name/, @setup_docs)) {
7123 CHK
("UNDOCUMENTED_SETUP",
7124 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7128 # check for pointless casting of alloc functions
7129 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7130 WARN
("UNNECESSARY_CASTS",
7131 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7135 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7136 if ($perl_version_ok &&
7137 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7138 CHK
("ALLOC_SIZEOF_STRUCT",
7139 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7142 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
7143 if ($perl_version_ok &&
7145 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7149 my $newfunc = "kmalloc_array";
7150 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7153 if ($a1 =~ /^sizeof\s*\S/) {
7157 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7158 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7159 my $cnt = statement_rawlines
($stat);
7160 my $herectx = get_stat_here
($linenr, $cnt, $here);
7162 if (WARN
("ALLOC_WITH_MULTIPLY",
7163 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7166 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
7171 # check for krealloc arg reuse
7172 if ($perl_version_ok &&
7173 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7175 WARN
("KREALLOC_ARG_REUSE",
7176 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7179 # check for alloc argument mismatch
7180 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) {
7181 WARN
("ALLOC_ARRAY_ARGS",
7182 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7185 # check for multiple semicolons
7186 if ($line =~ /;\s*;\s*$/) {
7187 if (WARN
("ONE_SEMICOLON",
7188 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7190 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7194 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7195 if ($realfile !~ m@
^include
/uapi/@
&&
7196 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7198 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7199 if (CHK
("BIT_MACRO",
7200 "Prefer using the BIT$ull macro\n" . $herecurr) &&
7202 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7206 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7207 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7208 WARN
("IS_ENABLED_CONFIG",
7209 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7212 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7213 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7215 if (WARN
("PREFER_IS_ENABLED",
7216 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7218 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7222 # check for /* fallthrough */ like comment, prefer fallthrough;
7223 my @fallthroughs = (
7226 'lint -fallthrough[ \t]*',
7227 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7228 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7229 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7230 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7232 if ($raw_comment ne '') {
7233 foreach my $ft (@fallthroughs) {
7234 if ($raw_comment =~ /$ft/) {
7235 my $msg_level = \
&WARN
;
7236 $msg_level = \
&CHK
if ($file);
7237 &{$msg_level}("PREFER_FALLTHROUGH",
7238 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7244 # check for switch/default statements without a break;
7245 if ($perl_version_ok &&
7247 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7248 my $cnt = statement_rawlines
($stat);
7249 my $herectx = get_stat_here
($linenr, $cnt, $here);
7251 WARN
("DEFAULT_NO_BREAK",
7252 "switch default: should use break\n" . $herectx);
7255 # check for gcc specific __FUNCTION__
7256 if ($line =~ /\b__FUNCTION__\b/) {
7257 if (WARN
("USE_FUNC",
7258 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
7260 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7264 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
7265 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7267 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7270 # check for use of yield()
7271 if ($line =~ /\byield\s*\(\s*\)/) {
7273 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
7276 # check for comparisons against true and false
7277 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7285 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7287 my $type = lc($otype);
7288 if ($type =~ /^(?:true|false)$/) {
7289 if (("$test" eq "==" && "$type" eq "true") ||
7290 ("$test" eq "!=" && "$type" eq "false")) {
7294 CHK
("BOOL_COMPARISON",
7295 "Using comparison to $otype is error prone\n" . $herecurr);
7297 ## maybe suggesting a correct construct would better
7298 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7303 # check for semaphores initialized locked
7304 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7305 WARN
("CONSIDER_COMPLETION",
7306 "consider using a completion\n" . $herecurr);
7309 # recommend kstrto* over simple_strto* and strict_strto*
7310 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7311 WARN
("CONSIDER_KSTRTO",
7312 "$1 is obsolete, use k$3 instead\n" . $herecurr);
7315 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
7316 if ($line =~ /^.\s*__initcall\s*\(/) {
7317 WARN
("USE_DEVICE_INITCALL",
7318 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7321 # check for spin_is_locked(), suggest lockdep instead
7322 if ($line =~ /\bspin_is_locked\(/) {
7324 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7327 # check for deprecated apis
7328 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7329 my $deprecated_api = $1;
7330 my $new_api = $deprecated_apis{$deprecated_api};
7331 WARN
("DEPRECATED_API",
7332 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7335 # check for various structs that are normally const (ops, kgdb, device_tree)
7336 # and avoid what seem like struct definitions 'struct foo {'
7337 if (defined($const_structs) &&
7338 $line !~ /\bconst\b/ &&
7339 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7340 WARN
("CONST_STRUCT",
7341 "struct $1 should normally be const\n" . $herecurr);
7344 # use of NR_CPUS is usually wrong
7345 # ignore definitions of NR_CPUS and usage to define arrays as likely right
7346 # ignore designated initializers using NR_CPUS
7347 if ($line =~ /\bNR_CPUS\b/ &&
7348 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7349 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7350 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7351 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7352 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7353 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7356 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7359 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7360 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7361 ERROR
("DEFINE_ARCH_HAS",
7362 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7365 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
7366 if ($perl_version_ok &&
7367 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7368 WARN
("LIKELY_MISUSE",
7369 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7372 # return sysfs_emit(foo, fmt, ...) fmt without newline
7373 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7374 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7375 my $offset = $+[6] - 1;
7376 if (WARN
("SYSFS_EMIT",
7377 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7379 substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7383 # nested likely/unlikely calls
7384 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7385 WARN
("LIKELY_MISUSE",
7386 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7389 # whine mightly about in_atomic
7390 if ($line =~ /\bin_atomic\s*\(/) {
7391 if ($realfile =~ m@
^drivers
/@
) {
7393 "do not use in_atomic in drivers\n" . $herecurr);
7394 } elsif ($realfile !~ m@
^kernel
/@
) {
7396 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7400 # check for lockdep_set_novalidate_class
7401 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7402 $line =~ /__lockdep_no_validate__\s*\)/ ) {
7403 if ($realfile !~ m@
^kernel
/lockdep@
&&
7404 $realfile !~ m@
^include
/linux/lockdep@
&&
7405 $realfile !~ m@
^drivers
/base/core@
) {
7407 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7411 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7412 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7413 WARN
("EXPORTED_WORLD_WRITABLE",
7414 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7417 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7418 # and whether or not function naming is typical and if
7419 # DEVICE_ATTR permissions uses are unusual too
7420 if ($perl_version_ok &&
7422 $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*\)/) {
7427 my $octal_perms = perms_to_octal
($perms);
7428 if ($show =~ /^${var}_show$/ &&
7429 $store =~ /^${var}_store$/ &&
7430 $octal_perms eq "0644") {
7431 if (WARN
("DEVICE_ATTR_RW",
7432 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7434 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7436 } elsif ($show =~ /^${var}_show$/ &&
7437 $store =~ /^NULL$/ &&
7438 $octal_perms eq "0444") {
7439 if (WARN
("DEVICE_ATTR_RO",
7440 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7442 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7444 } elsif ($show =~ /^NULL$/ &&
7445 $store =~ /^${var}_store$/ &&
7446 $octal_perms eq "0200") {
7447 if (WARN
("DEVICE_ATTR_WO",
7448 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7450 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7452 } elsif ($octal_perms eq "0644" ||
7453 $octal_perms eq "0444" ||
7454 $octal_perms eq "0200") {
7455 my $newshow = "$show";
7456 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7457 my $newstore = $store;
7458 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7460 if ($show ne $newshow) {
7461 $rename .= " '$show' to '$newshow'";
7463 if ($store ne $newstore) {
7464 $rename .= " '$store' to '$newstore'";
7466 WARN
("DEVICE_ATTR_FUNCTIONS",
7467 "Consider renaming function(s)$rename\n" . $herecurr);
7469 WARN
("DEVICE_ATTR_PERMS",
7470 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7474 # Mode permission misuses where it seems decimal should be octal
7475 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7476 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7477 # specific definition of not visible in sysfs.
7478 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7479 # use the default permissions
7480 if ($perl_version_ok &&
7482 $line =~ /$mode_perms_search/) {
7483 foreach my $entry (@mode_permission_funcs) {
7484 my $func = $entry->[0];
7485 my $arg_pos = $entry->[1];
7487 my $lc = $stat =~ tr@
\n@@
;
7488 $lc = $lc + $linenr;
7489 my $stat_real = get_stat_real
($linenr, $lc);
7494 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7496 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7497 if ($stat =~ /$test/) {
7499 $val = $6 if ($skip_args ne "");
7500 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7501 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7502 ($val =~ /^$Octal$/ && length($val) ne 4))) {
7503 ERROR
("NON_OCTAL_PERMISSIONS",
7504 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7506 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7507 ERROR
("EXPORTED_WORLD_WRITABLE",
7508 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7514 # check for uses of S_<PERMS> that could be octal for readability
7515 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7517 my $octal = perms_to_octal
($oval);
7518 if (WARN
("SYMBOLIC_PERMS",
7519 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7521 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7525 # validate content of MODULE_LICENSE against list from include/linux/module.h
7526 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7527 my $extracted_string = get_quoted_string
($line, $rawline);
7528 my $valid_licenses = qr{
7531 GPL\
and\ additional\ rights
|
7537 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7538 WARN
("MODULE_LICENSE",
7539 "unknown module license " . $extracted_string . "\n" . $herecurr);
7543 # check for sysctl duplicate constants
7544 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7545 WARN
("DUPLICATED_SYSCTL_CONST",
7546 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7550 # If we have no input at all, then there is nothing to report on
7551 # so just keep quiet.
7552 if ($#rawlines == -1) {
7556 # In mailback mode only produce a report in the negative, for
7557 # things that appear to be patches.
7558 if ($mailback && ($clean == 1 || !$is_patch)) {
7562 # This is not a patch, and we are in 'no-patch' mode so
7564 if (!$chk_patch && !$is_patch) {
7568 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7569 ERROR
("NOT_UNIFIED_DIFF",
7570 "Does not appear to be a unified-diff format patch\n");
7572 if ($is_patch && $has_commit_log && $chk_signoff) {
7573 if ($signoff == 0) {
7574 ERROR
("MISSING_SIGN_OFF",
7575 "Missing Signed-off-by: line(s)\n");
7576 } elsif ($authorsignoff != 1) {
7577 # authorsignoff values:
7578 # 0 -> missing sign off
7579 # 1 -> sign off identical
7580 # 2 -> names and addresses match, comments mismatch
7581 # 3 -> addresses match, names different
7582 # 4 -> names match, addresses different
7583 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7585 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7587 if ($authorsignoff == 0) {
7588 ERROR
("NO_AUTHOR_SIGN_OFF",
7589 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7590 } elsif ($authorsignoff == 2) {
7591 CHK
("FROM_SIGN_OFF_MISMATCH",
7592 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7593 } elsif ($authorsignoff == 3) {
7594 WARN
("FROM_SIGN_OFF_MISMATCH",
7595 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7596 } elsif ($authorsignoff == 4) {
7597 WARN
("FROM_SIGN_OFF_MISMATCH",
7598 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7599 } elsif ($authorsignoff == 5) {
7600 WARN
("FROM_SIGN_OFF_MISMATCH",
7601 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7606 print report_dump
();
7607 if ($summary && !($clean == 1 && $quiet == 1)) {
7608 print "$filename " if ($summary_file);
7609 print "total: $cnt_error errors, $cnt_warn warnings, " .
7610 (($check)?
"$cnt_chk checks, " : "") .
7611 "$cnt_lines lines checked\n";
7615 # If there were any defects found and not already fixing them
7616 if (!$clean and !$fix) {
7619 NOTE
: For some of the reported defects
, checkpatch may be able to
7620 mechanically convert to the typical style using
--fix
or --fix
-inplace
.
7623 # If there were whitespace errors which cleanpatch can fix
7624 # then suggest that.
7625 if ($rpt_cleaners) {
7629 NOTE
: Whitespace errors detected
.
7630 You may wish to
use scripts
/cleanpatch or scripts/cleanfile
7635 if ($clean == 0 && $fix &&
7636 ("@rawlines" ne "@fixed" ||
7637 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7638 my $newfile = $filename;
7639 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7643 @fixed = fix_inserted_deleted_lines
(\
@fixed, \
@fixed_inserted, \
@fixed_deleted);
7645 open($f, '>', $newfile)
7646 or die "$P: Can't open $newfile for write\n";
7647 foreach my $fixed_line (@fixed) {
7650 if ($linecount > 3) {
7651 $fixed_line =~ s/^\+//;
7652 print $f $fixed_line . "\n";
7655 print $f $fixed_line . "\n";
7663 Wrote EXPERIMENTAL
--fix correction
(s
) to
'$newfile'
7665 Do _NOT_ trust the results written to this file
.
7666 Do _NOT_ submit these changes without inspecting them
for correctness
.
7668 This EXPERIMENTAL file is simply a convenience to help rewrite patches
.
7669 No warranties
, expressed
or implied
...
7677 print "$vname has no obvious style problems and is ready for submission.\n";
7679 print "$vname has style problems, please review.\n";