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);
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 80;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile = "";
64 my $allow_c99_comments = 1;
70 Usage: $P [OPTION]... [FILE]...
75 --no-tree run without a kernel tree
76 --no-signoff do not check for 'Signed-off-by' line
77 --patch treat FILE as patchfile (default)
78 --emacs emacs compile window format
79 --terse one line per report
80 --showfile emit diffed file position, not input file position
81 -g, --git treat FILE as a single commit or git revision range
82 single git commit with:
86 multiple git commits with:
90 git merges are ignored
91 -f, --file treat FILE as regular source file
92 --subjective, --strict enable more subjective tests
93 --list-types list the possible message types
94 --types TYPE(,TYPE2...) show only these comma separated message types
95 --ignore TYPE(,TYPE2...) ignore various comma separated message types
96 --show-types show the specific message type in the output
97 --max-line-length=n set the maximum line length, if exceeded, warn
98 --min-conf-desc-length=n set the min description length, if shorter, warn
99 --root=PATH PATH to the kernel tree root
100 --no-summary suppress the per-file summary
101 --mailback only produce a report in case of warnings/errors
102 --summary-file include the filename in summary
103 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
104 'values', 'possible', 'type', and 'attr' (default
106 --test-only=WORD report only warnings/errors containing WORD
108 --fix EXPERIMENTAL - may create horrible results
109 If correctable single-line errors exist, create
110 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
111 with potential errors corrected to the preferred
113 --fix-inplace EXPERIMENTAL - may create horrible results
114 Is the same as --fix, but overwrites the input
115 file. It's your fault if there's no backup or git
116 --ignore-perl-version override checking of perl version. expect
118 --codespell Use the codespell dictionary for spelling/typos
119 (default:/usr/share/codespell/dictionary.txt)
120 --codespellfile Use this codespell dictionary
121 --typedefsfile Read additional types from this file
122 --color[=WHEN] Use colors 'always', 'never', or only when output
123 is a terminal ('auto'). Default is 'auto'.
124 -h, --help, --version display this help and exit
126 When FILE is - read standard input.
134 return grep { !$seen{$_}++ } @_;
144 open(my $script, '<', abs_path($P)) or
145 die "$P: Can't read '$P' $!\n";
147 my $text = <$script>;
151 # Also catch when type or level is passed through a variable
152 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
155 @types = sort(uniq(@types));
156 print("#\tMessage type\n\n");
157 foreach my $type (@types) {
158 print(++$count . "\t" . $type . "\n");
164 my $conf = which_conf($configuration_file);
167 open(my $conffile, '<', "$conf")
168 or warn "$P: Can't find a readable $configuration_file file $!\n";
170 while (<$conffile>) {
173 $line =~ s/\s*\n?$//g;
177 next if ($line =~ m/^\s*#/);
178 next if ($line =~ m/^\s*$/);
180 my @words = split(" ", $line);
181 foreach my $word (@words) {
182 last if ($word =~ m/^#/);
183 push (@conf_args, $word);
187 unshift(@ARGV, @conf_args) if @conf_args;
190 # Perl's Getopt::Long allows options to take optional arguments after a space.
191 # Prevent --color by itself from consuming other arguments
193 if ($_ eq "--color" || $_ eq "-color") {
194 $_ = "--color=$color";
199 'q|quiet+' => \$quiet,
201 'signoff!' => \$chk_signoff,
202 'patch!' => \$chk_patch,
205 'showfile!' => \$showfile,
208 'subjective!' => \$check,
209 'strict!' => \$check,
210 'ignore=s' => \@ignore,
212 'show-types!' => \$show_types,
213 'list-types!' => \$list_types,
214 'max-line-length=i' => \$max_line_length,
215 'min-conf-desc-length=i' => \$min_conf_desc_length,
217 'summary!' => \$summary,
218 'mailback!' => \$mailback,
219 'summary-file!' => \$summary_file,
221 'fix-inplace!' => \$fix_inplace,
222 'ignore-perl-version!' => \$ignore_perl_version,
223 'debug=s' => \%debug,
224 'test-only=s' => \$tst_only,
225 'codespell!' => \$codespell,
226 'codespellfile=s' => \$codespellfile,
227 'typedefsfile=s' => \$typedefsfile,
228 'color=s' => \$color,
229 'no-color' => \$color, #keep old behaviors of -nocolor
230 'nocolor' => \$color, #keep old behaviors of -nocolor
237 list_types(0) if ($list_types);
239 $fix = 1 if ($fix_inplace);
240 $check_orig = $check;
244 my $perl_version_ok = 1;
245 if ($^V && $^V lt $minimum_perl_version) {
246 $perl_version_ok = 0;
247 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
248 exit(1) if (!$ignore_perl_version);
251 #if no filenames are given, push '-' to read patch from stdin
256 if ($color =~ /^[01]$/) {
258 } elsif ($color =~ /^always$/i) {
260 } elsif ($color =~ /^never$/i) {
262 } elsif ($color =~ /^auto$/i) {
263 $color = (-t STDOUT);
265 die "Invalid color mode: $color\n";
268 sub hash_save_array_words {
269 my ($hashRef, $arrayRef) = @_;
271 my @array = split(/,/, join(',', @$arrayRef));
272 foreach my $word (@array) {
273 $word =~ s/\s*\n?$//g;
276 $word =~ tr/[a-z]/[A-Z]/;
278 next if ($word =~ m/^\s*#/);
279 next if ($word =~ m/^\s*$/);
285 sub hash_show_words {
286 my ($hashRef, $prefix) = @_;
288 if (keys %$hashRef) {
289 print "\nNOTE: $prefix message types:";
290 foreach my $word (sort keys %$hashRef) {
297 hash_save_array_words(\%ignore_type, \@ignore);
298 hash_save_array_words(\%use_type, \@use);
301 my $dbg_possible = 0;
304 for my $key (keys %debug) {
306 eval "\${dbg_$key} = '$debug{$key}';";
310 my $rpt_cleaners = 0;
319 if (!top_of_kernel_tree($root)) {
320 die "$P: $root: --root does not point at a valid tree\n";
323 if (top_of_kernel_tree('.')) {
325 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
326 top_of_kernel_tree($1)) {
331 if (!defined $root) {
332 print "Must be run from the top-level dir. of a kernel tree\n";
337 my $emitted_corrupt = 0;
340 [A-Za-z_][A-Za-z\d_]*
341 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
343 our $Storage = qr{extern|static|asmlinkage};
357 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
358 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
359 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
360 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
361 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
363 # Notes to $Attribute:
364 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
385 ____cacheline_aligned|
386 ____cacheline_aligned_in_smp|
387 ____cacheline_internodealigned_in_smp|
391 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
392 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
393 our $Lval = qr{$Ident(?:$Member)*};
395 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
396 our $Binary = qr{(?i)0b[01]+$Int_type?};
397 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
398 our $Int = qr{[0-9]+$Int_type?};
399 our $Octal = qr{0[0-7]+$Int_type?};
400 our $String = qr{"[X\t]*"};
401 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
402 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
403 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
404 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
405 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
406 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
407 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
408 our $Arithmetic = qr{\+|-|\*|\/|%};
412 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
415 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
419 our $NonptrTypeMisordered;
420 our $NonptrTypeWithAttr;
424 our $DeclareMisordered;
426 our $NON_ASCII_UTF8 = qr{
427 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
428 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
429 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
430 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
431 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
432 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
433 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
437 [\x09\x0A\x0D\x20-\x7E] # ASCII
441 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
442 our $typeOtherOSTypedefs = qr{(?x:
443 u_(?:char|short|int|long) | # bsd
444 u(?:nchar|short|int|long) # sysv
446 our $typeKernelTypedefs = qr{(?x:
447 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
450 our $typeTypedefs = qr{(?x:
452 $typeOtherOSTypedefs\b|
453 $typeKernelTypedefs\b
456 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
458 our $logFunctions = qr{(?x:
459 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
460 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
462 WARN(?:_RATELIMIT|_ONCE|)|
465 seq_vprintf|seq_printf|seq_puts
468 our $signature_tags = qr{(?xi:
479 our @typeListMisordered = (
480 qr{char\s+(?:un)?signed},
481 qr{int\s+(?:(?:un)?signed\s+)?short\s},
482 qr{int\s+short(?:\s+(?:un)?signed)},
483 qr{short\s+int(?:\s+(?:un)?signed)},
484 qr{(?:un)?signed\s+int\s+short},
485 qr{short\s+(?:un)?signed},
486 qr{long\s+int\s+(?:un)?signed},
487 qr{int\s+long\s+(?:un)?signed},
488 qr{long\s+(?:un)?signed\s+int},
489 qr{int\s+(?:un)?signed\s+long},
490 qr{int\s+(?:un)?signed},
491 qr{int\s+long\s+long\s+(?:un)?signed},
492 qr{long\s+long\s+int\s+(?:un)?signed},
493 qr{long\s+long\s+(?:un)?signed\s+int},
494 qr{long\s+long\s+(?:un)?signed},
495 qr{long\s+(?:un)?signed},
500 qr{(?:(?:un)?signed\s+)?char},
501 qr{(?:(?:un)?signed\s+)?short\s+int},
502 qr{(?:(?:un)?signed\s+)?short},
503 qr{(?:(?:un)?signed\s+)?int},
504 qr{(?:(?:un)?signed\s+)?long\s+int},
505 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
506 qr{(?:(?:un)?signed\s+)?long\s+long},
507 qr{(?:(?:un)?signed\s+)?long},
516 qr{${Ident}_handler},
517 qr{${Ident}_handler_fn},
521 our $C90_int_types = qr{(?x:
522 long\s+long\s+int\s+(?:un)?signed|
523 long\s+long\s+(?:un)?signed\s+int|
524 long\s+long\s+(?:un)?signed|
525 (?:(?:un)?signed\s+)?long\s+long\s+int|
526 (?:(?:un)?signed\s+)?long\s+long|
527 int\s+long\s+long\s+(?:un)?signed|
528 int\s+(?:(?:un)?signed\s+)?long\s+long|
530 long\s+int\s+(?:un)?signed|
531 long\s+(?:un)?signed\s+int|
532 long\s+(?:un)?signed|
533 (?:(?:un)?signed\s+)?long\s+int|
534 (?:(?:un)?signed\s+)?long|
535 int\s+long\s+(?:un)?signed|
536 int\s+(?:(?:un)?signed\s+)?long|
539 (?:(?:un)?signed\s+)?int
542 our @typeListFile = ();
543 our @typeListWithAttr = (
545 qr{struct\s+$InitAttribute\s+$Ident},
546 qr{union\s+$InitAttribute\s+$Ident},
549 our @modifierList = (
552 our @modifierListFile = ();
554 our @mode_permission_funcs = (
556 ["module_param_(?:array|named|string)", 4],
557 ["module_param_array_named", 5],
558 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
559 ["proc_create(?:_data|)", 2],
560 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
561 ["IIO_DEV_ATTR_[A-Z_]+", 1],
562 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
563 ["SENSOR_TEMPLATE(?:_2|)", 3],
567 #Create a search pattern for all these functions to speed up a loop below
568 our $mode_perms_search = "";
569 foreach my $entry (@mode_permission_funcs) {
570 $mode_perms_search .= '|' if ($mode_perms_search ne "");
571 $mode_perms_search .= $entry->[0];
573 $mode_perms_search = "(?:${mode_perms_search})";
575 our $mode_perms_world_writable = qr{
583 our %mode_permission_string_types = (
602 #Create a search pattern for all these strings to speed up a loop below
603 our $mode_perms_string_search = "";
604 foreach my $entry (keys %mode_permission_string_types) {
605 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
606 $mode_perms_string_search .= $entry;
608 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
609 our $multi_mode_perms_string_search = qr{
610 ${single_mode_perms_string_search}
611 (?:\s*\|\s*${single_mode_perms_string_search})*
617 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
624 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
625 $curpos = pos($string);
628 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
630 $to |= $mode_permission_string_types{$match};
631 $val .= '\s*\|\s*' if ($val ne "");
635 $oval =~ s/^\s*\|\s*//;
636 $oval =~ s/\s*\|\s*$//;
637 return sprintf("%04o", $to);
640 our $allowed_asm_includes = qr{(?x:
646 # memory.h: ARM has a custom one
648 # Load common spelling mistakes and build regular expression list.
652 if (open(my $spelling, '<', $spelling_file)) {
653 while (<$spelling>) {
656 $line =~ s/\s*\n?$//g;
659 next if ($line =~ m/^\s*#/);
660 next if ($line =~ m/^\s*$/);
662 my ($suspect, $fix) = split(/\|\|/, $line);
664 $spelling_fix{$suspect} = $fix;
668 warn "No typos will be found - file '$spelling_file': $!\n";
672 if (open(my $spelling, '<', $codespellfile)) {
673 while (<$spelling>) {
676 $line =~ s/\s*\n?$//g;
679 next if ($line =~ m/^\s*#/);
680 next if ($line =~ m/^\s*$/);
681 next if ($line =~ m/, disabled/i);
685 my ($suspect, $fix) = split(/->/, $line);
687 $spelling_fix{$suspect} = $fix;
691 warn "No codespell typos will be found - file '$codespellfile': $!\n";
695 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
698 my ($wordsRef, $file) = @_;
700 if (open(my $words, '<', $file)) {
704 $line =~ s/\s*\n?$//g;
707 next if ($line =~ m/^\s*#/);
708 next if ($line =~ m/^\s*$/);
710 print("$file: '$line' invalid - ignored\n");
714 $$wordsRef .= '|' if ($$wordsRef ne "");
724 my $const_structs = "";
725 read_words(\$const_structs, $conststructsfile)
726 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
728 my $typeOtherTypedefs = "";
729 if (length($typedefsfile)) {
730 read_words(\$typeOtherTypedefs, $typedefsfile)
731 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
733 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
736 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
737 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
738 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
739 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
740 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
746 (?:$Modifier\s+|const\s+)*
748 (?:typeof|__typeof__)\s*\([^\)]*\)|
752 (?:\s+$Modifier|\s+const)*
754 $NonptrTypeMisordered = qr{
755 (?:$Modifier\s+|const\s+)*
759 (?:\s+$Modifier|\s+const)*
761 $NonptrTypeWithAttr = qr{
762 (?:$Modifier\s+|const\s+)*
764 (?:typeof|__typeof__)\s*\([^\)]*\)|
768 (?:\s+$Modifier|\s+const)*
772 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
773 (?:\s+$Inline|\s+$Modifier)*
775 $TypeMisordered = qr{
776 $NonptrTypeMisordered
777 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
778 (?:\s+$Inline|\s+$Modifier)*
780 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
781 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
785 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
787 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
788 # requires at least perl version v5.10.0
789 # Any use must be runtime checked with $^V
791 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
792 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
793 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
795 our $declaration_macros = qr{(?x:
796 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
797 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
798 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
799 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
804 return "" if (!defined($string));
806 while ($string =~ /^\s*\(.*\)\s*$/) {
807 $string =~ s@^\s*\(\s*@@;
808 $string =~ s@\s*\)\s*$@@;
811 $string =~ s@\s+@ @g;
816 sub seed_camelcase_file {
819 return if (!(-f $file));
823 open(my $include_file, '<', "$file")
824 or warn "$P: Can't read '$file' $!\n";
825 my $text = <$include_file>;
826 close($include_file);
828 my @lines = split('\n', $text);
830 foreach my $line (@lines) {
831 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
832 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
834 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
836 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
842 sub is_maintained_obsolete {
845 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
847 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
849 return $status =~ /obsolete/i;
852 sub is_SPDX_License_valid {
855 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py"));
857 my $status = `echo "$license" | python $root/scripts/spdxcheck.py -`;
858 return 0 if ($status ne "");
862 my $camelcase_seeded = 0;
863 sub seed_camelcase_includes {
864 return if ($camelcase_seeded);
867 my $camelcase_cache = "";
868 my @include_files = ();
870 $camelcase_seeded = 1;
873 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
874 chomp $git_last_include_commit;
875 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
877 my $last_mod_date = 0;
878 $files = `find $root/include -name "*.h"`;
879 @include_files = split('\n', $files);
880 foreach my $file (@include_files) {
881 my $date = POSIX::strftime("%Y%m%d%H%M",
882 localtime((stat $file)[9]));
883 $last_mod_date = $date if ($last_mod_date < $date);
885 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
888 if ($camelcase_cache ne "" && -f $camelcase_cache) {
889 open(my $camelcase_file, '<', "$camelcase_cache")
890 or warn "$P: Can't read '$camelcase_cache' $!\n";
891 while (<$camelcase_file>) {
895 close($camelcase_file);
901 $files = `git ls-files "include/*.h"`;
902 @include_files = split('\n', $files);
905 foreach my $file (@include_files) {
906 seed_camelcase_file($file);
909 if ($camelcase_cache ne "") {
910 unlink glob ".checkpatch-camelcase.*";
911 open(my $camelcase_file, '>', "$camelcase_cache")
912 or warn "$P: Can't write '$camelcase_cache' $!\n";
913 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
914 print $camelcase_file ("$_\n");
916 close($camelcase_file);
920 sub git_commit_info {
921 my ($commit, $id, $desc) = @_;
923 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
925 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
926 $output =~ s/^\s*//gm;
927 my @lines = split("\n", $output);
929 return ($id, $desc) if ($#lines < 0);
931 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
932 # Maybe one day convert this block of bash into something that returns
933 # all matching commit ids, but it's very slow...
935 # echo "checking commits $1..."
936 # git rev-list --remotes | grep -i "^$1" |
937 # while read line ; do
938 # git log --format='%H %s' -1 $line |
939 # echo "commit $(cut -c 1-12,41-)"
941 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
944 $id = substr($lines[0], 0, 12);
945 $desc = substr($lines[0], 41);
951 $chk_signoff = 0 if ($file);
956 my @fixed_inserted = ();
957 my @fixed_deleted = ();
960 # If input is git commits, extract all commits from the commit expressions.
961 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
962 die "$P: No git repository found\n" if ($git && !-e ".git");
966 foreach my $commit_expr (@ARGV) {
968 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
969 $git_range = "-$2 $1";
970 } elsif ($commit_expr =~ m/\.\./) {
971 $git_range = "$commit_expr";
973 $git_range = "-1 $commit_expr";
975 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
976 foreach my $line (split(/\n/, $lines)) {
977 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
978 next if (!defined($1) || !defined($2));
981 unshift(@commits, $sha1);
982 $git_commits{$sha1} = $subject;
985 die "$P: no git commits after extraction!\n" if (@commits == 0);
990 for my $filename (@ARGV) {
993 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
994 die "$P: $filename: git format-patch failed - $!\n";
996 open($FILE, '-|', "diff -u /dev/null $filename") ||
997 die "$P: $filename: diff failed - $!\n";
998 } elsif ($filename eq '-') {
999 open($FILE, '<&STDIN');
1001 open($FILE, '<', "$filename") ||
1002 die "$P: $filename: open failed - $!\n";
1004 if ($filename eq '-') {
1005 $vname = 'Your patch';
1007 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1013 push(@rawlines, $_);
1017 if ($#ARGV > 0 && $quiet == 0) {
1018 print '-' x length($vname) . "\n";
1020 print '-' x length($vname) . "\n";
1023 if (!process($filename)) {
1029 @fixed_inserted = ();
1030 @fixed_deleted = ();
1032 @modifierListFile = ();
1038 hash_show_words(\%use_type, "Used");
1039 hash_show_words(\%ignore_type, "Ignored");
1041 if (!$perl_version_ok) {
1044 NOTE: perl $^V is not modern enough to detect all possible issues.
1045 An upgrade to at least perl $minimum_perl_version is suggested.
1051 NOTE: If any of the errors are false positives, please report
1052 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1059 sub top_of_kernel_tree {
1063 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1064 "README", "Documentation", "arch", "include", "drivers",
1065 "fs", "init", "ipc", "kernel", "lib", "scripts",
1068 foreach my $check (@tree_check) {
1069 if (! -e $root . '/' . $check) {
1077 my ($formatted_email) = @_;
1083 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1086 $comment = $3 if defined $3;
1087 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1089 $comment = $2 if defined $2;
1090 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1092 $comment = $2 if defined $2;
1093 $formatted_email =~ s/\Q$address\E.*$//;
1094 $name = $formatted_email;
1095 $name = trim($name);
1096 $name =~ s/^\"|\"$//g;
1097 # If there's a name left after stripping spaces and
1098 # leading quotes, and the address doesn't have both
1099 # leading and trailing angle brackets, the address
1101 # "joe smith joe@smith.com" bad
1102 # "joe smith <joe@smith.com" bad
1103 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1110 $name = trim($name);
1111 $name =~ s/^\"|\"$//g;
1112 $address = trim($address);
1113 $address =~ s/^\<|\>$//g;
1115 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1116 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1117 $name = "\"$name\"";
1120 return ($name, $address, $comment);
1124 my ($name, $address) = @_;
1126 my $formatted_email;
1128 $name = trim($name);
1129 $name =~ s/^\"|\"$//g;
1130 $address = trim($address);
1132 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1133 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1134 $name = "\"$name\"";
1137 if ("$name" eq "") {
1138 $formatted_email = "$address";
1140 $formatted_email = "$name <$address>";
1143 return $formatted_email;
1149 foreach my $path (split(/:/, $ENV{PATH})) {
1150 if (-e "$path/$bin") {
1151 return "$path/$bin";
1161 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1162 if (-e "$path/$conf") {
1163 return "$path/$conf";
1175 for my $c (split(//, $str)) {
1179 for (; ($n % 8) != 0; $n++) {
1191 (my $res = shift) =~ tr/\t/ /c;
1198 # Drop the diff line leader and expand tabs
1200 $line = expand_tabs($line);
1202 # Pick the indent from the front of the line.
1203 my ($white) = ($line =~ /^(\s*)/);
1205 return (length($line), length($white));
1208 my $sanitise_quote = '';
1210 sub sanitise_line_reset {
1211 my ($in_comment) = @_;
1214 $sanitise_quote = '*/';
1216 $sanitise_quote = '';
1229 # Always copy over the diff marker.
1230 $res = substr($line, 0, 1);
1232 for ($off = 1; $off < length($line); $off++) {
1233 $c = substr($line, $off, 1);
1235 # Comments we are whacking completely including the begin
1236 # and end, all to $;.
1237 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1238 $sanitise_quote = '*/';
1240 substr($res, $off, 2, "$;$;");
1244 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1245 $sanitise_quote = '';
1246 substr($res, $off, 2, "$;$;");
1250 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1251 $sanitise_quote = '//';
1253 substr($res, $off, 2, $sanitise_quote);
1258 # A \ in a string means ignore the next character.
1259 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1261 substr($res, $off, 2, 'XX');
1266 if ($c eq "'" || $c eq '"') {
1267 if ($sanitise_quote eq '') {
1268 $sanitise_quote = $c;
1270 substr($res, $off, 1, $c);
1272 } elsif ($sanitise_quote eq $c) {
1273 $sanitise_quote = '';
1277 #print "c<$c> SQ<$sanitise_quote>\n";
1278 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1279 substr($res, $off, 1, $;);
1280 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1281 substr($res, $off, 1, $;);
1282 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1283 substr($res, $off, 1, 'X');
1285 substr($res, $off, 1, $c);
1289 if ($sanitise_quote eq '//') {
1290 $sanitise_quote = '';
1293 # The pathname on a #include may be surrounded by '<' and '>'.
1294 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1295 my $clean = 'X' x length($1);
1296 $res =~ s@\<.*\>@<$clean>@;
1298 # The whole of a #error is a string.
1299 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1300 my $clean = 'X' x length($1);
1301 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1304 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1306 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1312 sub get_quoted_string {
1313 my ($line, $rawline) = @_;
1315 return "" if (!defined($line) || !defined($rawline));
1316 return "" if ($line !~ m/($String)/g);
1317 return substr($rawline, $-[0], $+[0] - $-[0]);
1320 sub ctx_statement_block {
1321 my ($linenr, $remain, $off) = @_;
1322 my $line = $linenr - 1;
1325 my $coff = $off - 1;
1339 @stack = (['', 0]) if ($#stack == -1);
1341 #warn "CSB: blk<$blk> remain<$remain>\n";
1342 # If we are about to drop off the end, pull in more
1345 for (; $remain > 0; $line++) {
1346 last if (!defined $lines[$line]);
1347 next if ($lines[$line] =~ /^-/);
1350 $blk .= $lines[$line] . "\n";
1351 $len = length($blk);
1355 # Bail if there is no further context.
1356 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1360 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1366 $c = substr($blk, $off, 1);
1367 $remainder = substr($blk, $off);
1369 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1371 # Handle nested #if/#else.
1372 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1373 push(@stack, [ $type, $level ]);
1374 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1375 ($type, $level) = @{$stack[$#stack - 1]};
1376 } elsif ($remainder =~ /^#\s*endif\b/) {
1377 ($type, $level) = @{pop(@stack)};
1380 # Statement ends at the ';' or a close '}' at the
1382 if ($level == 0 && $c eq ';') {
1386 # An else is really a conditional as long as its not else if
1387 if ($level == 0 && $coff_set == 0 &&
1388 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1389 $remainder =~ /^(else)(?:\s|{)/ &&
1390 $remainder !~ /^else\s+if\b/) {
1391 $coff = $off + length($1) - 1;
1393 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1394 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1397 if (($type eq '' || $type eq '(') && $c eq '(') {
1401 if ($type eq '(' && $c eq ')') {
1403 $type = ($level != 0)? '(' : '';
1405 if ($level == 0 && $coff < $soff) {
1408 #warn "CSB: mark coff<$coff>\n";
1411 if (($type eq '' || $type eq '{') && $c eq '{') {
1415 if ($type eq '{' && $c eq '}') {
1417 $type = ($level != 0)? '{' : '';
1420 if (substr($blk, $off + 1, 1) eq ';') {
1426 # Preprocessor commands end at the newline unless escaped.
1427 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1435 # We are truly at the end, so shuffle to the next line.
1442 my $statement = substr($blk, $soff, $off - $soff + 1);
1443 my $condition = substr($blk, $soff, $coff - $soff + 1);
1445 #warn "STATEMENT<$statement>\n";
1446 #warn "CONDITION<$condition>\n";
1448 #print "coff<$coff> soff<$off> loff<$loff>\n";
1450 return ($statement, $condition,
1451 $line, $remain + 1, $off - $loff + 1, $level);
1454 sub statement_lines {
1457 # Strip the diff line prefixes and rip blank lines at start and end.
1458 $stmt =~ s/(^|\n)./$1/g;
1462 my @stmt_lines = ($stmt =~ /\n/g);
1464 return $#stmt_lines + 2;
1467 sub statement_rawlines {
1470 my @stmt_lines = ($stmt =~ /\n/g);
1472 return $#stmt_lines + 2;
1475 sub statement_block_size {
1478 $stmt =~ s/(^|\n)./$1/g;
1484 my @stmt_lines = ($stmt =~ /\n/g);
1485 my @stmt_statements = ($stmt =~ /;/g);
1487 my $stmt_lines = $#stmt_lines + 2;
1488 my $stmt_statements = $#stmt_statements + 1;
1490 if ($stmt_lines > $stmt_statements) {
1493 return $stmt_statements;
1497 sub ctx_statement_full {
1498 my ($linenr, $remain, $off) = @_;
1499 my ($statement, $condition, $level);
1503 # Grab the first conditional/block pair.
1504 ($statement, $condition, $linenr, $remain, $off, $level) =
1505 ctx_statement_block($linenr, $remain, $off);
1506 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1507 push(@chunks, [ $condition, $statement ]);
1508 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1509 return ($level, $linenr, @chunks);
1512 # Pull in the following conditional/block pairs and see if they
1513 # could continue the statement.
1515 ($statement, $condition, $linenr, $remain, $off, $level) =
1516 ctx_statement_block($linenr, $remain, $off);
1517 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1518 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1520 push(@chunks, [ $condition, $statement ]);
1523 return ($level, $linenr, @chunks);
1527 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1529 my $start = $linenr - 1;
1536 my @stack = ($level);
1537 for ($line = $start; $remain > 0; $line++) {
1538 next if ($rawlines[$line] =~ /^-/);
1541 $blk .= $rawlines[$line];
1543 # Handle nested #if/#else.
1544 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1545 push(@stack, $level);
1546 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1547 $level = $stack[$#stack - 1];
1548 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1549 $level = pop(@stack);
1552 foreach my $c (split(//, $lines[$line])) {
1553 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1559 if ($c eq $close && $level > 0) {
1561 last if ($level == 0);
1562 } elsif ($c eq $open) {
1567 if (!$outer || $level <= 1) {
1568 push(@res, $rawlines[$line]);
1571 last if ($level == 0);
1574 return ($level, @res);
1576 sub ctx_block_outer {
1577 my ($linenr, $remain) = @_;
1579 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1583 my ($linenr, $remain) = @_;
1585 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1589 my ($linenr, $remain, $off) = @_;
1591 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1594 sub ctx_block_level {
1595 my ($linenr, $remain) = @_;
1597 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1599 sub ctx_statement_level {
1600 my ($linenr, $remain, $off) = @_;
1602 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1605 sub ctx_locate_comment {
1606 my ($first_line, $end_line) = @_;
1608 # Catch a comment on the end of the line itself.
1609 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1610 return $current_comment if (defined $current_comment);
1612 # Look through the context and try and figure out if there is a
1615 $current_comment = '';
1616 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1617 my $line = $rawlines[$linenr - 1];
1619 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1622 if ($line =~ m@/\*@) {
1625 if (!$in_comment && $current_comment ne '') {
1626 $current_comment = '';
1628 $current_comment .= $line . "\n" if ($in_comment);
1629 if ($line =~ m@\*/@) {
1634 chomp($current_comment);
1635 return($current_comment);
1637 sub ctx_has_comment {
1638 my ($first_line, $end_line) = @_;
1639 my $cmt = ctx_locate_comment($first_line, $end_line);
1641 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1642 ##print "CMMT: $cmt\n";
1644 return ($cmt ne '');
1648 my ($linenr, $cnt) = @_;
1650 my $offset = $linenr - 1;
1655 $line = $rawlines[$offset++];
1656 next if (defined($line) && $line =~ /^-/);
1664 my ($linenr, $lc) = @_;
1666 my $stat_real = raw_line($linenr, 0);
1667 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1668 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1675 my ($linenr, $cnt, $here) = @_;
1677 my $herectx = $here . "\n";
1678 for (my $n = 0; $n < $cnt; $n++) {
1679 $herectx .= raw_line($linenr, $n) . "\n";
1690 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1693 $coded = sprintf("^%c", unpack('C', $2) + 64);
1702 my $av_preprocessor = 0;
1707 sub annotate_reset {
1708 $av_preprocessor = 0;
1710 @av_paren_type = ('E');
1711 $av_pend_colon = 'O';
1714 sub annotate_values {
1715 my ($stream, $type) = @_;
1718 my $var = '_' x length($stream);
1721 print "$stream\n" if ($dbg_values > 1);
1723 while (length($cur)) {
1724 @av_paren_type = ('E') if ($#av_paren_type < 0);
1725 print " <" . join('', @av_paren_type) .
1726 "> <$type> <$av_pending>" if ($dbg_values > 1);
1727 if ($cur =~ /^(\s+)/o) {
1728 print "WS($1)\n" if ($dbg_values > 1);
1729 if ($1 =~ /\n/ && $av_preprocessor) {
1730 $type = pop(@av_paren_type);
1731 $av_preprocessor = 0;
1734 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1735 print "CAST($1)\n" if ($dbg_values > 1);
1736 push(@av_paren_type, $type);
1739 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1740 print "DECLARE($1)\n" if ($dbg_values > 1);
1743 } elsif ($cur =~ /^($Modifier)\s*/) {
1744 print "MODIFIER($1)\n" if ($dbg_values > 1);
1747 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1748 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1749 $av_preprocessor = 1;
1750 push(@av_paren_type, $type);
1756 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1757 print "UNDEF($1)\n" if ($dbg_values > 1);
1758 $av_preprocessor = 1;
1759 push(@av_paren_type, $type);
1761 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1762 print "PRE_START($1)\n" if ($dbg_values > 1);
1763 $av_preprocessor = 1;
1765 push(@av_paren_type, $type);
1766 push(@av_paren_type, $type);
1769 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1770 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1771 $av_preprocessor = 1;
1773 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1777 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1778 print "PRE_END($1)\n" if ($dbg_values > 1);
1780 $av_preprocessor = 1;
1782 # Assume all arms of the conditional end as this
1783 # one does, and continue as if the #endif was not here.
1784 pop(@av_paren_type);
1785 push(@av_paren_type, $type);
1788 } elsif ($cur =~ /^(\\\n)/o) {
1789 print "PRECONT($1)\n" if ($dbg_values > 1);
1791 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1792 print "ATTR($1)\n" if ($dbg_values > 1);
1793 $av_pending = $type;
1796 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1797 print "SIZEOF($1)\n" if ($dbg_values > 1);
1803 } elsif ($cur =~ /^(if|while|for)\b/o) {
1804 print "COND($1)\n" if ($dbg_values > 1);
1808 } elsif ($cur =~/^(case)/o) {
1809 print "CASE($1)\n" if ($dbg_values > 1);
1810 $av_pend_colon = 'C';
1813 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1814 print "KEYWORD($1)\n" if ($dbg_values > 1);
1817 } elsif ($cur =~ /^(\()/o) {
1818 print "PAREN('$1')\n" if ($dbg_values > 1);
1819 push(@av_paren_type, $av_pending);
1823 } elsif ($cur =~ /^(\))/o) {
1824 my $new_type = pop(@av_paren_type);
1825 if ($new_type ne '_') {
1827 print "PAREN('$1') -> $type\n"
1828 if ($dbg_values > 1);
1830 print "PAREN('$1')\n" if ($dbg_values > 1);
1833 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1834 print "FUNC($1)\n" if ($dbg_values > 1);
1838 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1839 if (defined $2 && $type eq 'C' || $type eq 'T') {
1840 $av_pend_colon = 'B';
1841 } elsif ($type eq 'E') {
1842 $av_pend_colon = 'L';
1844 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1847 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1848 print "IDENT($1)\n" if ($dbg_values > 1);
1851 } elsif ($cur =~ /^($Assignment)/o) {
1852 print "ASSIGN($1)\n" if ($dbg_values > 1);
1855 } elsif ($cur =~/^(;|{|})/) {
1856 print "END($1)\n" if ($dbg_values > 1);
1858 $av_pend_colon = 'O';
1860 } elsif ($cur =~/^(,)/) {
1861 print "COMMA($1)\n" if ($dbg_values > 1);
1864 } elsif ($cur =~ /^(\?)/o) {
1865 print "QUESTION($1)\n" if ($dbg_values > 1);
1868 } elsif ($cur =~ /^(:)/o) {
1869 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1871 substr($var, length($res), 1, $av_pend_colon);
1872 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1877 $av_pend_colon = 'O';
1879 } elsif ($cur =~ /^(\[)/o) {
1880 print "CLOSE($1)\n" if ($dbg_values > 1);
1883 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1886 print "OPV($1)\n" if ($dbg_values > 1);
1893 substr($var, length($res), 1, $variant);
1896 } elsif ($cur =~ /^($Operators)/o) {
1897 print "OP($1)\n" if ($dbg_values > 1);
1898 if ($1 ne '++' && $1 ne '--') {
1902 } elsif ($cur =~ /(^.)/o) {
1903 print "C($1)\n" if ($dbg_values > 1);
1906 $cur = substr($cur, length($1));
1907 $res .= $type x length($1);
1911 return ($res, $var);
1915 my ($possible, $line) = @_;
1916 my $notPermitted = qr{(?:
1933 ^(?:typedef|struct|enum)\b
1935 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1936 if ($possible !~ $notPermitted) {
1937 # Check for modifiers.
1938 $possible =~ s/\s*$Storage\s*//g;
1939 $possible =~ s/\s*$Sparse\s*//g;
1940 if ($possible =~ /^\s*$/) {
1942 } elsif ($possible =~ /\s/) {
1943 $possible =~ s/\s*$Type\s*//g;
1944 for my $modifier (split(' ', $possible)) {
1945 if ($modifier !~ $notPermitted) {
1946 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1947 push(@modifierListFile, $modifier);
1952 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1953 push(@typeListFile, $possible);
1957 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1966 $type =~ tr/[a-z]/[A-Z]/;
1968 return defined $use_type{$type} if (scalar keys %use_type > 0);
1970 return !defined $ignore_type{$type};
1974 my ($level, $type, $msg) = @_;
1976 if (!show_type($type) ||
1977 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1982 if ($level eq 'ERROR') {
1984 } elsif ($level eq 'WARNING') {
1990 $output .= $prefix . $level . ':';
1992 $output .= BLUE if ($color);
1993 $output .= "$type:";
1995 $output .= RESET if ($color);
1996 $output .= ' ' . $msg . "\n";
1999 my @lines = split("\n", $output, -1);
2000 splice(@lines, 1, 1);
2001 $output = join("\n", @lines);
2003 $output = (split('\n', $output))[0] . "\n" if ($terse);
2005 push(our @report, $output);
2014 sub fixup_current_range {
2015 my ($lineRef, $offset, $length) = @_;
2017 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2020 my $no = $o + $offset;
2021 my $nl = $l + $length;
2022 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2026 sub fix_inserted_deleted_lines {
2027 my ($linesRef, $insertedRef, $deletedRef) = @_;
2029 my $range_last_linenr = 0;
2030 my $delta_offset = 0;
2035 my $next_insert = 0;
2036 my $next_delete = 0;
2040 my $inserted = @{$insertedRef}[$next_insert++];
2041 my $deleted = @{$deletedRef}[$next_delete++];
2043 foreach my $old_line (@{$linesRef}) {
2045 my $line = $old_line; #don't modify the array
2046 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2048 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2049 $range_last_linenr = $new_linenr;
2050 fixup_current_range(\$line, $delta_offset, 0);
2053 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2054 $deleted = @{$deletedRef}[$next_delete++];
2056 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2059 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2060 push(@lines, ${$inserted}{'LINE'});
2061 $inserted = @{$insertedRef}[$next_insert++];
2063 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2067 push(@lines, $line);
2077 sub fix_insert_line {
2078 my ($linenr, $line) = @_;
2084 push(@fixed_inserted, $inserted);
2087 sub fix_delete_line {
2088 my ($linenr, $line) = @_;
2095 push(@fixed_deleted, $deleted);
2099 my ($type, $msg) = @_;
2101 if (report("ERROR", $type, $msg)) {
2109 my ($type, $msg) = @_;
2111 if (report("WARNING", $type, $msg)) {
2119 my ($type, $msg) = @_;
2121 if ($check && report("CHECK", $type, $msg)) {
2129 sub check_absolute_file {
2130 my ($absolute, $herecurr) = @_;
2131 my $file = $absolute;
2133 ##print "absolute<$absolute>\n";
2135 # See if any suffix of this path is a path within the tree.
2136 while ($file =~ s@^[^/]*/@@) {
2137 if (-f "$root/$file") {
2138 ##print "file<$file>\n";
2146 # It is, so see if the prefix is acceptable.
2147 my $prefix = $absolute;
2148 substr($prefix, -length($file)) = '';
2150 ##print "prefix<$prefix>\n";
2151 if ($prefix ne ".../") {
2152 WARN("USE_RELATIVE_PATH",
2153 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2160 $string =~ s/^\s+|\s+$//g;
2168 $string =~ s/^\s+//;
2176 $string =~ s/\s+$//;
2181 sub string_find_replace {
2182 my ($string, $find, $replace) = @_;
2184 $string =~ s/$find/$replace/g;
2192 my $source_indent = 8;
2193 my $max_spaces_before_tab = $source_indent - 1;
2194 my $spaces_to_tab = " " x $source_indent;
2196 #convert leading spaces to tabs
2197 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2198 #Remove spaces before a tab
2199 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2204 sub pos_last_openparen {
2209 my $opens = $line =~ tr/\(/\(/;
2210 my $closes = $line =~ tr/\)/\)/;
2212 my $last_openparen = 0;
2214 if (($opens == 0) || ($closes >= $opens)) {
2218 my $len = length($line);
2220 for ($pos = 0; $pos < $len; $pos++) {
2221 my $string = substr($line, $pos);
2222 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2223 $pos += length($1) - 1;
2224 } elsif (substr($line, $pos, 1) eq '(') {
2225 $last_openparen = $pos;
2226 } elsif (index($string, '(') == -1) {
2231 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2235 my $filename = shift;
2241 my $stashrawline="";
2251 my $authorsignoff = 0;
2253 my $in_header_lines = $file ? 0 : 1;
2254 my $in_commit_log = 0; #Scanning lines before patch
2255 my $has_commit_log = 0; #Encountered lines before patch
2256 my $commit_log_possible_stack_dump = 0;
2257 my $commit_log_long_line = 0;
2258 my $commit_log_has_diff = 0;
2259 my $reported_maintainer_file = 0;
2260 my $non_utf8_charset = 0;
2262 my $last_blank_line = 0;
2263 my $last_coalesced_string_linenr = -1;
2271 # Trace the real file/line as we go.
2276 my $context_function; #undef'd unless there's a known function
2278 my $comment_edge = 0;
2282 my $prev_values = 'E';
2285 my %suppress_ifbraces;
2286 my %suppress_whiletrailers;
2287 my %suppress_export;
2288 my $suppress_statement = 0;
2290 my %signatures = ();
2292 # Pre-scan the patch sanitizing the lines.
2293 # Pre-scan the patch looking for any __setup documentation.
2295 my @setup_docs = ();
2298 my $camelcase_file_seeded = 0;
2300 my $checklicenseline = 1;
2302 sanitise_line_reset();
2304 foreach my $rawline (@rawlines) {
2308 push(@fixed, $rawline) if ($fix);
2310 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2312 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2317 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2326 # Guestimate if this is a continuing comment. Run
2327 # the context looking for a comment "edge". If this
2328 # edge is a close comment then we must be in a comment
2332 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2333 next if (defined $rawlines[$ln - 1] &&
2334 $rawlines[$ln - 1] =~ /^-/);
2336 #print "RAW<$rawlines[$ln - 1]>\n";
2337 last if (!defined $rawlines[$ln - 1]);
2338 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2339 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2344 if (defined $edge && $edge eq '*/') {
2348 # Guestimate if this is a continuing comment. If this
2349 # is the start of a diff block and this line starts
2350 # ' *' then it is very likely a comment.
2351 if (!defined $edge &&
2352 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2357 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2358 sanitise_line_reset($in_comment);
2360 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2361 # Standardise the strings and chars within the input to
2362 # simplify matching -- only bother with positive lines.
2363 $line = sanitise_line($rawline);
2365 push(@lines, $line);
2368 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2373 #print "==>$rawline\n";
2374 #print "-->$line\n";
2376 if ($setup_docs && $line =~ /^\+/) {
2377 push(@setup_docs, $line);
2386 foreach my $line (@lines) {
2389 my $sline = $line; #copy of $line
2390 $sline =~ s/$;/ /g; #with comments as spaces
2392 my $rawline = $rawlines[$linenr - 1];
2394 # check if it's a mode change, rename or start of a patch
2395 if (!$in_commit_log &&
2396 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2397 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2398 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2402 #extract the line range in the file after the patch is applied
2403 if (!$in_commit_log &&
2404 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2407 $first_line = $linenr + 1;
2417 %suppress_ifbraces = ();
2418 %suppress_whiletrailers = ();
2419 %suppress_export = ();
2420 $suppress_statement = 0;
2421 if ($context =~ /\b(\w+)\s*\(/) {
2422 $context_function = $1;
2424 undef $context_function;
2428 # track the line number as we move through the hunk, note that
2429 # new versions of GNU diff omit the leading space on completely
2430 # blank context lines so we need to count that too.
2431 } elsif ($line =~ /^( |\+|$)/) {
2433 $realcnt-- if ($realcnt != 0);
2435 # Measure the line length and indent.
2436 ($length, $indent) = line_stats($rawline);
2438 # Track the previous line.
2439 ($prevline, $stashline) = ($stashline, $line);
2440 ($previndent, $stashindent) = ($stashindent, $indent);
2441 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2443 #warn "line<$line>\n";
2445 } elsif ($realcnt == 1) {
2449 my $hunk_line = ($realcnt != 0);
2451 $here = "#$linenr: " if (!$file);
2452 $here = "#$realline: " if ($file);
2455 # extract the filename as it passes
2456 if ($line =~ /^diff --git.*?(\S+)$/) {
2458 $realfile =~ s@^([^/]*)/@@ if (!$file);
2461 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2463 $realfile =~ s@^([^/]*)/@@ if (!$file);
2467 if (!$file && $tree && $p1_prefix ne '' &&
2468 -e "$root/$p1_prefix") {
2469 WARN("PATCH_PREFIX",
2470 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2473 if ($realfile =~ m@^include/asm/@) {
2474 ERROR("MODIFIED_INCLUDE_ASM",
2475 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2480 #make up the handle for any error we report on this line
2482 $prefix = "$realfile:$realline: "
2485 $prefix = "$filename:$realline: ";
2487 $prefix = "$filename:$linenr: ";
2492 if (is_maintained_obsolete($realfile)) {
2494 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2496 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2499 $check = $check_orig;
2501 $checklicenseline = 1;
2505 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2507 my $hereline = "$here\n$rawline\n";
2508 my $herecurr = "$here\n$rawline\n";
2509 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2511 $cnt_lines++ if ($realcnt != 0);
2513 # Check if the commit log has what seems like a diff which can confuse patch
2514 if ($in_commit_log && !$commit_log_has_diff &&
2515 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2516 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2517 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2518 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2519 ERROR("DIFF_IN_COMMIT_MSG",
2520 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2521 $commit_log_has_diff = 1;
2524 # Check for incorrect file permissions
2525 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2526 my $permhere = $here . "FILE: $realfile\n";
2527 if ($realfile !~ m@scripts/@ &&
2528 $realfile !~ /\.(py|pl|awk|sh)$/) {
2529 ERROR("EXECUTE_PERMISSIONS",
2530 "do not set execute permissions for source files\n" . $permhere);
2534 # Check the patch for a From:
2535 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2537 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2541 # Check the patch for a signoff:
2542 if ($line =~ /^\s*signed-off-by:/i) {
2545 if ($author ne '') {
2548 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2554 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2555 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2556 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2557 $reported_maintainer_file = 1;
2560 # Check signature styles
2561 if (!$in_header_lines &&
2562 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2563 my $space_before = $1;
2565 my $space_after = $3;
2567 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2569 if ($sign_off !~ /$signature_tags/) {
2570 WARN("BAD_SIGN_OFF",
2571 "Non-standard signature: $sign_off\n" . $herecurr);
2573 if (defined $space_before && $space_before ne "") {
2574 if (WARN("BAD_SIGN_OFF",
2575 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2577 $fixed[$fixlinenr] =
2578 "$ucfirst_sign_off $email";
2581 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2582 if (WARN("BAD_SIGN_OFF",
2583 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2585 $fixed[$fixlinenr] =
2586 "$ucfirst_sign_off $email";
2590 if (!defined $space_after || $space_after ne " ") {
2591 if (WARN("BAD_SIGN_OFF",
2592 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2594 $fixed[$fixlinenr] =
2595 "$ucfirst_sign_off $email";
2599 my ($email_name, $email_address, $comment) = parse_email($email);
2600 my $suggested_email = format_email(($email_name, $email_address));
2601 if ($suggested_email eq "") {
2602 ERROR("BAD_SIGN_OFF",
2603 "Unrecognized email address: '$email'\n" . $herecurr);
2605 my $dequoted = $suggested_email;
2606 $dequoted =~ s/^"//;
2607 $dequoted =~ s/" </ </;
2608 # Don't force email to have quotes
2609 # Allow just an angle bracketed address
2610 if ("$dequoted$comment" ne $email &&
2611 "<$email_address>$comment" ne $email &&
2612 "$suggested_email$comment" ne $email) {
2613 WARN("BAD_SIGN_OFF",
2614 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2618 # Check for duplicate signatures
2619 my $sig_nospace = $line;
2620 $sig_nospace =~ s/\s//g;
2621 $sig_nospace = lc($sig_nospace);
2622 if (defined $signatures{$sig_nospace}) {
2623 WARN("BAD_SIGN_OFF",
2624 "Duplicate signature\n" . $herecurr);
2626 $signatures{$sig_nospace} = 1;
2630 # Check email subject for common tools that don't need to be mentioned
2631 if ($in_header_lines &&
2632 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2633 WARN("EMAIL_SUBJECT",
2634 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2637 # Check for unwanted Gerrit info
2638 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2639 ERROR("GERRIT_CHANGE_ID",
2640 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2643 # Check if the commit log is in a possible stack dump
2644 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2645 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2646 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2648 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2649 # stack dump address
2650 $commit_log_possible_stack_dump = 1;
2653 # Check for line lengths > 75 in commit log, warn once
2654 if ($in_commit_log && !$commit_log_long_line &&
2655 length($line) > 75 &&
2656 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2657 # file delta changes
2658 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2660 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2661 # A Fixes: or Link: line
2662 $commit_log_possible_stack_dump)) {
2663 WARN("COMMIT_LOG_LONG_LINE",
2664 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2665 $commit_log_long_line = 1;
2668 # Reset possible stack dump if a blank line is found
2669 if ($in_commit_log && $commit_log_possible_stack_dump &&
2671 $commit_log_possible_stack_dump = 0;
2674 # Check for git id commit length and improperly formed commit descriptions
2675 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2676 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2677 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2678 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2679 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2680 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2681 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2682 my $init_char = "c";
2683 my $orig_commit = "";
2690 my $id = '0123456789ab';
2691 my $orig_desc = "commit description";
2692 my $description = "";
2694 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2696 $orig_commit = lc($2);
2697 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2698 $orig_commit = lc($1);
2701 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2702 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2703 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2704 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2705 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2708 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2709 defined $rawlines[$linenr] &&
2710 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2713 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2714 defined $rawlines[$linenr] &&
2715 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2716 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2718 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2719 $orig_desc .= " " . $1;
2723 ($id, $description) = git_commit_info($orig_commit,
2727 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2728 ERROR("GIT_COMMIT_ID",
2729 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2733 # Check for added, moved or deleted files
2734 if (!$reported_maintainer_file && !$in_commit_log &&
2735 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2736 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2737 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2738 (defined($1) || defined($2))))) {
2740 $reported_maintainer_file = 1;
2741 WARN("FILE_PATH_CHANGES",
2742 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2745 # Check for wrappage within a valid hunk of the file
2746 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2747 ERROR("CORRUPTED_PATCH",
2748 "patch seems to be corrupt (line wrapped?)\n" .
2749 $herecurr) if (!$emitted_corrupt++);
2752 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2753 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2754 $rawline !~ m/^$UTF8*$/) {
2755 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2757 my $blank = copy_spacing($rawline);
2758 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2759 my $hereptr = "$hereline$ptr\n";
2762 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2765 # Check if it's the start of a commit log
2766 # (not a header line and we haven't seen the patch filename)
2767 if ($in_header_lines && $realfile =~ /^$/ &&
2768 !($rawline =~ /^\s+(?:\S|$)/ ||
2769 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2770 $in_header_lines = 0;
2772 $has_commit_log = 1;
2775 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2776 # declined it, i.e defined some charset where it is missing.
2777 if ($in_header_lines &&
2778 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2780 $non_utf8_charset = 1;
2783 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2784 $rawline =~ /$NON_ASCII_UTF8/) {
2785 WARN("UTF8_BEFORE_PATCH",
2786 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2789 # Check for absolute kernel paths in commit message
2790 if ($tree && $in_commit_log) {
2791 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2794 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2795 check_absolute_file($1, $herecurr)) {
2798 check_absolute_file($file, $herecurr);
2803 # Check for various typo / spelling mistakes
2804 if (defined($misspellings) &&
2805 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2806 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2808 my $typo_fix = $spelling_fix{lc($typo)};
2809 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2810 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2811 my $msg_level = \&WARN;
2812 $msg_level = \&CHK if ($file);
2813 if (&{$msg_level}("TYPO_SPELLING",
2814 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2816 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2821 # ignore non-hunk lines and lines being removed
2822 next if (!$hunk_line || $line =~ /^-/);
2824 #trailing whitespace
2825 if ($line =~ /^\+.*\015/) {
2826 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2827 if (ERROR("DOS_LINE_ENDINGS",
2828 "DOS line endings\n" . $herevet) &&
2830 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2832 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2833 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2834 if (ERROR("TRAILING_WHITESPACE",
2835 "trailing whitespace\n" . $herevet) &&
2837 $fixed[$fixlinenr] =~ s/\s+$//;
2843 # Check for FSF mailing addresses.
2844 if ($rawline =~ /\bwrite to the Free/i ||
2845 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2846 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2847 $rawline =~ /\b51\s+Franklin\s+St/i) {
2848 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2849 my $msg_level = \&ERROR;
2850 $msg_level = \&CHK if ($file);
2851 &{$msg_level}("FSF_MAILING_ADDRESS",
2852 "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)
2855 # check for Kconfig help text having a real description
2856 # Only applies when adding the entry originally, after that we do not have
2857 # sufficient context to determine whether it is indeed long enough.
2858 if ($realfile =~ /Kconfig/ &&
2859 # 'choice' is usually the last thing on the line (though
2860 # Kconfig supports named choices), so use a word boundary
2861 # (\b) rather than a whitespace character (\s)
2862 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2865 my $ln = $linenr + 1;
2869 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2870 $f = $lines[$ln - 1];
2871 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2872 $is_end = $lines[$ln - 1] =~ /^\+/;
2874 next if ($f =~ /^-/);
2875 last if (!$file && $f =~ /^\@\@/);
2877 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2879 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2880 if ($lines[$ln - 1] =~ "---help---") {
2881 WARN("CONFIG_DESCRIPTION",
2882 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2890 next if ($f =~ /^$/);
2892 # This only checks context lines in the patch
2893 # and so hopefully shouldn't trigger false
2894 # positives, even though some of these are
2895 # common words in help texts
2896 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2897 if|endif|menu|endmenu|source)\b/x) {
2903 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2904 WARN("CONFIG_DESCRIPTION",
2905 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2907 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2910 # check for MAINTAINERS entries that don't have the right form
2911 if ($realfile =~ /^MAINTAINERS$/ &&
2912 $rawline =~ /^\+[A-Z]:/ &&
2913 $rawline !~ /^\+[A-Z]:\t\S/) {
2914 if (WARN("MAINTAINERS_STYLE",
2915 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2917 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2921 # discourage the use of boolean for type definition attributes of Kconfig options
2922 if ($realfile =~ /Kconfig/ &&
2923 $line =~ /^\+\s*\bboolean\b/) {
2924 WARN("CONFIG_TYPE_BOOLEAN",
2925 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2928 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2929 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2932 'EXTRA_AFLAGS' => 'asflags-y',
2933 'EXTRA_CFLAGS' => 'ccflags-y',
2934 'EXTRA_CPPFLAGS' => 'cppflags-y',
2935 'EXTRA_LDFLAGS' => 'ldflags-y',
2938 WARN("DEPRECATED_VARIABLE",
2939 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2942 # check for DT compatible documentation
2943 if (defined $root &&
2944 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2945 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2947 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2949 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2950 my $vp_file = $dt_path . "vendor-prefixes.txt";
2952 foreach my $compat (@compats) {
2953 my $compat2 = $compat;
2954 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2955 my $compat3 = $compat;
2956 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2957 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2959 WARN("UNDOCUMENTED_DT_STRING",
2960 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2963 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2965 `grep -Eq "^$vendor\\b" $vp_file`;
2967 WARN("UNDOCUMENTED_DT_STRING",
2968 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2973 # check for using SPDX license tag at beginning of files
2974 if ($realline == $checklicenseline) {
2975 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
2976 $checklicenseline = 2;
2977 } elsif ($rawline =~ /^\+/) {
2979 if ($realfile =~ /\.(h|s|S)$/) {
2981 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
2983 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
2985 } elsif ($realfile =~ /\.rst$/) {
2989 if ($comment !~ /^$/ &&
2990 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
2991 WARN("SPDX_LICENSE_TAG",
2992 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
2993 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
2994 my $spdx_license = $1;
2995 if (!is_SPDX_License_valid($spdx_license)) {
2996 WARN("SPDX_LICENSE_TAG",
2997 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3003 # check we are in a valid source file if not then ignore this hunk
3004 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3006 # line length limit (with some exclusions)
3008 # There are a few types of lines that may extend beyond $max_line_length:
3009 # logging functions like pr_info that end in a string
3010 # lines with a single string
3011 # #defines that are a single string
3012 # lines with an RFC3986 like URL
3014 # There are 3 different line length message types:
3015 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3016 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3017 # LONG_LINE all other lines longer than $max_line_length
3019 # if LONG_LINE is ignored, the other 2 types are also ignored
3022 if ($line =~ /^\+/ && $length > $max_line_length) {
3023 my $msg_type = "LONG_LINE";
3025 # Check the allowed long line types first
3027 # logging functions that end in a string that starts
3028 # before $max_line_length
3029 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3030 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3033 # lines with only strings (w/ possible termination)
3034 # #defines with only strings
3035 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3036 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3039 # More special cases
3040 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3041 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3044 # URL ($rawline is used in case the URL is in a comment)
3045 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3048 # Otherwise set the alternate message types
3050 # a comment starts before $max_line_length
3051 } elsif ($line =~ /($;[\s$;]*)$/ &&
3052 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3053 $msg_type = "LONG_LINE_COMMENT"
3055 # a quoted string starts before $max_line_length
3056 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3057 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3058 $msg_type = "LONG_LINE_STRING"
3061 if ($msg_type ne "" &&
3062 (show_type("LONG_LINE") || show_type($msg_type))) {
3064 "line over $max_line_length characters\n" . $herecurr);
3068 # check for adding lines without a newline.
3069 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3070 WARN("MISSING_EOF_NEWLINE",
3071 "adding a line without newline at end of file\n" . $herecurr);
3074 # check we are in a valid source file C or perl if not then ignore this hunk
3075 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3077 # at the beginning of a line any tabs must come first and anything
3078 # more than 8 must use tabs.
3079 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3080 $rawline =~ /^\+\s* \s*/) {
3081 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3083 if (ERROR("CODE_INDENT",
3084 "code indent should use tabs where possible\n" . $herevet) &&
3086 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3090 # check for space before tabs.
3091 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3092 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3093 if (WARN("SPACE_BEFORE_TAB",
3094 "please, no space before tabs\n" . $herevet) &&
3096 while ($fixed[$fixlinenr] =~
3097 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3098 while ($fixed[$fixlinenr] =~
3099 s/(^\+.*) +\t/$1\t/) {}
3103 # check for assignments on the start of a line
3104 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3105 CHK("ASSIGNMENT_CONTINUATIONS",
3106 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3109 # check for && or || at the start of a line
3110 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3111 CHK("LOGICAL_CONTINUATIONS",
3112 "Logical continuations should be on the previous line\n" . $hereprev);
3115 # check indentation starts on a tab stop
3116 if ($perl_version_ok &&
3117 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3118 my $indent = length($1);
3121 "Statements should start on a tabstop\n" . $herecurr) &&
3123 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3128 # check multi-line statement indentation matches previous line
3129 if ($perl_version_ok &&
3130 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3131 $prevline =~ /^\+(\t*)(.*)$/;
3135 my $pos = pos_last_openparen($rest);
3137 $line =~ /^(\+| )([ \t]*)/;
3140 my $goodtabindent = $oldindent .
3143 my $goodspaceindent = $oldindent . " " x $pos;
3145 if ($newindent ne $goodtabindent &&
3146 $newindent ne $goodspaceindent) {
3148 if (CHK("PARENTHESIS_ALIGNMENT",
3149 "Alignment should match open parenthesis\n" . $hereprev) &&
3150 $fix && $line =~ /^\+/) {
3151 $fixed[$fixlinenr] =~
3152 s/^\+[ \t]*/\+$goodtabindent/;
3158 # check for space after cast like "(int) foo" or "(struct foo) bar"
3159 # avoid checking a few false positives:
3160 # "sizeof(<type>)" or "__alignof__(<type>)"
3161 # function pointer declarations like "(*foo)(int) = bar;"
3162 # structure definitions like "(struct foo) { 0 };"
3163 # multiline macros that define functions
3164 # known attributes or the __attribute__ keyword
3165 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3166 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3168 "No space is necessary after a cast\n" . $herecurr) &&
3170 $fixed[$fixlinenr] =~
3171 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3175 # Block comment styles
3176 # Networking with an initial /*
3177 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3178 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3179 $rawline =~ /^\+[ \t]*\*/ &&
3181 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3182 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3185 # Block comments use * on subsequent lines
3186 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3187 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3188 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3189 $rawline =~ /^\+/ && #line is new
3190 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3191 WARN("BLOCK_COMMENT_STYLE",
3192 "Block comments use * on subsequent lines\n" . $hereprev);
3195 # Block comments use */ on trailing lines
3196 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3197 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3198 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3199 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3200 WARN("BLOCK_COMMENT_STYLE",
3201 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3204 # Block comment * alignment
3205 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3206 $line =~ /^\+[ \t]*$;/ && #leading comment
3207 $rawline =~ /^\+[ \t]*\*/ && #leading *
3208 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3209 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3210 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3212 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3214 $oldindent = expand_tabs($1);
3216 $prevrawline =~ m@^\+(.*/?)\*@;
3217 $oldindent = expand_tabs($1);
3219 $rawline =~ m@^\+([ \t]*)\*@;
3221 $newindent = expand_tabs($newindent);
3222 if (length($oldindent) ne length($newindent)) {
3223 WARN("BLOCK_COMMENT_STYLE",
3224 "Block comments should align the * on each line\n" . $hereprev);
3228 # check for missing blank lines after struct/union declarations
3229 # with exceptions for various attributes and macros
3230 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3232 !($line =~ /^\+\s*$/ ||
3233 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3234 $line =~ /^\+\s*MODULE_/i ||
3235 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3236 $line =~ /^\+[a-z_]*init/ ||
3237 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3238 $line =~ /^\+\s*DECLARE/ ||
3239 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3240 $line =~ /^\+\s*__setup/)) {
3241 if (CHK("LINE_SPACING",
3242 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3244 fix_insert_line($fixlinenr, "\+");
3248 # check for multiple consecutive blank lines
3249 if ($prevline =~ /^[\+ ]\s*$/ &&
3250 $line =~ /^\+\s*$/ &&
3251 $last_blank_line != ($linenr - 1)) {
3252 if (CHK("LINE_SPACING",
3253 "Please don't use multiple blank lines\n" . $hereprev) &&
3255 fix_delete_line($fixlinenr, $rawline);
3258 $last_blank_line = $linenr;
3261 # check for missing blank lines after declarations
3262 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3263 # actual declarations
3264 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3265 # function pointer declarations
3266 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3267 # foo bar; where foo is some local typedef or #define
3268 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3269 # known declaration macros
3270 $prevline =~ /^\+\s+$declaration_macros/) &&
3271 # for "else if" which can look like "$Ident $Ident"
3272 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3273 # other possible extensions of declaration lines
3274 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3275 # not starting a section or a macro "\" extended line
3276 $prevline =~ /(?:\{\s*|\\)$/) &&
3277 # looks like a declaration
3278 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3279 # function pointer declarations
3280 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3281 # foo bar; where foo is some local typedef or #define
3282 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3283 # known declaration macros
3284 $sline =~ /^\+\s+$declaration_macros/ ||
3285 # start of struct or union or enum
3286 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3287 # start or end of block or continuation of declaration
3288 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3289 # bitfield continuation
3290 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3291 # other possible extensions of declaration lines
3292 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3293 # indentation of previous and current line are the same
3294 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3295 if (WARN("LINE_SPACING",
3296 "Missing a blank line after declarations\n" . $hereprev) &&
3298 fix_insert_line($fixlinenr, "\+");
3302 # check for spaces at the beginning of a line.
3304 # 1) within comments
3305 # 2) indented preprocessor commands
3307 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3308 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3309 if (WARN("LEADING_SPACE",
3310 "please, no spaces at the start of a line\n" . $herevet) &&
3312 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3316 # check we are in a valid C source file if not then ignore this hunk
3317 next if ($realfile !~ /\.(h|c)$/);
3319 # check for unusual line ending [ or (
3320 if ($line =~ /^\+.*([\[\(])\s*$/) {
3321 CHK("OPEN_ENDED_LINE",
3322 "Lines should not end with a '$1'\n" . $herecurr);
3325 # check if this appears to be the start function declaration, save the name
3326 if ($sline =~ /^\+\{\s*$/ &&
3327 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3328 $context_function = $1;
3331 # check if this appears to be the end of function declaration
3332 if ($sline =~ /^\+\}\s*$/) {
3333 undef $context_function;
3336 # check indentation of any line with a bare else
3337 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3338 # if the previous line is a break or return and is indented 1 tab more...
3339 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3340 my $tabs = length($1) + 1;
3341 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3342 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3343 defined $lines[$linenr] &&
3344 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3345 WARN("UNNECESSARY_ELSE",
3346 "else is not generally useful after a break or return\n" . $hereprev);
3350 # check indentation of a line with a break;
3351 # if the previous line is a goto or return and is indented the same # of tabs
3352 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3354 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3355 WARN("UNNECESSARY_BREAK",
3356 "break is not useful after a goto or return\n" . $hereprev);
3360 # check for RCS/CVS revision markers
3361 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3363 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3366 # check for old HOTPLUG __dev<foo> section markings
3367 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3368 WARN("HOTPLUG_SECTION",
3369 "Using $1 is unnecessary\n" . $herecurr);
3372 # Check for potential 'bare' types
3373 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3375 #print "LINE<$line>\n";
3376 if ($linenr > $suppress_statement &&
3377 $realcnt && $sline =~ /.\s*\S/) {
3378 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3379 ctx_statement_block($linenr, $realcnt, 0);
3380 $stat =~ s/\n./\n /g;
3381 $cond =~ s/\n./\n /g;
3383 #print "linenr<$linenr> <$stat>\n";
3384 # If this statement has no statement boundaries within
3385 # it there is no point in retrying a statement scan
3386 # until we hit end of it.
3387 my $frag = $stat; $frag =~ s/;+\s*$//;
3388 if ($frag !~ /(?:{|;)/) {
3389 #print "skip<$line_nr_next>\n";
3390 $suppress_statement = $line_nr_next;
3393 # Find the real next line.
3394 $realline_next = $line_nr_next;
3395 if (defined $realline_next &&
3396 (!defined $lines[$realline_next - 1] ||
3397 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3404 # Ignore goto labels.
3405 if ($s =~ /$Ident:\*$/s) {
3407 # Ignore functions being called
3408 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3410 } elsif ($s =~ /^.\s*else\b/s) {
3412 # declarations always start with types
3413 } 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) {
3416 possible($type, "A:" . $s);
3418 # definitions in global scope can only start with types
3419 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3420 possible($1, "B:" . $s);
3423 # any (foo ... *) is a pointer cast, and foo is a type
3424 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3425 possible($1, "C:" . $s);
3428 # Check for any sort of function declaration.
3429 # int foo(something bar, other baz);
3430 # void (*store_gdt)(x86_descr_ptr *);
3431 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3432 my ($name_len) = length($1);
3435 substr($ctx, 0, $name_len + 1, '');
3436 $ctx =~ s/\)[^\)]*$//;
3438 for my $arg (split(/\s*,\s*/, $ctx)) {
3439 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3441 possible($1, "D:" . $s);
3449 # Checks which may be anchored in the context.
3452 # Check for switch () and associated case and default
3453 # statements should be at the same indent.
3454 if ($line=~/\bswitch\s*\(.*\)/) {
3457 my @ctx = ctx_block_outer($linenr, $realcnt);
3459 for my $ctx (@ctx) {
3460 my ($clen, $cindent) = line_stats($ctx);
3461 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3462 $indent != $cindent) {
3463 $err .= "$sep$ctx\n";
3470 ERROR("SWITCH_CASE_INDENT_LEVEL",
3471 "switch and case should be at the same indent\n$hereline$err");
3475 # if/while/etc brace do not go on next line, unless defining a do while loop,
3476 # or if that brace on the next line is for something else
3477 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3478 my $pre_ctx = "$1$2";
3480 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3482 if ($line =~ /^\+\t{6,}/) {
3483 WARN("DEEP_INDENTATION",
3484 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3487 my $ctx_cnt = $realcnt - $#ctx - 1;
3488 my $ctx = join("\n", @ctx);
3490 my $ctx_ln = $linenr;
3491 my $ctx_skip = $realcnt;
3493 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3494 defined $lines[$ctx_ln - 1] &&
3495 $lines[$ctx_ln - 1] =~ /^-/)) {
3496 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3497 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3501 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3502 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3504 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3506 "that open brace { should be on the previous line\n" .
3507 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3509 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3510 $ctx =~ /\)\s*\;\s*$/ &&
3511 defined $lines[$ctx_ln - 1])
3513 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3514 if ($nindent > $indent) {
3515 WARN("TRAILING_SEMICOLON",
3516 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3517 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3522 # Check relative indent for conditionals and blocks.
3523 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3524 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3525 ctx_statement_block($linenr, $realcnt, 0)
3526 if (!defined $stat);
3527 my ($s, $c) = ($stat, $cond);
3529 substr($s, 0, length($c), '');
3531 # remove inline comments
3535 # Find out how long the conditional actually is.
3536 my @newlines = ($c =~ /\n/gs);
3537 my $cond_lines = 1 + $#newlines;
3539 # Make sure we remove the line prefixes as we have
3540 # none on the first line, and are going to readd them
3543 while ($s =~ /\n\s+\\\n/) {
3544 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3547 # We want to check the first line inside the block
3548 # starting at the end of the conditional, so remove:
3549 # 1) any blank line termination
3550 # 2) any opening brace { on end of the line
3552 my $continuation = 0;
3554 $s =~ s/^.*\bdo\b//;
3556 if ($s =~ s/^\s*\\//) {
3559 if ($s =~ s/^\s*?\n//) {
3564 # Also ignore a loop construct at the end of a
3565 # preprocessor statement.
3566 if (($prevline =~ /^.\s*#\s*define\s/ ||
3567 $prevline =~ /\\\s*$/) && $continuation == 0) {
3573 while ($cond_ptr != $cond_lines) {
3574 $cond_ptr = $cond_lines;
3576 # If we see an #else/#elif then the code
3578 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3583 # 1) blank lines, they should be at 0,
3584 # 2) preprocessor lines, and
3586 if ($continuation ||
3588 $s =~ /^\s*#\s*?/ ||
3589 $s =~ /^\s*$Ident\s*:/) {
3590 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3591 if ($s =~ s/^.*?\n//) {
3597 my (undef, $sindent) = line_stats("+" . $s);
3598 my $stat_real = raw_line($linenr, $cond_lines);
3600 # Check if either of these lines are modified, else
3601 # this is not this patch's fault.
3602 if (!defined($stat_real) ||
3603 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3606 if (defined($stat_real) && $cond_lines > 1) {
3607 $stat_real = "[...]\n$stat_real";
3610 #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";
3612 if ($check && $s ne '' &&
3613 (($sindent % 8) != 0 ||
3614 ($sindent < $indent) ||
3615 ($sindent == $indent &&
3616 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3617 ($sindent > $indent + 8))) {
3618 WARN("SUSPECT_CODE_INDENT",
3619 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3623 # Track the 'values' across context and added lines.
3624 my $opline = $line; $opline =~ s/^./ /;
3625 my ($curr_values, $curr_vars) =
3626 annotate_values($opline . "\n", $prev_values);
3627 $curr_values = $prev_values . $curr_values;
3629 my $outline = $opline; $outline =~ s/\t/ /g;
3630 print "$linenr > .$outline\n";
3631 print "$linenr > $curr_values\n";
3632 print "$linenr > $curr_vars\n";
3634 $prev_values = substr($curr_values, -1);
3636 #ignore lines not being added
3637 next if ($line =~ /^[^\+]/);
3639 # check for dereferences that span multiple lines
3640 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3641 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3642 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3644 $line =~ /^.\s*($Lval)/;
3647 WARN("MULTILINE_DEREFERENCE",
3648 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3651 # check for declarations of signed or unsigned without int
3652 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3655 $var = "" if (!defined $var);
3656 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3660 $pointer = "" if (!defined $pointer);
3662 if (WARN("UNSPECIFIED_INT",
3663 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3665 my $decl = trim($sign) . " int ";
3666 my $comp_pointer = $pointer;
3667 $comp_pointer =~ s/\s//g;
3668 $decl .= $comp_pointer;
3669 $decl = rtrim($decl) if ($var eq "");
3670 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3675 # TEST: allow direct testing of the type matcher.
3677 if ($line =~ /^.\s*$Declare\s*$/) {
3679 "TEST: is type\n" . $herecurr);
3680 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3681 ERROR("TEST_NOT_TYPE",
3682 "TEST: is not type ($1 is)\n". $herecurr);
3686 # TEST: allow direct testing of the attribute matcher.
3688 if ($line =~ /^.\s*$Modifier\s*$/) {
3690 "TEST: is attr\n" . $herecurr);
3691 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3692 ERROR("TEST_NOT_ATTR",
3693 "TEST: is not attr ($1 is)\n". $herecurr);
3698 # check for initialisation to aggregates open brace on the next line
3699 if ($line =~ /^.\s*{/ &&
3700 $prevline =~ /(?:^|[^=])=\s*$/) {
3701 if (ERROR("OPEN_BRACE",
3702 "that open brace { should be on the previous line\n" . $hereprev) &&
3703 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3704 fix_delete_line($fixlinenr - 1, $prevrawline);
3705 fix_delete_line($fixlinenr, $rawline);
3706 my $fixedline = $prevrawline;
3707 $fixedline =~ s/\s*=\s*$/ = {/;
3708 fix_insert_line($fixlinenr, $fixedline);
3710 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3711 fix_insert_line($fixlinenr, $fixedline);
3716 # Checks which are anchored on the added line.
3719 # check for malformed paths in #include statements (uses RAW line)
3720 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3722 if ($path =~ m{//}) {
3723 ERROR("MALFORMED_INCLUDE",
3724 "malformed #include filename\n" . $herecurr);
3726 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3727 ERROR("UAPI_INCLUDE",
3728 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3732 # no C99 // comments
3733 if ($line =~ m{//}) {
3734 if (ERROR("C99_COMMENTS",
3735 "do not use C99 // comments\n" . $herecurr) &&
3737 my $line = $fixed[$fixlinenr];
3738 if ($line =~ /\/\/(.*)$/) {
3739 my $comment = trim($1);
3740 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3744 # Remove C99 comments.
3746 $opline =~ s@//.*@@;
3748 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3749 # the whole statement.
3750 #print "APW <$lines[$realline_next - 1]>\n";
3751 if (defined $realline_next &&
3752 exists $lines[$realline_next - 1] &&
3753 !defined $suppress_export{$realline_next} &&
3754 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3755 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3756 # Handle definitions which produce identifiers with
3759 # EXPORT_SYMBOL(something_foo);
3761 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3762 $name =~ /^${Ident}_$2/) {
3763 #print "FOO C name<$name>\n";
3764 $suppress_export{$realline_next} = 1;
3766 } elsif ($stat !~ /(?:
3768 ^.DEFINE_$Ident\(\Q$name\E\)|
3769 ^.DECLARE_$Ident\(\Q$name\E\)|
3770 ^.LIST_HEAD\(\Q$name\E\)|
3771 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3772 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3774 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3775 $suppress_export{$realline_next} = 2;
3777 $suppress_export{$realline_next} = 1;
3780 if (!defined $suppress_export{$linenr} &&
3781 $prevline =~ /^.\s*$/ &&
3782 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3783 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3784 #print "FOO B <$lines[$linenr - 1]>\n";
3785 $suppress_export{$linenr} = 2;
3787 if (defined $suppress_export{$linenr} &&
3788 $suppress_export{$linenr} == 2) {
3789 WARN("EXPORT_SYMBOL",
3790 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3793 # check for global initialisers.
3794 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3795 if (ERROR("GLOBAL_INITIALISERS",
3796 "do not initialise globals to $1\n" . $herecurr) &&
3798 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3801 # check for static initialisers.
3802 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3803 if (ERROR("INITIALISED_STATIC",
3804 "do not initialise statics to $1\n" .
3807 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3811 # check for misordered declarations of char/short/int/long with signed/unsigned
3812 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3814 WARN("MISORDERED_TYPE",
3815 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3818 # check for static const char * arrays.
3819 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3820 WARN("STATIC_CONST_CHAR_ARRAY",
3821 "static const char * array should probably be static const char * const\n" .
3825 # check for static char foo[] = "bar" declarations.
3826 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3827 WARN("STATIC_CONST_CHAR_ARRAY",
3828 "static char array declaration should probably be static const char\n" .
3832 # check for const <foo> const where <foo> is not a pointer or array type
3833 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3835 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3837 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3838 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3840 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3844 # check for non-global char *foo[] = {"bar", ...} declarations.
3845 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3846 WARN("STATIC_CONST_CHAR_ARRAY",
3847 "char * array declaration might be better as static const\n" .
3851 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3852 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3854 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3856 if (WARN("ARRAY_SIZE",
3857 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3859 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3864 # check for function declarations without arguments like "int foo()"
3865 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3866 if (ERROR("FUNCTION_WITHOUT_ARGS",
3867 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3869 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3873 # check for new typedefs, only function parameters and sparse annotations
3875 if ($line =~ /\btypedef\s/ &&
3876 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3877 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3878 $line !~ /\b$typeTypedefs\b/ &&
3879 $line !~ /\b__bitwise\b/) {
3880 WARN("NEW_TYPEDEFS",
3881 "do not add new typedefs\n" . $herecurr);
3884 # * goes on variable not on type
3886 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3888 my ($ident, $from, $to) = ($1, $2, $2);
3890 # Should start with a space.
3891 $to =~ s/^(\S)/ $1/;
3892 # Should not end with a space.
3894 # '*'s should not have spaces between.
3895 while ($to =~ s/\*\s+\*/\*\*/) {
3898 ## print "1: from<$from> to<$to> ident<$ident>\n";
3900 if (ERROR("POINTER_LOCATION",
3901 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3903 my $sub_from = $ident;
3904 my $sub_to = $ident;
3905 $sub_to =~ s/\Q$from\E/$to/;
3906 $fixed[$fixlinenr] =~
3907 s@\Q$sub_from\E@$sub_to@;
3911 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3913 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3915 # Should start with a space.
3916 $to =~ s/^(\S)/ $1/;
3917 # Should not end with a space.
3919 # '*'s should not have spaces between.
3920 while ($to =~ s/\*\s+\*/\*\*/) {
3922 # Modifiers should have spaces.
3923 $to =~ s/(\b$Modifier$)/$1 /;
3925 ## print "2: from<$from> to<$to> ident<$ident>\n";
3926 if ($from ne $to && $ident !~ /^$Modifier$/) {
3927 if (ERROR("POINTER_LOCATION",
3928 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3931 my $sub_from = $match;
3932 my $sub_to = $match;
3933 $sub_to =~ s/\Q$from\E/$to/;
3934 $fixed[$fixlinenr] =~
3935 s@\Q$sub_from\E@$sub_to@;
3940 # avoid BUG() or BUG_ON()
3941 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3942 my $msg_level = \&WARN;
3943 $msg_level = \&CHK if ($file);
3944 &{$msg_level}("AVOID_BUG",
3945 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3948 # avoid LINUX_VERSION_CODE
3949 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3950 WARN("LINUX_VERSION_CODE",
3951 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3954 # check for uses of printk_ratelimit
3955 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3956 WARN("PRINTK_RATELIMITED",
3957 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3960 # printk should use KERN_* levels
3961 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
3962 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3963 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
3966 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3968 my $level = lc($orig);
3969 $level = "warn" if ($level eq "warning");
3970 my $level2 = $level;
3971 $level2 = "dbg" if ($level eq "debug");
3972 WARN("PREFER_PR_LEVEL",
3973 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3976 if ($line =~ /\bpr_warning\s*\(/) {
3977 if (WARN("PREFER_PR_LEVEL",
3978 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3980 $fixed[$fixlinenr] =~
3981 s/\bpr_warning\b/pr_warn/;
3985 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3987 my $level = lc($orig);
3988 $level = "warn" if ($level eq "warning");
3989 $level = "dbg" if ($level eq "debug");
3990 WARN("PREFER_DEV_LEVEL",
3991 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3994 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
3995 # number of false positives, but assembly files are not checked, so at
3996 # least the arch entry code will not trigger this warning.
3997 if ($line =~ /\bENOSYS\b/) {
3999 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4002 # function brace can't be on same line, except for #defines of do while,
4003 # or if closed on same line
4004 if ($perl_version_ok &&
4005 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4006 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4008 if (ERROR("OPEN_BRACE",
4009 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4011 fix_delete_line($fixlinenr, $rawline);
4012 my $fixed_line = $rawline;
4013 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4016 fix_insert_line($fixlinenr, ltrim($line1));
4017 fix_insert_line($fixlinenr, "\+{");
4018 if ($line2 !~ /^\s*$/) {
4019 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4024 # open braces for enum, union and struct go on the same line.
4025 if ($line =~ /^.\s*{/ &&
4026 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4027 if (ERROR("OPEN_BRACE",
4028 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4029 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4030 fix_delete_line($fixlinenr - 1, $prevrawline);
4031 fix_delete_line($fixlinenr, $rawline);
4032 my $fixedline = rtrim($prevrawline) . " {";
4033 fix_insert_line($fixlinenr, $fixedline);
4034 $fixedline = $rawline;
4035 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4036 if ($fixedline !~ /^\+\s*$/) {
4037 fix_insert_line($fixlinenr, $fixedline);
4042 # missing space after union, struct or enum definition
4043 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4045 "missing space after $1 definition\n" . $herecurr) &&
4047 $fixed[$fixlinenr] =~
4048 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4052 # Function pointer declarations
4053 # check spacing between type, funcptr, and args
4054 # canonical declaration is "type (*funcptr)(args...)"
4055 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4057 my $pre_pointer_space = $2;
4058 my $post_pointer_space = $3;
4060 my $post_funcname_space = $5;
4061 my $pre_args_space = $6;
4063 # the $Declare variable will capture all spaces after the type
4064 # so check it for a missing trailing missing space but pointer return types
4065 # don't need a space so don't warn for those.
4066 my $post_declare_space = "";
4067 if ($declare =~ /(\s+)$/) {
4068 $post_declare_space = $1;
4069 $declare = rtrim($declare);
4071 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4073 "missing space after return type\n" . $herecurr);
4074 $post_declare_space = " ";
4077 # unnecessary space "type (*funcptr)(args...)"
4078 # This test is not currently implemented because these declarations are
4080 # int foo(int bar, ...)
4081 # and this is form shouldn't/doesn't generate a checkpatch warning.
4083 # elsif ($declare =~ /\s{2,}$/) {
4085 # "Multiple spaces after return type\n" . $herecurr);
4088 # unnecessary space "type ( *funcptr)(args...)"
4089 if (defined $pre_pointer_space &&
4090 $pre_pointer_space =~ /^\s/) {
4092 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4095 # unnecessary space "type (* funcptr)(args...)"
4096 if (defined $post_pointer_space &&
4097 $post_pointer_space =~ /^\s/) {
4099 "Unnecessary space before function pointer name\n" . $herecurr);
4102 # unnecessary space "type (*funcptr )(args...)"
4103 if (defined $post_funcname_space &&
4104 $post_funcname_space =~ /^\s/) {
4106 "Unnecessary space after function pointer name\n" . $herecurr);
4109 # unnecessary space "type (*funcptr) (args...)"
4110 if (defined $pre_args_space &&
4111 $pre_args_space =~ /^\s/) {
4113 "Unnecessary space before function pointer arguments\n" . $herecurr);
4116 if (show_type("SPACING") && $fix) {
4117 $fixed[$fixlinenr] =~
4118 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4122 # check for spacing round square brackets; allowed:
4123 # 1. with a type on the left -- int [] a;
4124 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4125 # 3. inside a curly brace -- = { [0...10] = 5 }
4126 while ($line =~ /(.*?\s)\[/g) {
4127 my ($where, $prefix) = ($-[1], $1);
4128 if ($prefix !~ /$Type\s+$/ &&
4129 ($where != 0 || $prefix !~ /^.\s+$/) &&
4130 $prefix !~ /[{,:]\s+$/) {
4131 if (ERROR("BRACKET_SPACE",
4132 "space prohibited before open square bracket '['\n" . $herecurr) &&
4134 $fixed[$fixlinenr] =~
4135 s/^(\+.*?)\s+\[/$1\[/;
4140 # check for spaces between functions and their parentheses.
4141 while ($line =~ /($Ident)\s+\(/g) {
4143 my $ctx_before = substr($line, 0, $-[1]);
4144 my $ctx = "$ctx_before$name";
4146 # Ignore those directives where spaces _are_ permitted.
4148 if|for|while|switch|return|case|
4149 volatile|__volatile__|
4150 __attribute__|format|__extension__|
4153 # cpp #define statements have non-optional spaces, ie
4154 # if there is a space between the name and the open
4155 # parenthesis it is simply not a parameter group.
4156 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4158 # cpp #elif statement condition may start with a (
4159 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4161 # If this whole things ends with a type its most
4162 # likely a typedef for a function.
4163 } elsif ($ctx =~ /$Type$/) {
4167 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4169 $fixed[$fixlinenr] =~
4170 s/\b$name\s+\(/$name\(/;
4175 # Check operator spacing.
4176 if (!($line=~/\#\s*include/)) {
4177 my $fixed_line = "";
4181 <<=|>>=|<=|>=|==|!=|
4182 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4183 =>|->|<<|>>|<|>|=|!|~|
4184 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4187 my @elements = split(/($ops|;)/, $opline);
4189 ## print("element count: <" . $#elements . ">\n");
4190 ## foreach my $el (@elements) {
4191 ## print("el: <$el>\n");
4194 my @fix_elements = ();
4197 foreach my $el (@elements) {
4198 push(@fix_elements, substr($rawline, $off, length($el)));
4199 $off += length($el);
4204 my $blank = copy_spacing($opline);
4205 my $last_after = -1;
4207 for (my $n = 0; $n < $#elements; $n += 2) {
4209 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4211 ## print("n: <$n> good: <$good>\n");
4213 $off += length($elements[$n]);
4215 # Pick up the preceding and succeeding characters.
4216 my $ca = substr($opline, 0, $off);
4218 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4219 $cc = substr($opline, $off + length($elements[$n + 1]));
4221 my $cb = "$ca$;$cc";
4224 $a = 'V' if ($elements[$n] ne '');
4225 $a = 'W' if ($elements[$n] =~ /\s$/);
4226 $a = 'C' if ($elements[$n] =~ /$;$/);
4227 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4228 $a = 'O' if ($elements[$n] eq '');
4229 $a = 'E' if ($ca =~ /^\s*$/);
4231 my $op = $elements[$n + 1];
4234 if (defined $elements[$n + 2]) {
4235 $c = 'V' if ($elements[$n + 2] ne '');
4236 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4237 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4238 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4239 $c = 'O' if ($elements[$n + 2] eq '');
4240 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4245 my $ctx = "${a}x${c}";
4247 my $at = "(ctx:$ctx)";
4249 my $ptr = substr($blank, 0, $off) . "^";
4250 my $hereptr = "$hereline$ptr\n";
4252 # Pull out the value of this operator.
4253 my $op_type = substr($curr_values, $off + 1, 1);
4255 # Get the full operator variant.
4256 my $opv = $op . substr($curr_vars, $off, 1);
4258 # Ignore operators passed as parameters.
4259 if ($op_type ne 'V' &&
4260 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4263 # } elsif ($op =~ /^$;+$/) {
4265 # ; should have either the end of line or a space or \ after it
4266 } elsif ($op eq ';') {
4267 if ($ctx !~ /.x[WEBC]/ &&
4268 $cc !~ /^\\/ && $cc !~ /^;/) {
4269 if (ERROR("SPACING",
4270 "space required after that '$op' $at\n" . $hereptr)) {
4271 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4277 } elsif ($op eq '//') {
4279 # : when part of a bitfield
4280 } elsif ($opv eq ':B') {
4281 # skip the bitfield test for now
4285 } elsif ($op eq '->') {
4286 if ($ctx =~ /Wx.|.xW/) {
4287 if (ERROR("SPACING",
4288 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4289 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4290 if (defined $fix_elements[$n + 2]) {
4291 $fix_elements[$n + 2] =~ s/^\s+//;
4297 # , must not have a space before and must have a space on the right.
4298 } elsif ($op eq ',') {
4299 my $rtrim_before = 0;
4300 my $space_after = 0;
4301 if ($ctx =~ /Wx./) {
4302 if (ERROR("SPACING",
4303 "space prohibited before that '$op' $at\n" . $hereptr)) {
4308 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4309 if (ERROR("SPACING",
4310 "space required after that '$op' $at\n" . $hereptr)) {
4316 if ($rtrim_before || $space_after) {
4317 if ($rtrim_before) {
4318 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4320 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4327 # '*' as part of a type definition -- reported already.
4328 } elsif ($opv eq '*_') {
4329 #warn "'*' is part of type\n";
4331 # unary operators should have a space before and
4332 # none after. May be left adjacent to another
4333 # unary operator, or a cast
4334 } elsif ($op eq '!' || $op eq '~' ||
4335 $opv eq '*U' || $opv eq '-U' ||
4336 $opv eq '&U' || $opv eq '&&U') {
4337 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4338 if (ERROR("SPACING",
4339 "space required before that '$op' $at\n" . $hereptr)) {
4340 if ($n != $last_after + 2) {
4341 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4346 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4347 # A unary '*' may be const
4349 } elsif ($ctx =~ /.xW/) {
4350 if (ERROR("SPACING",
4351 "space prohibited after that '$op' $at\n" . $hereptr)) {
4352 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4353 if (defined $fix_elements[$n + 2]) {
4354 $fix_elements[$n + 2] =~ s/^\s+//;
4360 # unary ++ and unary -- are allowed no space on one side.
4361 } elsif ($op eq '++' or $op eq '--') {
4362 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4363 if (ERROR("SPACING",
4364 "space required one side of that '$op' $at\n" . $hereptr)) {
4365 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4369 if ($ctx =~ /Wx[BE]/ ||
4370 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4371 if (ERROR("SPACING",
4372 "space prohibited before that '$op' $at\n" . $hereptr)) {
4373 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4377 if ($ctx =~ /ExW/) {
4378 if (ERROR("SPACING",
4379 "space prohibited after that '$op' $at\n" . $hereptr)) {
4380 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4381 if (defined $fix_elements[$n + 2]) {
4382 $fix_elements[$n + 2] =~ s/^\s+//;
4388 # << and >> may either have or not have spaces both sides
4389 } elsif ($op eq '<<' or $op eq '>>' or
4390 $op eq '&' or $op eq '^' or $op eq '|' or
4391 $op eq '+' or $op eq '-' or
4392 $op eq '*' or $op eq '/' or
4396 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4398 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4399 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4400 $fix_elements[$n + 2] =~ s/^\s+//;
4403 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4405 "space preferred before that '$op' $at\n" . $hereptr)) {
4406 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4410 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4411 if (ERROR("SPACING",
4412 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4413 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4414 if (defined $fix_elements[$n + 2]) {
4415 $fix_elements[$n + 2] =~ s/^\s+//;
4421 # A colon needs no spaces before when it is
4422 # terminating a case value or a label.
4423 } elsif ($opv eq ':C' || $opv eq ':L') {
4424 if ($ctx =~ /Wx./) {
4425 if (ERROR("SPACING",
4426 "space prohibited before that '$op' $at\n" . $hereptr)) {
4427 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4432 # All the others need spaces both sides.
4433 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4436 # Ignore email addresses <foo@bar>
4438 $cc =~ /^\S+\@\S+>/) ||
4440 $ca =~ /<\S+\@\S+$/))
4445 # for asm volatile statements
4446 # ignore a colon with another
4447 # colon immediately before or after
4449 ($ca =~ /:$/ || $cc =~ /^:/)) {
4453 # messages are ERROR, but ?: are CHK
4455 my $msg_level = \&ERROR;
4456 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4458 if (&{$msg_level}("SPACING",
4459 "spaces required around that '$op' $at\n" . $hereptr)) {
4460 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4461 if (defined $fix_elements[$n + 2]) {
4462 $fix_elements[$n + 2] =~ s/^\s+//;
4468 $off += length($elements[$n + 1]);
4470 ## print("n: <$n> GOOD: <$good>\n");
4472 $fixed_line = $fixed_line . $good;
4475 if (($#elements % 2) == 0) {
4476 $fixed_line = $fixed_line . $fix_elements[$#elements];
4479 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4480 $fixed[$fixlinenr] = $fixed_line;
4486 # check for whitespace before a non-naked semicolon
4487 if ($line =~ /^\+.*\S\s+;\s*$/) {
4489 "space prohibited before semicolon\n" . $herecurr) &&
4491 1 while $fixed[$fixlinenr] =~
4492 s/^(\+.*\S)\s+;/$1;/;
4496 # check for multiple assignments
4497 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4498 CHK("MULTIPLE_ASSIGNMENTS",
4499 "multiple assignments should be avoided\n" . $herecurr);
4502 ## # check for multiple declarations, allowing for a function declaration
4504 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4505 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4507 ## # Remove any bracketed sections to ensure we do not
4508 ## # falsly report the parameters of functions.
4510 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4512 ## if ($ln =~ /,/) {
4513 ## WARN("MULTIPLE_DECLARATION",
4514 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4518 #need space before brace following if, while, etc
4519 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4521 if (ERROR("SPACING",
4522 "space required before the open brace '{'\n" . $herecurr) &&
4524 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\)))\{/$1 {/;
4528 ## # check for blank lines before declarations
4529 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4530 ## $prevrawline =~ /^.\s*$/) {
4532 ## "No blank lines before declarations\n" . $hereprev);
4536 # closing brace should have a space following it when it has anything
4538 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4539 if (ERROR("SPACING",
4540 "space required after that close brace '}'\n" . $herecurr) &&
4542 $fixed[$fixlinenr] =~
4543 s/}((?!(?:,|;|\)))\S)/} $1/;
4547 # check spacing on square brackets
4548 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4549 if (ERROR("SPACING",
4550 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4552 $fixed[$fixlinenr] =~
4556 if ($line =~ /\s\]/) {
4557 if (ERROR("SPACING",
4558 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4560 $fixed[$fixlinenr] =~
4565 # check spacing on parentheses
4566 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4567 $line !~ /for\s*\(\s+;/) {
4568 if (ERROR("SPACING",
4569 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4571 $fixed[$fixlinenr] =~
4575 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4576 $line !~ /for\s*\(.*;\s+\)/ &&
4577 $line !~ /:\s+\)/) {
4578 if (ERROR("SPACING",
4579 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4581 $fixed[$fixlinenr] =~
4586 # check unnecessary parentheses around addressof/dereference single $Lvals
4587 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4589 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4591 if (CHK("UNNECESSARY_PARENTHESES",
4592 "Unnecessary parentheses around $var\n" . $herecurr) &&
4594 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4598 # check for unnecessary parentheses around function pointer uses
4599 # ie: (foo->bar)(); should be foo->bar();
4600 # but not "if (foo->bar) (" to avoid some false positives
4601 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4603 if (CHK("UNNECESSARY_PARENTHESES",
4604 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4606 my $var2 = deparenthesize($var);
4608 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4612 # check for unnecessary parentheses around comparisons in if uses
4613 # when !drivers/staging or command-line uses --strict
4614 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4615 $perl_version_ok && defined($stat) &&
4616 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4618 my $test = substr($2, 1, -1);
4620 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4622 # avoid parentheses around potential macro args
4623 next if ($match =~ /^\s*\w+\s*$/);
4624 if (!defined($herectx)) {
4625 $herectx = $here . "\n";
4626 my $cnt = statement_rawlines($if_stat);
4627 for (my $n = 0; $n < $cnt; $n++) {
4628 my $rl = raw_line($linenr, $n);
4629 $herectx .= $rl . "\n";
4630 last if $rl =~ /^[ \+].*\{/;
4633 CHK("UNNECESSARY_PARENTHESES",
4634 "Unnecessary parentheses around '$match'\n" . $herectx);
4638 #goto labels aren't indented, allow a single space however
4639 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4640 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4641 if (WARN("INDENTED_LABEL",
4642 "labels should not be indented\n" . $herecurr) &&
4644 $fixed[$fixlinenr] =~
4649 # return is not a function
4650 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4652 if ($perl_version_ok &&
4653 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4655 $value = deparenthesize($value);
4656 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4657 ERROR("RETURN_PARENTHESES",
4658 "return is not a function, parentheses are not required\n" . $herecurr);
4660 } elsif ($spacing !~ /\s+/) {
4662 "space required before the open parenthesis '('\n" . $herecurr);
4666 # unnecessary return in a void function
4667 # at end-of-function, with the previous line a single leading tab, then return;
4668 # and the line before that not a goto label target like "out:"
4669 if ($sline =~ /^[ \+]}\s*$/ &&
4670 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4672 $lines[$linenr - 3] =~ /^[ +]/ &&
4673 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4675 "void function return statements are not generally useful\n" . $hereprev);
4678 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4679 if ($perl_version_ok &&
4680 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4681 my $openparens = $1;
4682 my $count = $openparens =~ tr@\(@\(@;
4684 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4685 my $comp = $4; #Not $1 because of $LvalOrFunc
4686 $msg = " - maybe == should be = ?" if ($comp eq "==");
4687 WARN("UNNECESSARY_PARENTHESES",
4688 "Unnecessary parentheses$msg\n" . $herecurr);
4692 # comparisons with a constant or upper case identifier on the left
4693 # avoid cases like "foo + BAR < baz"
4694 # only fix matches surrounded by parentheses to avoid incorrect
4695 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4696 if ($perl_version_ok &&
4697 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4702 my $newcomp = $comp;
4703 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4704 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4705 WARN("CONSTANT_COMPARISON",
4706 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4710 } elsif ($comp eq "<=") {
4712 } elsif ($comp eq ">") {
4714 } elsif ($comp eq ">=") {
4717 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4721 # Return of what appears to be an errno should normally be negative
4722 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4724 if ($name ne 'EOF' && $name ne 'ERROR') {
4725 WARN("USE_NEGATIVE_ERRNO",
4726 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4730 # Need a space before open parenthesis after if, while etc
4731 if ($line =~ /\b(if|while|for|switch)\(/) {
4732 if (ERROR("SPACING",
4733 "space required before the open parenthesis '('\n" . $herecurr) &&
4735 $fixed[$fixlinenr] =~
4736 s/\b(if|while|for|switch)\(/$1 \(/;
4740 # Check for illegal assignment in if conditional -- and check for trailing
4741 # statements after the conditional.
4742 if ($line =~ /do\s*(?!{)/) {
4743 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4744 ctx_statement_block($linenr, $realcnt, 0)
4745 if (!defined $stat);
4746 my ($stat_next) = ctx_statement_block($line_nr_next,
4747 $remain_next, $off_next);
4748 $stat_next =~ s/\n./\n /g;
4749 ##print "stat<$stat> stat_next<$stat_next>\n";
4751 if ($stat_next =~ /^\s*while\b/) {
4752 # If the statement carries leading newlines,
4753 # then count those as offsets.
4755 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4757 statement_rawlines($whitespace) - 1;
4759 $suppress_whiletrailers{$line_nr_next +
4763 if (!defined $suppress_whiletrailers{$linenr} &&
4764 defined($stat) && defined($cond) &&
4765 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4766 my ($s, $c) = ($stat, $cond);
4768 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4769 ERROR("ASSIGN_IN_IF",
4770 "do not use assignment in if condition\n" . $herecurr);
4773 # Find out what is on the end of the line after the
4775 substr($s, 0, length($c), '');
4777 $s =~ s/$;//g; # Remove any comments
4778 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4779 $c !~ /}\s*while\s*/)
4781 # Find out how long the conditional actually is.
4782 my @newlines = ($c =~ /\n/gs);
4783 my $cond_lines = 1 + $#newlines;
4786 $stat_real = raw_line($linenr, $cond_lines)
4787 . "\n" if ($cond_lines);
4788 if (defined($stat_real) && $cond_lines > 1) {
4789 $stat_real = "[...]\n$stat_real";
4792 ERROR("TRAILING_STATEMENTS",
4793 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4797 # Check for bitwise tests written as boolean
4809 WARN("HEXADECIMAL_BOOLEAN_TEST",
4810 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4813 # if and else should not have general statements after it
4814 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4816 $s =~ s/$;//g; # Remove any comments
4817 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4818 ERROR("TRAILING_STATEMENTS",
4819 "trailing statements should be on next line\n" . $herecurr);
4822 # if should not continue a brace
4823 if ($line =~ /}\s*if\b/) {
4824 ERROR("TRAILING_STATEMENTS",
4825 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4828 # case and default should not have general statements after them
4829 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4831 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4835 ERROR("TRAILING_STATEMENTS",
4836 "trailing statements should be on next line\n" . $herecurr);
4839 # Check for }<nl>else {, these must be at the same
4840 # indent level to be relevant to each other.
4841 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4842 $previndent == $indent) {
4843 if (ERROR("ELSE_AFTER_BRACE",
4844 "else should follow close brace '}'\n" . $hereprev) &&
4845 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4846 fix_delete_line($fixlinenr - 1, $prevrawline);
4847 fix_delete_line($fixlinenr, $rawline);
4848 my $fixedline = $prevrawline;
4849 $fixedline =~ s/}\s*$//;
4850 if ($fixedline !~ /^\+\s*$/) {
4851 fix_insert_line($fixlinenr, $fixedline);
4853 $fixedline = $rawline;
4854 $fixedline =~ s/^(.\s*)else/$1} else/;
4855 fix_insert_line($fixlinenr, $fixedline);
4859 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4860 $previndent == $indent) {
4861 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4863 # Find out what is on the end of the line after the
4865 substr($s, 0, length($c), '');
4868 if ($s =~ /^\s*;/) {
4869 if (ERROR("WHILE_AFTER_BRACE",
4870 "while should follow close brace '}'\n" . $hereprev) &&
4871 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4872 fix_delete_line($fixlinenr - 1, $prevrawline);
4873 fix_delete_line($fixlinenr, $rawline);
4874 my $fixedline = $prevrawline;
4875 my $trailing = $rawline;
4876 $trailing =~ s/^\+//;
4877 $trailing = trim($trailing);
4878 $fixedline =~ s/}\s*$/} $trailing/;
4879 fix_insert_line($fixlinenr, $fixedline);
4884 #Specific variable tests
4885 while ($line =~ m{($Constant|$Lval)}g) {
4888 #gcc binary extension
4889 if ($var =~ /^$Binary$/) {
4890 if (WARN("GCC_BINARY_CONSTANT",
4891 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4893 my $hexval = sprintf("0x%x", oct($var));
4894 $fixed[$fixlinenr] =~
4895 s/\b$var\b/$hexval/;
4900 if ($var !~ /^$Constant$/ &&
4901 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4902 #Ignore Page<foo> variants
4903 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4904 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4905 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4906 #Ignore some three character SI units explicitly, like MiB and KHz
4907 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4908 while ($var =~ m{($Ident)}g) {
4910 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4912 seed_camelcase_includes();
4913 if (!$file && !$camelcase_file_seeded) {
4914 seed_camelcase_file($realfile);
4915 $camelcase_file_seeded = 1;
4918 if (!defined $camelcase{$word}) {
4919 $camelcase{$word} = 1;
4921 "Avoid CamelCase: <$word>\n" . $herecurr);
4927 #no spaces allowed after \ in define
4928 if ($line =~ /\#\s*define.*\\\s+$/) {
4929 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4930 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4932 $fixed[$fixlinenr] =~ s/\s+$//;
4936 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4937 # itself <asm/foo.h> (uses RAW line)
4938 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4940 my $checkfile = "include/linux/$file";
4941 if (-f "$root/$checkfile" &&
4942 $realfile ne $checkfile &&
4943 $1 !~ /$allowed_asm_includes/)
4945 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4946 if ($asminclude > 0) {
4947 if ($realfile =~ m{^arch/}) {
4948 CHK("ARCH_INCLUDE_LINUX",
4949 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4951 WARN("INCLUDE_LINUX",
4952 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4958 # multi-statement macros should be enclosed in a do while loop, grab the
4959 # first statement and ensure its the whole macro if its not enclosed
4960 # in a known good container
4961 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4962 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4965 my ($off, $dstat, $dcond, $rest);
4967 my $has_flow_statement = 0;
4968 my $has_arg_concat = 0;
4969 ($dstat, $dcond, $ln, $cnt, $off) =
4970 ctx_statement_block($linenr, $realcnt, 0);
4972 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4973 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4975 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4976 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
4978 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
4979 my $define_args = $1;
4980 my $define_stmt = $dstat;
4983 if (defined $define_args && $define_args ne "") {
4984 $define_args = substr($define_args, 1, length($define_args) - 2);
4985 $define_args =~ s/\s*//g;
4986 $define_args =~ s/\\\+?//g;
4987 @def_args = split(",", $define_args);
4991 $dstat =~ s/\\\n.//g;
4992 $dstat =~ s/^\s*//s;
4993 $dstat =~ s/\s*$//s;
4995 # Flatten any parentheses and braces
4996 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4997 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4998 $dstat =~ s/.\[[^\[\]]*\]/1/)
5002 # Flatten any obvious string concatentation.
5003 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5004 $dstat =~ s/$Ident\s*($String)/$1/)
5008 # Make asm volatile uses seem like a generic function
5009 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5011 my $exceptions = qr{
5024 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5027 my $stmt_cnt = statement_rawlines($ctx);
5028 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5031 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5032 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5033 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5034 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5035 $dstat !~ /$exceptions/ &&
5036 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5037 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5038 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5039 $dstat !~ /^for\s*$Constant$/ && # for (...)
5040 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5041 $dstat !~ /^do\s*{/ && # do {...
5042 $dstat !~ /^\(\{/ && # ({...
5043 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5045 if ($dstat =~ /^\s*if\b/) {
5046 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5047 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5048 } elsif ($dstat =~ /;/) {
5049 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5050 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5052 ERROR("COMPLEX_MACRO",
5053 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5058 # Make $define_stmt single line, comment-free, etc
5059 my @stmt_array = split('\n', $define_stmt);
5062 foreach my $l (@stmt_array) {
5067 } elsif ($l =~ /^[\+ ]/) {
5068 $define_stmt .= substr($l, 1);
5071 $define_stmt =~ s/$;//g;
5072 $define_stmt =~ s/\s+/ /g;
5073 $define_stmt = trim($define_stmt);
5075 # check if any macro arguments are reused (ignore '...' and 'type')
5076 foreach my $arg (@def_args) {
5077 next if ($arg =~ /\.\.\./);
5078 next if ($arg =~ /^type$/i);
5079 my $tmp_stmt = $define_stmt;
5080 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5081 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5082 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5083 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5085 CHK("MACRO_ARG_REUSE",
5086 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5088 # check if any macro arguments may have other precedence issues
5089 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5090 ((defined($1) && $1 ne ',') ||
5091 (defined($2) && $2 ne ','))) {
5092 CHK("MACRO_ARG_PRECEDENCE",
5093 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5097 # check for macros with flow control, but without ## concatenation
5098 # ## concatenation is commonly a macro that defines a function so ignore those
5099 if ($has_flow_statement && !$has_arg_concat) {
5100 my $cnt = statement_rawlines($ctx);
5101 my $herectx = get_stat_here($linenr, $cnt, $here);
5103 WARN("MACRO_WITH_FLOW_CONTROL",
5104 "Macros with flow control statements should be avoided\n" . "$herectx");
5107 # check for line continuations outside of #defines, preprocessor #, and asm
5110 if ($prevline !~ /^..*\\$/ &&
5111 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5112 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5113 $line =~ /^\+.*\\$/) {
5114 WARN("LINE_CONTINUATIONS",
5115 "Avoid unnecessary line continuations\n" . $herecurr);
5119 # do {} while (0) macro tests:
5120 # single-statement macros do not need to be enclosed in do while (0) loop,
5121 # macro should not end with a semicolon
5122 if ($perl_version_ok &&
5123 $realfile !~ m@/vmlinux.lds.h$@ &&
5124 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5127 my ($off, $dstat, $dcond, $rest);
5129 ($dstat, $dcond, $ln, $cnt, $off) =
5130 ctx_statement_block($linenr, $realcnt, 0);
5133 $dstat =~ s/\\\n.//g;
5136 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5141 my $cnt = statement_rawlines($ctx);
5142 my $herectx = get_stat_here($linenr, $cnt, $here);
5144 if (($stmts =~ tr/;/;/) == 1 &&
5145 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5146 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5147 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5149 if (defined $semis && $semis ne "") {
5150 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5151 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5153 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5155 my $cnt = statement_rawlines($ctx);
5156 my $herectx = get_stat_here($linenr, $cnt, $here);
5158 WARN("TRAILING_SEMICOLON",
5159 "macros should not use a trailing semicolon\n" . "$herectx");
5163 # check for redundant bracing round if etc
5164 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5165 my ($level, $endln, @chunks) =
5166 ctx_statement_full($linenr, $realcnt, 1);
5167 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5168 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5169 if ($#chunks > 0 && $level == 0) {
5173 my $herectx = $here . "\n";
5174 my $ln = $linenr - 1;
5175 for my $chunk (@chunks) {
5176 my ($cond, $block) = @{$chunk};
5178 # If the condition carries leading newlines, then count those as offsets.
5179 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5180 my $offset = statement_rawlines($whitespace) - 1;
5182 $allowed[$allow] = 0;
5183 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5185 # We have looked at and allowed this specific line.
5186 $suppress_ifbraces{$ln + $offset} = 1;
5188 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5189 $ln += statement_rawlines($block) - 1;
5191 substr($block, 0, length($cond), '');
5193 $seen++ if ($block =~ /^\s*{/);
5195 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5196 if (statement_lines($cond) > 1) {
5197 #print "APW: ALLOWED: cond<$cond>\n";
5198 $allowed[$allow] = 1;
5200 if ($block =~/\b(?:if|for|while)\b/) {
5201 #print "APW: ALLOWED: block<$block>\n";
5202 $allowed[$allow] = 1;
5204 if (statement_block_size($block) > 1) {
5205 #print "APW: ALLOWED: lines block<$block>\n";
5206 $allowed[$allow] = 1;
5211 my $sum_allowed = 0;
5212 foreach (@allowed) {
5215 if ($sum_allowed == 0) {
5217 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5218 } elsif ($sum_allowed != $allow &&
5221 "braces {} should be used on all arms of this statement\n" . $herectx);
5226 if (!defined $suppress_ifbraces{$linenr - 1} &&
5227 $line =~ /\b(if|while|for|else)\b/) {
5230 # Check the pre-context.
5231 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5232 #print "APW: ALLOWED: pre<$1>\n";
5236 my ($level, $endln, @chunks) =
5237 ctx_statement_full($linenr, $realcnt, $-[0]);
5239 # Check the condition.
5240 my ($cond, $block) = @{$chunks[0]};
5241 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5242 if (defined $cond) {
5243 substr($block, 0, length($cond), '');
5245 if (statement_lines($cond) > 1) {
5246 #print "APW: ALLOWED: cond<$cond>\n";
5249 if ($block =~/\b(?:if|for|while)\b/) {
5250 #print "APW: ALLOWED: block<$block>\n";
5253 if (statement_block_size($block) > 1) {
5254 #print "APW: ALLOWED: lines block<$block>\n";
5257 # Check the post-context.
5258 if (defined $chunks[1]) {
5259 my ($cond, $block) = @{$chunks[1]};
5260 if (defined $cond) {
5261 substr($block, 0, length($cond), '');
5263 if ($block =~ /^\s*\{/) {
5264 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5268 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5269 my $cnt = statement_rawlines($block);
5270 my $herectx = get_stat_here($linenr, $cnt, $here);
5273 "braces {} are not necessary for single statement blocks\n" . $herectx);
5277 # check for single line unbalanced braces
5278 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5279 $sline =~ /^.\s*else\s*\{\s*$/) {
5280 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5283 # check for unnecessary blank lines around braces
5284 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5286 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5287 $fix && $prevrawline =~ /^\+/) {
5288 fix_delete_line($fixlinenr - 1, $prevrawline);
5291 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5293 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5295 fix_delete_line($fixlinenr, $rawline);
5299 # no volatiles please
5300 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5301 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5303 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5306 # Check for user-visible strings broken across lines, which breaks the ability
5307 # to grep for the string. Make exceptions when the previous string ends in a
5308 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5309 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5310 if ($line =~ /^\+\s*$String/ &&
5311 $prevline =~ /"\s*$/ &&
5312 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5313 if (WARN("SPLIT_STRING",
5314 "quoted string split across lines\n" . $hereprev) &&
5316 $prevrawline =~ /^\+.*"\s*$/ &&
5317 $last_coalesced_string_linenr != $linenr - 1) {
5318 my $extracted_string = get_quoted_string($line, $rawline);
5319 my $comma_close = "";
5320 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5324 fix_delete_line($fixlinenr - 1, $prevrawline);
5325 fix_delete_line($fixlinenr, $rawline);
5326 my $fixedline = $prevrawline;
5327 $fixedline =~ s/"\s*$//;
5328 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5329 fix_insert_line($fixlinenr - 1, $fixedline);
5330 $fixedline = $rawline;
5331 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5332 if ($fixedline !~ /\+\s*$/) {
5333 fix_insert_line($fixlinenr, $fixedline);
5335 $last_coalesced_string_linenr = $linenr;
5339 # check for missing a space in a string concatenation
5340 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5341 WARN('MISSING_SPACE',
5342 "break quoted strings at a space character\n" . $hereprev);
5345 # check for an embedded function name in a string when the function is known
5346 # This does not work very well for -f --file checking as it depends on patch
5347 # context providing the function name or a single line form for in-file
5348 # function declarations
5349 if ($line =~ /^\+.*$String/ &&
5350 defined($context_function) &&
5351 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5352 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5353 WARN("EMBEDDED_FUNCTION_NAME",
5354 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5357 # check for spaces before a quoted newline
5358 if ($rawline =~ /^.*\".*\s\\n/) {
5359 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5360 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5362 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5367 # concatenated string without spaces between elements
5368 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5369 if (CHK("CONCATENATED_STRING",
5370 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5372 while ($line =~ /($String)/g) {
5373 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5374 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5375 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5380 # uncoalesced string fragments
5381 if ($line =~ /$String\s*"/) {
5382 if (WARN("STRING_FRAGMENTS",
5383 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5385 while ($line =~ /($String)(?=\s*")/g) {
5386 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5387 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5392 # check for non-standard and hex prefixed decimal printf formats
5393 my $show_L = 1; #don't show the same defect twice
5395 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5396 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5397 $string =~ s/%%/__/g;
5399 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5401 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5405 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5407 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5410 # check for 0x<decimal>
5411 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5412 ERROR("PRINTF_0XDECIMAL",
5413 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5417 # check for line continuations in quoted strings with odd counts of "
5418 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5419 WARN("LINE_CONTINUATIONS",
5420 "Avoid line continuations in quoted strings\n" . $herecurr);
5424 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5425 CHK("REDUNDANT_CODE",
5426 "if this code is redundant consider removing it\n" .
5430 # check for needless "if (<foo>) fn(<foo>)" uses
5431 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5432 my $tested = quotemeta($1);
5433 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5434 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5436 if (WARN('NEEDLESS_IF',
5437 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5440 my $leading_tabs = "";
5441 my $new_leading_tabs = "";
5442 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5447 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5448 $new_leading_tabs = $1;
5449 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5456 fix_delete_line($fixlinenr - 1, $prevrawline);
5457 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5463 # check for unnecessary "Out of Memory" messages
5464 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5465 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5466 (defined $1 || defined $3) &&
5469 my $testline = $lines[$linenr - 3];
5471 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5472 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5474 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|kmemdup|(?:dev_)?alloc_skb)/) {
5476 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5480 # check for logging functions with KERN_<LEVEL>
5481 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5482 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5484 if (WARN("UNNECESSARY_KERN_LEVEL",
5485 "Possible unnecessary $level\n" . $herecurr) &&
5487 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5491 # check for logging continuations
5492 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5493 WARN("LOGGING_CONTINUATION",
5494 "Avoid logging continuation uses where feasible\n" . $herecurr);
5497 # check for mask then right shift without a parentheses
5498 if ($perl_version_ok &&
5499 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5500 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5501 WARN("MASK_THEN_SHIFT",
5502 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5505 # check for pointer comparisons to NULL
5506 if ($perl_version_ok) {
5507 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5510 $equal = "" if ($4 eq "!=");
5511 if (CHK("COMPARISON_TO_NULL",
5512 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5514 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5519 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5520 if ($line =~ /(\b$InitAttribute\b)/) {
5522 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5525 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5526 ERROR("MISPLACED_INIT",
5527 "$attr should be placed after $var\n" . $herecurr)) ||
5528 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5529 WARN("MISPLACED_INIT",
5530 "$attr should be placed after $var\n" . $herecurr))) &&
5532 $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;
5537 # check for $InitAttributeData (ie: __initdata) with const
5538 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5540 $attr =~ /($InitAttributePrefix)(.*)/;
5541 my $attr_prefix = $1;
5543 if (ERROR("INIT_ATTRIBUTE",
5544 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5546 $fixed[$fixlinenr] =~
5547 s/$InitAttributeData/${attr_prefix}initconst/;
5551 # check for $InitAttributeConst (ie: __initconst) without const
5552 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5554 if (ERROR("INIT_ATTRIBUTE",
5555 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5557 my $lead = $fixed[$fixlinenr] =~
5558 /(^\+\s*(?:static\s+))/;
5560 $lead = "$lead " if ($lead !~ /^\+$/);
5561 $lead = "${lead}const ";
5562 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5566 # check for __read_mostly with const non-pointer (should just be const)
5567 if ($line =~ /\b__read_mostly\b/ &&
5568 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5569 if (ERROR("CONST_READ_MOSTLY",
5570 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5572 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5576 # don't use __constant_<foo> functions outside of include/uapi/
5577 if ($realfile !~ m@^include/uapi/@ &&
5578 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5579 my $constant_func = $1;
5580 my $func = $constant_func;
5581 $func =~ s/^__constant_//;
5582 if (WARN("CONSTANT_CONVERSION",
5583 "$constant_func should be $func\n" . $herecurr) &&
5585 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5589 # prefer usleep_range over udelay
5590 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5592 # ignore udelay's < 10, however
5593 if (! ($delay < 10) ) {
5595 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5597 if ($delay > 2000) {
5599 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5603 # warn about unexpectedly long msleep's
5604 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5607 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5611 # check for comparisons of jiffies
5612 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5613 WARN("JIFFIES_COMPARISON",
5614 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5617 # check for comparisons of get_jiffies_64()
5618 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5619 WARN("JIFFIES_COMPARISON",
5620 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5623 # warn about #ifdefs in C files
5624 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5625 # print "#ifdef in C files should be avoided\n";
5626 # print "$herecurr";
5630 # warn about spacing in #ifdefs
5631 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5632 if (ERROR("SPACING",
5633 "exactly one space required after that #$1\n" . $herecurr) &&
5635 $fixed[$fixlinenr] =~
5636 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5641 # check for spinlock_t definitions without a comment.
5642 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5643 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5645 if (!ctx_has_comment($first_line, $linenr)) {
5646 CHK("UNCOMMENTED_DEFINITION",
5647 "$1 definition without comment\n" . $herecurr);
5650 # check for memory barriers without a comment.
5656 read_barrier_depends
5658 my $barrier_stems = qr{
5666 my $all_barriers = qr{
5668 smp_(?:$barrier_stems)|
5669 virt_(?:$barrier_stems)
5672 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5673 if (!ctx_has_comment($first_line, $linenr)) {
5674 WARN("MEMORY_BARRIER",
5675 "memory barrier without comment\n" . $herecurr);
5679 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5681 if ($realfile !~ m@^include/asm-generic/@ &&
5682 $realfile !~ m@/barrier\.h$@ &&
5683 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5684 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5685 WARN("MEMORY_BARRIER",
5686 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5689 # check for waitqueue_active without a comment.
5690 if ($line =~ /\bwaitqueue_active\s*\(/) {
5691 if (!ctx_has_comment($first_line, $linenr)) {
5692 WARN("WAITQUEUE_ACTIVE",
5693 "waitqueue_active without comment\n" . $herecurr);
5697 # check for smp_read_barrier_depends and read_barrier_depends
5698 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5699 WARN("READ_BARRIER_DEPENDS",
5700 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5703 # check of hardware specific defines
5704 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5706 "architecture specific defines should be avoided\n" . $herecurr);
5709 # check that the storage class is not after a type
5710 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5711 WARN("STORAGE_CLASS",
5712 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5714 # Check that the storage class is at the beginning of a declaration
5715 if ($line =~ /\b$Storage\b/ &&
5716 $line !~ /^.\s*$Storage/ &&
5717 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5718 $1 !~ /[\,\)]\s*$/) {
5719 WARN("STORAGE_CLASS",
5720 "storage class should be at the beginning of the declaration\n" . $herecurr);
5723 # check the location of the inline attribute, that it is between
5724 # storage class and type.
5725 if ($line =~ /\b$Type\s+$Inline\b/ ||
5726 $line =~ /\b$Inline\s+$Storage\b/) {
5727 ERROR("INLINE_LOCATION",
5728 "inline keyword should sit between storage class and type\n" . $herecurr);
5731 # Check for __inline__ and __inline, prefer inline
5732 if ($realfile !~ m@\binclude/uapi/@ &&
5733 $line =~ /\b(__inline__|__inline)\b/) {
5735 "plain inline is preferred over $1\n" . $herecurr) &&
5737 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5742 # Check for __attribute__ packed, prefer __packed
5743 if ($realfile !~ m@\binclude/uapi/@ &&
5744 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5745 WARN("PREFER_PACKED",
5746 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5749 # Check for __attribute__ aligned, prefer __aligned
5750 if ($realfile !~ m@\binclude/uapi/@ &&
5751 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5752 WARN("PREFER_ALIGNED",
5753 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5756 # Check for __attribute__ format(printf, prefer __printf
5757 if ($realfile !~ m@\binclude/uapi/@ &&
5758 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5759 if (WARN("PREFER_PRINTF",
5760 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5762 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5767 # Check for __attribute__ format(scanf, prefer __scanf
5768 if ($realfile !~ m@\binclude/uapi/@ &&
5769 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5770 if (WARN("PREFER_SCANF",
5771 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5773 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5777 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5778 if ($perl_version_ok &&
5779 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5780 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5781 $line =~ /\b__weak\b/)) {
5782 ERROR("WEAK_DECLARATION",
5783 "Using weak declarations can have unintended link defects\n" . $herecurr);
5786 # check for c99 types like uint8_t used outside of uapi/ and tools/
5787 if ($realfile !~ m@\binclude/uapi/@ &&
5788 $realfile !~ m@\btools/@ &&
5789 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5791 if ($type =~ /\b($typeC99Typedefs)\b/) {
5793 my $kernel_type = 'u';
5794 $kernel_type = 's' if ($type =~ /^_*[si]/);
5797 if (CHK("PREFER_KERNEL_TYPES",
5798 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5800 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5805 # check for cast of C90 native int or longer types constants
5806 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5809 if (WARN("TYPECAST_INT_CONSTANT",
5810 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5813 my $newconst = $const;
5814 $newconst =~ s/${Int_type}$//;
5815 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5816 if ($cast =~ /\blong\s+long\b/) {
5818 } elsif ($cast =~ /\blong\b/) {
5821 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5825 # check for sizeof(&)
5826 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5827 WARN("SIZEOF_ADDRESS",
5828 "sizeof(& should be avoided\n" . $herecurr);
5831 # check for sizeof without parenthesis
5832 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5833 if (WARN("SIZEOF_PARENTHESIS",
5834 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5836 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5840 # check for struct spinlock declarations
5841 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5842 WARN("USE_SPINLOCK_T",
5843 "struct spinlock should be spinlock_t\n" . $herecurr);
5846 # check for seq_printf uses that could be seq_puts
5847 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5848 my $fmt = get_quoted_string($line, $rawline);
5851 if (WARN("PREFER_SEQ_PUTS",
5852 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5854 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5859 # check for vsprintf extension %p<foo> misuses
5860 if ($perl_version_ok &&
5862 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5863 $1 !~ /^_*volatile_*$/) {
5866 my $lc = $stat =~ tr@\n@@;
5867 $lc = $lc + $linenr;
5868 for (my $count = $linenr; $count <= $lc; $count++) {
5871 my $bad_specifier = "";
5872 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5875 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5878 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5879 $bad_specifier = $specifier;
5882 if ($extension eq "x" && !defined($stat_real)) {
5883 if (!defined($stat_real)) {
5884 $stat_real = get_stat_real($linenr, $lc);
5886 WARN("VSPRINTF_SPECIFIER_PX",
5887 "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");
5890 if ($bad_specifier ne "") {
5891 my $stat_real = get_stat_real($linenr, $lc);
5892 my $ext_type = "Invalid";
5894 if ($bad_specifier =~ /p[Ff]/) {
5895 $ext_type = "Deprecated";
5896 $use = " - use %pS instead";
5897 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5900 WARN("VSPRINTF_POINTER_EXTENSION",
5901 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5906 # Check for misused memsets
5907 if ($perl_version_ok &&
5909 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5915 if ($ms_size =~ /^(0x|)0$/i) {
5917 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5918 } elsif ($ms_size =~ /^(0x|)1$/i) {
5920 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5924 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5925 # if ($perl_version_ok &&
5927 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5928 # if (WARN("PREFER_ETHER_ADDR_COPY",
5929 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5931 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5935 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5936 # if ($perl_version_ok &&
5938 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5939 # WARN("PREFER_ETHER_ADDR_EQUAL",
5940 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5943 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5944 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5945 # if ($perl_version_ok &&
5947 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5951 # if ($ms_val =~ /^(?:0x|)0+$/i) {
5952 # if (WARN("PREFER_ETH_ZERO_ADDR",
5953 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5955 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5957 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5958 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
5959 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
5961 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
5966 # typecasts on min/max could be min_t/max_t
5967 if ($perl_version_ok &&
5969 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5970 if (defined $2 || defined $7) {
5972 my $cast1 = deparenthesize($2);
5974 my $cast2 = deparenthesize($7);
5978 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5979 $cast = "$cast1 or $cast2";
5980 } elsif ($cast1 ne "") {
5986 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5990 # check usleep_range arguments
5991 if ($perl_version_ok &&
5993 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5997 WARN("USLEEP_RANGE",
5998 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5999 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6001 WARN("USLEEP_RANGE",
6002 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6006 # check for naked sscanf
6007 if ($perl_version_ok &&
6009 $line =~ /\bsscanf\b/ &&
6010 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6011 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6012 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6013 my $lc = $stat =~ tr@\n@@;
6014 $lc = $lc + $linenr;
6015 my $stat_real = get_stat_real($linenr, $lc);
6016 WARN("NAKED_SSCANF",
6017 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6020 # check for simple sscanf that should be kstrto<foo>
6021 if ($perl_version_ok &&
6023 $line =~ /\bsscanf\b/) {
6024 my $lc = $stat =~ tr@\n@@;
6025 $lc = $lc + $linenr;
6026 my $stat_real = get_stat_real($linenr, $lc);
6027 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6029 my $count = $format =~ tr@%@%@;
6031 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6032 WARN("SSCANF_TO_KSTRTO",
6033 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6038 # check for new externs in .h files.
6039 if ($realfile =~ /\.h$/ &&
6040 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6041 if (CHK("AVOID_EXTERNS",
6042 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6044 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6048 # check for new externs in .c files.
6049 if ($realfile =~ /\.c$/ && defined $stat &&
6050 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6052 my $function_name = $1;
6053 my $paren_space = $2;
6056 if (defined $cond) {
6057 substr($s, 0, length($cond), '');
6059 if ($s =~ /^\s*;/ &&
6060 $function_name ne 'uninitialized_var')
6062 WARN("AVOID_EXTERNS",
6063 "externs should be avoided in .c files\n" . $herecurr);
6066 if ($paren_space =~ /\n/) {
6067 WARN("FUNCTION_ARGUMENTS",
6068 "arguments for function declarations should follow identifier\n" . $herecurr);
6071 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6072 $stat =~ /^.\s*extern\s+/)
6074 WARN("AVOID_EXTERNS",
6075 "externs should be avoided in .c files\n" . $herecurr);
6078 # check for function declarations that have arguments without identifier names
6079 if (defined $stat &&
6080 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6082 my $args = trim($1);
6083 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6085 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6086 WARN("FUNCTION_ARGUMENTS",
6087 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6092 # check for function definitions
6093 if ($perl_version_ok &&
6095 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6096 $context_function = $1;
6098 # check for multiline function definition with misplaced open brace
6100 my $cnt = statement_rawlines($stat);
6101 my $herectx = $here . "\n";
6102 for (my $n = 0; $n < $cnt; $n++) {
6103 my $rl = raw_line($linenr, $n);
6104 $herectx .= $rl . "\n";
6105 $ok = 1 if ($rl =~ /^[ \+]\{/);
6106 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6107 last if $rl =~ /^[ \+].*\{/;
6111 "open brace '{' following function definitions go on the next line\n" . $herectx);
6115 # checks for new __setup's
6116 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6119 if (!grep(/$name/, @setup_docs)) {
6120 CHK("UNDOCUMENTED_SETUP",
6121 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6125 # check for pointless casting of kmalloc return
6126 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6127 WARN("UNNECESSARY_CASTS",
6128 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6132 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6133 if ($perl_version_ok &&
6134 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6135 CHK("ALLOC_SIZEOF_STRUCT",
6136 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6139 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6140 if ($perl_version_ok &&
6142 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6146 my $newfunc = "kmalloc_array";
6147 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6150 if ($a1 =~ /^sizeof\s*\S/) {
6154 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6155 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6156 my $cnt = statement_rawlines($stat);
6157 my $herectx = get_stat_here($linenr, $cnt, $here);
6159 if (WARN("ALLOC_WITH_MULTIPLY",
6160 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6163 $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;
6168 # check for krealloc arg reuse
6169 if ($perl_version_ok &&
6170 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
6171 WARN("KREALLOC_ARG_REUSE",
6172 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6175 # check for alloc argument mismatch
6176 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6177 WARN("ALLOC_ARRAY_ARGS",
6178 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6181 # check for multiple semicolons
6182 if ($line =~ /;\s*;\s*$/) {
6183 if (WARN("ONE_SEMICOLON",
6184 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6186 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6190 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6191 if ($realfile !~ m@^include/uapi/@ &&
6192 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6194 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6195 if (CHK("BIT_MACRO",
6196 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6198 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6202 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6203 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6205 if (WARN("PREFER_IS_ENABLED",
6206 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6208 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6212 # check for case / default statements not preceded by break/fallthrough/switch
6213 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6215 my $has_statement = 0;
6217 my $prevline = $linenr;
6218 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6220 my $rline = $rawlines[$prevline - 1];
6221 my $fline = $lines[$prevline - 1];
6222 last if ($fline =~ /^\@\@/);
6223 next if ($fline =~ /^\-/);
6224 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6225 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6226 next if ($fline =~ /^.[\s$;]*$/);
6229 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6231 if (!$has_break && $has_statement) {
6232 WARN("MISSING_BREAK",
6233 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6237 # check for switch/default statements without a break;
6238 if ($perl_version_ok &&
6240 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6241 my $cnt = statement_rawlines($stat);
6242 my $herectx = get_stat_here($linenr, $cnt, $here);
6244 WARN("DEFAULT_NO_BREAK",
6245 "switch default: should use break\n" . $herectx);
6248 # check for gcc specific __FUNCTION__
6249 if ($line =~ /\b__FUNCTION__\b/) {
6250 if (WARN("USE_FUNC",
6251 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6253 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6257 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6258 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6260 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6263 # check for use of yield()
6264 if ($line =~ /\byield\s*\(\s*\)/) {
6266 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6269 # check for comparisons against true and false
6270 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6278 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6280 my $type = lc($otype);
6281 if ($type =~ /^(?:true|false)$/) {
6282 if (("$test" eq "==" && "$type" eq "true") ||
6283 ("$test" eq "!=" && "$type" eq "false")) {
6287 CHK("BOOL_COMPARISON",
6288 "Using comparison to $otype is error prone\n" . $herecurr);
6290 ## maybe suggesting a correct construct would better
6291 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6296 # check for bool bitfields
6297 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6298 WARN("BOOL_BITFIELD",
6299 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6302 # check for bool use in .h files
6303 if ($realfile =~ /\.h$/ &&
6304 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6306 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6309 # check for semaphores initialized locked
6310 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6311 WARN("CONSIDER_COMPLETION",
6312 "consider using a completion\n" . $herecurr);
6315 # recommend kstrto* over simple_strto* and strict_strto*
6316 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6317 WARN("CONSIDER_KSTRTO",
6318 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6321 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6322 if ($line =~ /^.\s*__initcall\s*\(/) {
6323 WARN("USE_DEVICE_INITCALL",
6324 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6327 # check for various structs that are normally const (ops, kgdb, device_tree)
6328 # and avoid what seem like struct definitions 'struct foo {'
6329 if ($line !~ /\bconst\b/ &&
6330 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6331 WARN("CONST_STRUCT",
6332 "struct $1 should normally be const\n" . $herecurr);
6335 # use of NR_CPUS is usually wrong
6336 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6337 if ($line =~ /\bNR_CPUS\b/ &&
6338 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6339 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6340 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6341 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6342 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6345 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6348 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6349 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6350 ERROR("DEFINE_ARCH_HAS",
6351 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6354 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6355 if ($perl_version_ok &&
6356 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6357 WARN("LIKELY_MISUSE",
6358 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6361 # whine mightly about in_atomic
6362 if ($line =~ /\bin_atomic\s*\(/) {
6363 if ($realfile =~ m@^drivers/@) {
6365 "do not use in_atomic in drivers\n" . $herecurr);
6366 } elsif ($realfile !~ m@^kernel/@) {
6368 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6372 # check for mutex_trylock_recursive usage
6373 if ($line =~ /mutex_trylock_recursive/) {
6375 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6378 # check for lockdep_set_novalidate_class
6379 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6380 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6381 if ($realfile !~ m@^kernel/lockdep@ &&
6382 $realfile !~ m@^include/linux/lockdep@ &&
6383 $realfile !~ m@^drivers/base/core@) {
6385 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6389 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6390 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6391 WARN("EXPORTED_WORLD_WRITABLE",
6392 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6395 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6396 # and whether or not function naming is typical and if
6397 # DEVICE_ATTR permissions uses are unusual too
6398 if ($perl_version_ok &&
6400 $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*\)/) {
6405 my $octal_perms = perms_to_octal($perms);
6406 if ($show =~ /^${var}_show$/ &&
6407 $store =~ /^${var}_store$/ &&
6408 $octal_perms eq "0644") {
6409 if (WARN("DEVICE_ATTR_RW",
6410 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6412 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6414 } elsif ($show =~ /^${var}_show$/ &&
6415 $store =~ /^NULL$/ &&
6416 $octal_perms eq "0444") {
6417 if (WARN("DEVICE_ATTR_RO",
6418 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6420 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6422 } elsif ($show =~ /^NULL$/ &&
6423 $store =~ /^${var}_store$/ &&
6424 $octal_perms eq "0200") {
6425 if (WARN("DEVICE_ATTR_WO",
6426 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6428 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6430 } elsif ($octal_perms eq "0644" ||
6431 $octal_perms eq "0444" ||
6432 $octal_perms eq "0200") {
6433 my $newshow = "$show";
6434 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6435 my $newstore = $store;
6436 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6438 if ($show ne $newshow) {
6439 $rename .= " '$show' to '$newshow'";
6441 if ($store ne $newstore) {
6442 $rename .= " '$store' to '$newstore'";
6444 WARN("DEVICE_ATTR_FUNCTIONS",
6445 "Consider renaming function(s)$rename\n" . $herecurr);
6447 WARN("DEVICE_ATTR_PERMS",
6448 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6452 # Mode permission misuses where it seems decimal should be octal
6453 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6454 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6455 # specific definition of not visible in sysfs.
6456 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6457 # use the default permissions
6458 if ($perl_version_ok &&
6460 $line =~ /$mode_perms_search/) {
6461 foreach my $entry (@mode_permission_funcs) {
6462 my $func = $entry->[0];
6463 my $arg_pos = $entry->[1];
6465 my $lc = $stat =~ tr@\n@@;
6466 $lc = $lc + $linenr;
6467 my $stat_real = get_stat_real($linenr, $lc);
6472 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6474 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6475 if ($stat =~ /$test/) {
6477 $val = $6 if ($skip_args ne "");
6478 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6479 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6480 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6481 ERROR("NON_OCTAL_PERMISSIONS",
6482 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6484 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6485 ERROR("EXPORTED_WORLD_WRITABLE",
6486 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6492 # check for uses of S_<PERMS> that could be octal for readability
6493 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6495 my $octal = perms_to_octal($oval);
6496 if (WARN("SYMBOLIC_PERMS",
6497 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6499 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6503 # validate content of MODULE_LICENSE against list from include/linux/module.h
6504 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6505 my $extracted_string = get_quoted_string($line, $rawline);
6506 my $valid_licenses = qr{
6509 GPL\ and\ additional\ rights|
6515 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6516 WARN("MODULE_LICENSE",
6517 "unknown module license " . $extracted_string . "\n" . $herecurr);
6522 # If we have no input at all, then there is nothing to report on
6523 # so just keep quiet.
6524 if ($#rawlines == -1) {
6528 # In mailback mode only produce a report in the negative, for
6529 # things that appear to be patches.
6530 if ($mailback && ($clean == 1 || !$is_patch)) {
6534 # This is not a patch, and we are are in 'no-patch' mode so
6536 if (!$chk_patch && !$is_patch) {
6540 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6541 ERROR("NOT_UNIFIED_DIFF",
6542 "Does not appear to be a unified-diff format patch\n");
6544 if ($is_patch && $has_commit_log && $chk_signoff) {
6545 if ($signoff == 0) {
6546 ERROR("MISSING_SIGN_OFF",
6547 "Missing Signed-off-by: line(s)\n");
6548 } elsif (!$authorsignoff) {
6549 WARN("NO_AUTHOR_SIGN_OFF",
6550 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6554 print report_dump();
6555 if ($summary && !($clean == 1 && $quiet == 1)) {
6556 print "$filename " if ($summary_file);
6557 print "total: $cnt_error errors, $cnt_warn warnings, " .
6558 (($check)? "$cnt_chk checks, " : "") .
6559 "$cnt_lines lines checked\n";
6563 # If there were any defects found and not already fixing them
6564 if (!$clean and !$fix) {
6567 NOTE: For some of the reported defects, checkpatch may be able to
6568 mechanically convert to the typical style using --fix or --fix-inplace.
6571 # If there were whitespace errors which cleanpatch can fix
6572 # then suggest that.
6573 if ($rpt_cleaners) {
6577 NOTE: Whitespace errors detected.
6578 You may wish to use scripts/cleanpatch or scripts/cleanfile
6583 if ($clean == 0 && $fix &&
6584 ("@rawlines" ne "@fixed" ||
6585 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6586 my $newfile = $filename;
6587 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6591 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6593 open($f, '>', $newfile)
6594 or die "$P: Can't open $newfile for write\n";
6595 foreach my $fixed_line (@fixed) {
6598 if ($linecount > 3) {
6599 $fixed_line =~ s/^\+//;
6600 print $f $fixed_line . "\n";
6603 print $f $fixed_line . "\n";
6611 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6613 Do _NOT_ trust the results written to this file.
6614 Do _NOT_ submit these changes without inspecting them for correctness.
6616 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6617 No warranties, expressed or implied...
6625 print "$vname has no obvious style problems and is ready for submission.\n";
6627 print "$vname has style problems, please review.\n";