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
386 ____cacheline_aligned|
387 ____cacheline_aligned_in_smp|
388 ____cacheline_internodealigned_in_smp|
392 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
393 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
394 our $Lval = qr{$Ident(?:$Member)*};
396 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
397 our $Binary = qr{(?i)0b[01]+$Int_type?};
398 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
399 our $Int = qr{[0-9]+$Int_type?};
400 our $Octal = qr{0[0-7]+$Int_type?};
401 our $String = qr{"[X\t]*"};
402 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
403 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
404 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
405 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
406 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
407 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
408 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
409 our $Arithmetic = qr{\+|-|\*|\/|%};
413 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
416 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
420 our $NonptrTypeMisordered;
421 our $NonptrTypeWithAttr;
425 our $DeclareMisordered;
427 our $NON_ASCII_UTF8 = qr{
428 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
429 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
430 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
431 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
432 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
433 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
434 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
438 [\x09\x0A\x0D\x20-\x7E] # ASCII
442 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
443 our $typeOtherOSTypedefs = qr{(?x:
444 u_(?:char|short|int|long) | # bsd
445 u(?:nchar|short|int|long) # sysv
447 our $typeKernelTypedefs = qr{(?x:
448 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
451 our $typeTypedefs = qr{(?x:
453 $typeOtherOSTypedefs\b|
454 $typeKernelTypedefs\b
457 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
459 our $logFunctions = qr{(?x:
460 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
461 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
463 WARN(?:_RATELIMIT|_ONCE|)|
466 seq_vprintf|seq_printf|seq_puts
469 our $signature_tags = qr{(?xi:
480 our @typeListMisordered = (
481 qr{char\s+(?:un)?signed},
482 qr{int\s+(?:(?:un)?signed\s+)?short\s},
483 qr{int\s+short(?:\s+(?:un)?signed)},
484 qr{short\s+int(?:\s+(?:un)?signed)},
485 qr{(?:un)?signed\s+int\s+short},
486 qr{short\s+(?:un)?signed},
487 qr{long\s+int\s+(?:un)?signed},
488 qr{int\s+long\s+(?:un)?signed},
489 qr{long\s+(?:un)?signed\s+int},
490 qr{int\s+(?:un)?signed\s+long},
491 qr{int\s+(?:un)?signed},
492 qr{int\s+long\s+long\s+(?:un)?signed},
493 qr{long\s+long\s+int\s+(?:un)?signed},
494 qr{long\s+long\s+(?:un)?signed\s+int},
495 qr{long\s+long\s+(?:un)?signed},
496 qr{long\s+(?:un)?signed},
501 qr{(?:(?:un)?signed\s+)?char},
502 qr{(?:(?:un)?signed\s+)?short\s+int},
503 qr{(?:(?:un)?signed\s+)?short},
504 qr{(?:(?:un)?signed\s+)?int},
505 qr{(?:(?:un)?signed\s+)?long\s+int},
506 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
507 qr{(?:(?:un)?signed\s+)?long\s+long},
508 qr{(?:(?:un)?signed\s+)?long},
517 qr{${Ident}_handler},
518 qr{${Ident}_handler_fn},
522 our $C90_int_types = qr{(?x:
523 long\s+long\s+int\s+(?:un)?signed|
524 long\s+long\s+(?:un)?signed\s+int|
525 long\s+long\s+(?:un)?signed|
526 (?:(?:un)?signed\s+)?long\s+long\s+int|
527 (?:(?:un)?signed\s+)?long\s+long|
528 int\s+long\s+long\s+(?:un)?signed|
529 int\s+(?:(?:un)?signed\s+)?long\s+long|
531 long\s+int\s+(?:un)?signed|
532 long\s+(?:un)?signed\s+int|
533 long\s+(?:un)?signed|
534 (?:(?:un)?signed\s+)?long\s+int|
535 (?:(?:un)?signed\s+)?long|
536 int\s+long\s+(?:un)?signed|
537 int\s+(?:(?:un)?signed\s+)?long|
540 (?:(?:un)?signed\s+)?int
543 our @typeListFile = ();
544 our @typeListWithAttr = (
546 qr{struct\s+$InitAttribute\s+$Ident},
547 qr{union\s+$InitAttribute\s+$Ident},
550 our @modifierList = (
553 our @modifierListFile = ();
555 our @mode_permission_funcs = (
557 ["module_param_(?:array|named|string)", 4],
558 ["module_param_array_named", 5],
559 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
560 ["proc_create(?:_data|)", 2],
561 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
562 ["IIO_DEV_ATTR_[A-Z_]+", 1],
563 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
564 ["SENSOR_TEMPLATE(?:_2|)", 3],
568 #Create a search pattern for all these functions to speed up a loop below
569 our $mode_perms_search = "";
570 foreach my $entry (@mode_permission_funcs) {
571 $mode_perms_search .= '|' if ($mode_perms_search ne "");
572 $mode_perms_search .= $entry->[0];
574 $mode_perms_search = "(?:${mode_perms_search})";
576 our $mode_perms_world_writable = qr{
584 our %mode_permission_string_types = (
603 #Create a search pattern for all these strings to speed up a loop below
604 our $mode_perms_string_search = "";
605 foreach my $entry (keys %mode_permission_string_types) {
606 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
607 $mode_perms_string_search .= $entry;
609 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
610 our $multi_mode_perms_string_search = qr{
611 ${single_mode_perms_string_search}
612 (?:\s*\|\s*${single_mode_perms_string_search})*
618 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
625 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
626 $curpos = pos($string);
629 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
631 $to |= $mode_permission_string_types{$match};
632 $val .= '\s*\|\s*' if ($val ne "");
636 $oval =~ s/^\s*\|\s*//;
637 $oval =~ s/\s*\|\s*$//;
638 return sprintf("%04o", $to);
641 our $allowed_asm_includes = qr{(?x:
647 # memory.h: ARM has a custom one
649 # Load common spelling mistakes and build regular expression list.
653 if (open(my $spelling, '<', $spelling_file)) {
654 while (<$spelling>) {
657 $line =~ s/\s*\n?$//g;
660 next if ($line =~ m/^\s*#/);
661 next if ($line =~ m/^\s*$/);
663 my ($suspect, $fix) = split(/\|\|/, $line);
665 $spelling_fix{$suspect} = $fix;
669 warn "No typos will be found - file '$spelling_file': $!\n";
673 if (open(my $spelling, '<', $codespellfile)) {
674 while (<$spelling>) {
677 $line =~ s/\s*\n?$//g;
680 next if ($line =~ m/^\s*#/);
681 next if ($line =~ m/^\s*$/);
682 next if ($line =~ m/, disabled/i);
686 my ($suspect, $fix) = split(/->/, $line);
688 $spelling_fix{$suspect} = $fix;
692 warn "No codespell typos will be found - file '$codespellfile': $!\n";
696 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
699 my ($wordsRef, $file) = @_;
701 if (open(my $words, '<', $file)) {
705 $line =~ s/\s*\n?$//g;
708 next if ($line =~ m/^\s*#/);
709 next if ($line =~ m/^\s*$/);
711 print("$file: '$line' invalid - ignored\n");
715 $$wordsRef .= '|' if ($$wordsRef ne "");
725 my $const_structs = "";
726 read_words(\$const_structs, $conststructsfile)
727 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
729 my $typeOtherTypedefs = "";
730 if (length($typedefsfile)) {
731 read_words(\$typeOtherTypedefs, $typedefsfile)
732 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
734 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
737 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
738 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
739 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
740 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
741 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
747 (?:$Modifier\s+|const\s+)*
749 (?:typeof|__typeof__)\s*\([^\)]*\)|
753 (?:\s+$Modifier|\s+const)*
755 $NonptrTypeMisordered = qr{
756 (?:$Modifier\s+|const\s+)*
760 (?:\s+$Modifier|\s+const)*
762 $NonptrTypeWithAttr = qr{
763 (?:$Modifier\s+|const\s+)*
765 (?:typeof|__typeof__)\s*\([^\)]*\)|
769 (?:\s+$Modifier|\s+const)*
773 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
774 (?:\s+$Inline|\s+$Modifier)*
776 $TypeMisordered = qr{
777 $NonptrTypeMisordered
778 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
779 (?:\s+$Inline|\s+$Modifier)*
781 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
782 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
786 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
788 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
789 # requires at least perl version v5.10.0
790 # Any use must be runtime checked with $^V
792 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
793 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
794 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
796 our $declaration_macros = qr{(?x:
797 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
798 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
799 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
800 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
805 return "" if (!defined($string));
807 while ($string =~ /^\s*\(.*\)\s*$/) {
808 $string =~ s@^\s*\(\s*@@;
809 $string =~ s@\s*\)\s*$@@;
812 $string =~ s@\s+@ @g;
817 sub seed_camelcase_file {
820 return if (!(-f $file));
824 open(my $include_file, '<', "$file")
825 or warn "$P: Can't read '$file' $!\n";
826 my $text = <$include_file>;
827 close($include_file);
829 my @lines = split('\n', $text);
831 foreach my $line (@lines) {
832 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
833 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
835 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
837 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
843 sub is_maintained_obsolete {
846 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
848 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
850 return $status =~ /obsolete/i;
853 sub is_SPDX_License_valid {
856 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
858 my $root_path = abs_path($root);
859 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
860 return 0 if ($status ne "");
864 my $camelcase_seeded = 0;
865 sub seed_camelcase_includes {
866 return if ($camelcase_seeded);
869 my $camelcase_cache = "";
870 my @include_files = ();
872 $camelcase_seeded = 1;
875 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
876 chomp $git_last_include_commit;
877 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
879 my $last_mod_date = 0;
880 $files = `find $root/include -name "*.h"`;
881 @include_files = split('\n', $files);
882 foreach my $file (@include_files) {
883 my $date = POSIX::strftime("%Y%m%d%H%M",
884 localtime((stat $file)[9]));
885 $last_mod_date = $date if ($last_mod_date < $date);
887 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
890 if ($camelcase_cache ne "" && -f $camelcase_cache) {
891 open(my $camelcase_file, '<', "$camelcase_cache")
892 or warn "$P: Can't read '$camelcase_cache' $!\n";
893 while (<$camelcase_file>) {
897 close($camelcase_file);
903 $files = `git ls-files "include/*.h"`;
904 @include_files = split('\n', $files);
907 foreach my $file (@include_files) {
908 seed_camelcase_file($file);
911 if ($camelcase_cache ne "") {
912 unlink glob ".checkpatch-camelcase.*";
913 open(my $camelcase_file, '>', "$camelcase_cache")
914 or warn "$P: Can't write '$camelcase_cache' $!\n";
915 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
916 print $camelcase_file ("$_\n");
918 close($camelcase_file);
922 sub git_commit_info {
923 my ($commit, $id, $desc) = @_;
925 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
927 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
928 $output =~ s/^\s*//gm;
929 my @lines = split("\n", $output);
931 return ($id, $desc) if ($#lines < 0);
933 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
934 # Maybe one day convert this block of bash into something that returns
935 # all matching commit ids, but it's very slow...
937 # echo "checking commits $1..."
938 # git rev-list --remotes | grep -i "^$1" |
939 # while read line ; do
940 # git log --format='%H %s' -1 $line |
941 # echo "commit $(cut -c 1-12,41-)"
943 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
946 $id = substr($lines[0], 0, 12);
947 $desc = substr($lines[0], 41);
953 $chk_signoff = 0 if ($file);
958 my @fixed_inserted = ();
959 my @fixed_deleted = ();
962 # If input is git commits, extract all commits from the commit expressions.
963 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
964 die "$P: No git repository found\n" if ($git && !-e ".git");
968 foreach my $commit_expr (@ARGV) {
970 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
971 $git_range = "-$2 $1";
972 } elsif ($commit_expr =~ m/\.\./) {
973 $git_range = "$commit_expr";
975 $git_range = "-1 $commit_expr";
977 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
978 foreach my $line (split(/\n/, $lines)) {
979 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
980 next if (!defined($1) || !defined($2));
983 unshift(@commits, $sha1);
984 $git_commits{$sha1} = $subject;
987 die "$P: no git commits after extraction!\n" if (@commits == 0);
992 for my $filename (@ARGV) {
995 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
996 die "$P: $filename: git format-patch failed - $!\n";
998 open($FILE, '-|', "diff -u /dev/null $filename") ||
999 die "$P: $filename: diff failed - $!\n";
1000 } elsif ($filename eq '-') {
1001 open($FILE, '<&STDIN');
1003 open($FILE, '<', "$filename") ||
1004 die "$P: $filename: open failed - $!\n";
1006 if ($filename eq '-') {
1007 $vname = 'Your patch';
1009 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1015 push(@rawlines, $_);
1019 if ($#ARGV > 0 && $quiet == 0) {
1020 print '-' x length($vname) . "\n";
1022 print '-' x length($vname) . "\n";
1025 if (!process($filename)) {
1031 @fixed_inserted = ();
1032 @fixed_deleted = ();
1034 @modifierListFile = ();
1040 hash_show_words(\%use_type, "Used");
1041 hash_show_words(\%ignore_type, "Ignored");
1043 if (!$perl_version_ok) {
1046 NOTE: perl $^V is not modern enough to detect all possible issues.
1047 An upgrade to at least perl $minimum_perl_version is suggested.
1053 NOTE: If any of the errors are false positives, please report
1054 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1061 sub top_of_kernel_tree {
1065 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1066 "README", "Documentation", "arch", "include", "drivers",
1067 "fs", "init", "ipc", "kernel", "lib", "scripts",
1070 foreach my $check (@tree_check) {
1071 if (! -e $root . '/' . $check) {
1079 my ($formatted_email) = @_;
1085 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1088 $comment = $3 if defined $3;
1089 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1091 $comment = $2 if defined $2;
1092 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1094 $comment = $2 if defined $2;
1095 $formatted_email =~ s/\Q$address\E.*$//;
1096 $name = $formatted_email;
1097 $name = trim($name);
1098 $name =~ s/^\"|\"$//g;
1099 # If there's a name left after stripping spaces and
1100 # leading quotes, and the address doesn't have both
1101 # leading and trailing angle brackets, the address
1103 # "joe smith joe@smith.com" bad
1104 # "joe smith <joe@smith.com" bad
1105 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1112 $name = trim($name);
1113 $name =~ s/^\"|\"$//g;
1114 $address = trim($address);
1115 $address =~ s/^\<|\>$//g;
1117 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1118 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1119 $name = "\"$name\"";
1122 return ($name, $address, $comment);
1126 my ($name, $address) = @_;
1128 my $formatted_email;
1130 $name = trim($name);
1131 $name =~ s/^\"|\"$//g;
1132 $address = trim($address);
1134 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1135 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1136 $name = "\"$name\"";
1139 if ("$name" eq "") {
1140 $formatted_email = "$address";
1142 $formatted_email = "$name <$address>";
1145 return $formatted_email;
1151 foreach my $path (split(/:/, $ENV{PATH})) {
1152 if (-e "$path/$bin") {
1153 return "$path/$bin";
1163 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1164 if (-e "$path/$conf") {
1165 return "$path/$conf";
1177 for my $c (split(//, $str)) {
1181 for (; ($n % 8) != 0; $n++) {
1193 (my $res = shift) =~ tr/\t/ /c;
1200 # Drop the diff line leader and expand tabs
1202 $line = expand_tabs($line);
1204 # Pick the indent from the front of the line.
1205 my ($white) = ($line =~ /^(\s*)/);
1207 return (length($line), length($white));
1210 my $sanitise_quote = '';
1212 sub sanitise_line_reset {
1213 my ($in_comment) = @_;
1216 $sanitise_quote = '*/';
1218 $sanitise_quote = '';
1231 # Always copy over the diff marker.
1232 $res = substr($line, 0, 1);
1234 for ($off = 1; $off < length($line); $off++) {
1235 $c = substr($line, $off, 1);
1237 # Comments we are whacking completely including the begin
1238 # and end, all to $;.
1239 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1240 $sanitise_quote = '*/';
1242 substr($res, $off, 2, "$;$;");
1246 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1247 $sanitise_quote = '';
1248 substr($res, $off, 2, "$;$;");
1252 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1253 $sanitise_quote = '//';
1255 substr($res, $off, 2, $sanitise_quote);
1260 # A \ in a string means ignore the next character.
1261 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1263 substr($res, $off, 2, 'XX');
1268 if ($c eq "'" || $c eq '"') {
1269 if ($sanitise_quote eq '') {
1270 $sanitise_quote = $c;
1272 substr($res, $off, 1, $c);
1274 } elsif ($sanitise_quote eq $c) {
1275 $sanitise_quote = '';
1279 #print "c<$c> SQ<$sanitise_quote>\n";
1280 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1281 substr($res, $off, 1, $;);
1282 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1283 substr($res, $off, 1, $;);
1284 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1285 substr($res, $off, 1, 'X');
1287 substr($res, $off, 1, $c);
1291 if ($sanitise_quote eq '//') {
1292 $sanitise_quote = '';
1295 # The pathname on a #include may be surrounded by '<' and '>'.
1296 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1297 my $clean = 'X' x length($1);
1298 $res =~ s@\<.*\>@<$clean>@;
1300 # The whole of a #error is a string.
1301 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1302 my $clean = 'X' x length($1);
1303 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1306 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1308 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1314 sub get_quoted_string {
1315 my ($line, $rawline) = @_;
1317 return "" if (!defined($line) || !defined($rawline));
1318 return "" if ($line !~ m/($String)/g);
1319 return substr($rawline, $-[0], $+[0] - $-[0]);
1322 sub ctx_statement_block {
1323 my ($linenr, $remain, $off) = @_;
1324 my $line = $linenr - 1;
1327 my $coff = $off - 1;
1341 @stack = (['', 0]) if ($#stack == -1);
1343 #warn "CSB: blk<$blk> remain<$remain>\n";
1344 # If we are about to drop off the end, pull in more
1347 for (; $remain > 0; $line++) {
1348 last if (!defined $lines[$line]);
1349 next if ($lines[$line] =~ /^-/);
1352 $blk .= $lines[$line] . "\n";
1353 $len = length($blk);
1357 # Bail if there is no further context.
1358 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1362 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1368 $c = substr($blk, $off, 1);
1369 $remainder = substr($blk, $off);
1371 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1373 # Handle nested #if/#else.
1374 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1375 push(@stack, [ $type, $level ]);
1376 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1377 ($type, $level) = @{$stack[$#stack - 1]};
1378 } elsif ($remainder =~ /^#\s*endif\b/) {
1379 ($type, $level) = @{pop(@stack)};
1382 # Statement ends at the ';' or a close '}' at the
1384 if ($level == 0 && $c eq ';') {
1388 # An else is really a conditional as long as its not else if
1389 if ($level == 0 && $coff_set == 0 &&
1390 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1391 $remainder =~ /^(else)(?:\s|{)/ &&
1392 $remainder !~ /^else\s+if\b/) {
1393 $coff = $off + length($1) - 1;
1395 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1396 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1399 if (($type eq '' || $type eq '(') && $c eq '(') {
1403 if ($type eq '(' && $c eq ')') {
1405 $type = ($level != 0)? '(' : '';
1407 if ($level == 0 && $coff < $soff) {
1410 #warn "CSB: mark coff<$coff>\n";
1413 if (($type eq '' || $type eq '{') && $c eq '{') {
1417 if ($type eq '{' && $c eq '}') {
1419 $type = ($level != 0)? '{' : '';
1422 if (substr($blk, $off + 1, 1) eq ';') {
1428 # Preprocessor commands end at the newline unless escaped.
1429 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1437 # We are truly at the end, so shuffle to the next line.
1444 my $statement = substr($blk, $soff, $off - $soff + 1);
1445 my $condition = substr($blk, $soff, $coff - $soff + 1);
1447 #warn "STATEMENT<$statement>\n";
1448 #warn "CONDITION<$condition>\n";
1450 #print "coff<$coff> soff<$off> loff<$loff>\n";
1452 return ($statement, $condition,
1453 $line, $remain + 1, $off - $loff + 1, $level);
1456 sub statement_lines {
1459 # Strip the diff line prefixes and rip blank lines at start and end.
1460 $stmt =~ s/(^|\n)./$1/g;
1464 my @stmt_lines = ($stmt =~ /\n/g);
1466 return $#stmt_lines + 2;
1469 sub statement_rawlines {
1472 my @stmt_lines = ($stmt =~ /\n/g);
1474 return $#stmt_lines + 2;
1477 sub statement_block_size {
1480 $stmt =~ s/(^|\n)./$1/g;
1486 my @stmt_lines = ($stmt =~ /\n/g);
1487 my @stmt_statements = ($stmt =~ /;/g);
1489 my $stmt_lines = $#stmt_lines + 2;
1490 my $stmt_statements = $#stmt_statements + 1;
1492 if ($stmt_lines > $stmt_statements) {
1495 return $stmt_statements;
1499 sub ctx_statement_full {
1500 my ($linenr, $remain, $off) = @_;
1501 my ($statement, $condition, $level);
1505 # Grab the first conditional/block pair.
1506 ($statement, $condition, $linenr, $remain, $off, $level) =
1507 ctx_statement_block($linenr, $remain, $off);
1508 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1509 push(@chunks, [ $condition, $statement ]);
1510 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1511 return ($level, $linenr, @chunks);
1514 # Pull in the following conditional/block pairs and see if they
1515 # could continue the statement.
1517 ($statement, $condition, $linenr, $remain, $off, $level) =
1518 ctx_statement_block($linenr, $remain, $off);
1519 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1520 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1522 push(@chunks, [ $condition, $statement ]);
1525 return ($level, $linenr, @chunks);
1529 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1531 my $start = $linenr - 1;
1538 my @stack = ($level);
1539 for ($line = $start; $remain > 0; $line++) {
1540 next if ($rawlines[$line] =~ /^-/);
1543 $blk .= $rawlines[$line];
1545 # Handle nested #if/#else.
1546 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1547 push(@stack, $level);
1548 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1549 $level = $stack[$#stack - 1];
1550 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1551 $level = pop(@stack);
1554 foreach my $c (split(//, $lines[$line])) {
1555 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1561 if ($c eq $close && $level > 0) {
1563 last if ($level == 0);
1564 } elsif ($c eq $open) {
1569 if (!$outer || $level <= 1) {
1570 push(@res, $rawlines[$line]);
1573 last if ($level == 0);
1576 return ($level, @res);
1578 sub ctx_block_outer {
1579 my ($linenr, $remain) = @_;
1581 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1585 my ($linenr, $remain) = @_;
1587 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1591 my ($linenr, $remain, $off) = @_;
1593 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1596 sub ctx_block_level {
1597 my ($linenr, $remain) = @_;
1599 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1601 sub ctx_statement_level {
1602 my ($linenr, $remain, $off) = @_;
1604 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1607 sub ctx_locate_comment {
1608 my ($first_line, $end_line) = @_;
1610 # Catch a comment on the end of the line itself.
1611 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1612 return $current_comment if (defined $current_comment);
1614 # Look through the context and try and figure out if there is a
1617 $current_comment = '';
1618 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1619 my $line = $rawlines[$linenr - 1];
1621 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1624 if ($line =~ m@/\*@) {
1627 if (!$in_comment && $current_comment ne '') {
1628 $current_comment = '';
1630 $current_comment .= $line . "\n" if ($in_comment);
1631 if ($line =~ m@\*/@) {
1636 chomp($current_comment);
1637 return($current_comment);
1639 sub ctx_has_comment {
1640 my ($first_line, $end_line) = @_;
1641 my $cmt = ctx_locate_comment($first_line, $end_line);
1643 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1644 ##print "CMMT: $cmt\n";
1646 return ($cmt ne '');
1650 my ($linenr, $cnt) = @_;
1652 my $offset = $linenr - 1;
1657 $line = $rawlines[$offset++];
1658 next if (defined($line) && $line =~ /^-/);
1666 my ($linenr, $lc) = @_;
1668 my $stat_real = raw_line($linenr, 0);
1669 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1670 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1677 my ($linenr, $cnt, $here) = @_;
1679 my $herectx = $here . "\n";
1680 for (my $n = 0; $n < $cnt; $n++) {
1681 $herectx .= raw_line($linenr, $n) . "\n";
1692 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1695 $coded = sprintf("^%c", unpack('C', $2) + 64);
1704 my $av_preprocessor = 0;
1709 sub annotate_reset {
1710 $av_preprocessor = 0;
1712 @av_paren_type = ('E');
1713 $av_pend_colon = 'O';
1716 sub annotate_values {
1717 my ($stream, $type) = @_;
1720 my $var = '_' x length($stream);
1723 print "$stream\n" if ($dbg_values > 1);
1725 while (length($cur)) {
1726 @av_paren_type = ('E') if ($#av_paren_type < 0);
1727 print " <" . join('', @av_paren_type) .
1728 "> <$type> <$av_pending>" if ($dbg_values > 1);
1729 if ($cur =~ /^(\s+)/o) {
1730 print "WS($1)\n" if ($dbg_values > 1);
1731 if ($1 =~ /\n/ && $av_preprocessor) {
1732 $type = pop(@av_paren_type);
1733 $av_preprocessor = 0;
1736 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1737 print "CAST($1)\n" if ($dbg_values > 1);
1738 push(@av_paren_type, $type);
1741 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1742 print "DECLARE($1)\n" if ($dbg_values > 1);
1745 } elsif ($cur =~ /^($Modifier)\s*/) {
1746 print "MODIFIER($1)\n" if ($dbg_values > 1);
1749 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1750 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1751 $av_preprocessor = 1;
1752 push(@av_paren_type, $type);
1758 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1759 print "UNDEF($1)\n" if ($dbg_values > 1);
1760 $av_preprocessor = 1;
1761 push(@av_paren_type, $type);
1763 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1764 print "PRE_START($1)\n" if ($dbg_values > 1);
1765 $av_preprocessor = 1;
1767 push(@av_paren_type, $type);
1768 push(@av_paren_type, $type);
1771 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1772 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1773 $av_preprocessor = 1;
1775 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1779 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1780 print "PRE_END($1)\n" if ($dbg_values > 1);
1782 $av_preprocessor = 1;
1784 # Assume all arms of the conditional end as this
1785 # one does, and continue as if the #endif was not here.
1786 pop(@av_paren_type);
1787 push(@av_paren_type, $type);
1790 } elsif ($cur =~ /^(\\\n)/o) {
1791 print "PRECONT($1)\n" if ($dbg_values > 1);
1793 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1794 print "ATTR($1)\n" if ($dbg_values > 1);
1795 $av_pending = $type;
1798 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1799 print "SIZEOF($1)\n" if ($dbg_values > 1);
1805 } elsif ($cur =~ /^(if|while|for)\b/o) {
1806 print "COND($1)\n" if ($dbg_values > 1);
1810 } elsif ($cur =~/^(case)/o) {
1811 print "CASE($1)\n" if ($dbg_values > 1);
1812 $av_pend_colon = 'C';
1815 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1816 print "KEYWORD($1)\n" if ($dbg_values > 1);
1819 } elsif ($cur =~ /^(\()/o) {
1820 print "PAREN('$1')\n" if ($dbg_values > 1);
1821 push(@av_paren_type, $av_pending);
1825 } elsif ($cur =~ /^(\))/o) {
1826 my $new_type = pop(@av_paren_type);
1827 if ($new_type ne '_') {
1829 print "PAREN('$1') -> $type\n"
1830 if ($dbg_values > 1);
1832 print "PAREN('$1')\n" if ($dbg_values > 1);
1835 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1836 print "FUNC($1)\n" if ($dbg_values > 1);
1840 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1841 if (defined $2 && $type eq 'C' || $type eq 'T') {
1842 $av_pend_colon = 'B';
1843 } elsif ($type eq 'E') {
1844 $av_pend_colon = 'L';
1846 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1849 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1850 print "IDENT($1)\n" if ($dbg_values > 1);
1853 } elsif ($cur =~ /^($Assignment)/o) {
1854 print "ASSIGN($1)\n" if ($dbg_values > 1);
1857 } elsif ($cur =~/^(;|{|})/) {
1858 print "END($1)\n" if ($dbg_values > 1);
1860 $av_pend_colon = 'O';
1862 } elsif ($cur =~/^(,)/) {
1863 print "COMMA($1)\n" if ($dbg_values > 1);
1866 } elsif ($cur =~ /^(\?)/o) {
1867 print "QUESTION($1)\n" if ($dbg_values > 1);
1870 } elsif ($cur =~ /^(:)/o) {
1871 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1873 substr($var, length($res), 1, $av_pend_colon);
1874 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1879 $av_pend_colon = 'O';
1881 } elsif ($cur =~ /^(\[)/o) {
1882 print "CLOSE($1)\n" if ($dbg_values > 1);
1885 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1888 print "OPV($1)\n" if ($dbg_values > 1);
1895 substr($var, length($res), 1, $variant);
1898 } elsif ($cur =~ /^($Operators)/o) {
1899 print "OP($1)\n" if ($dbg_values > 1);
1900 if ($1 ne '++' && $1 ne '--') {
1904 } elsif ($cur =~ /(^.)/o) {
1905 print "C($1)\n" if ($dbg_values > 1);
1908 $cur = substr($cur, length($1));
1909 $res .= $type x length($1);
1913 return ($res, $var);
1917 my ($possible, $line) = @_;
1918 my $notPermitted = qr{(?:
1935 ^(?:typedef|struct|enum)\b
1937 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1938 if ($possible !~ $notPermitted) {
1939 # Check for modifiers.
1940 $possible =~ s/\s*$Storage\s*//g;
1941 $possible =~ s/\s*$Sparse\s*//g;
1942 if ($possible =~ /^\s*$/) {
1944 } elsif ($possible =~ /\s/) {
1945 $possible =~ s/\s*$Type\s*//g;
1946 for my $modifier (split(' ', $possible)) {
1947 if ($modifier !~ $notPermitted) {
1948 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1949 push(@modifierListFile, $modifier);
1954 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1955 push(@typeListFile, $possible);
1959 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1968 $type =~ tr/[a-z]/[A-Z]/;
1970 return defined $use_type{$type} if (scalar keys %use_type > 0);
1972 return !defined $ignore_type{$type};
1976 my ($level, $type, $msg) = @_;
1978 if (!show_type($type) ||
1979 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1984 if ($level eq 'ERROR') {
1986 } elsif ($level eq 'WARNING') {
1992 $output .= $prefix . $level . ':';
1994 $output .= BLUE if ($color);
1995 $output .= "$type:";
1997 $output .= RESET if ($color);
1998 $output .= ' ' . $msg . "\n";
2001 my @lines = split("\n", $output, -1);
2002 splice(@lines, 1, 1);
2003 $output = join("\n", @lines);
2005 $output = (split('\n', $output))[0] . "\n" if ($terse);
2007 push(our @report, $output);
2016 sub fixup_current_range {
2017 my ($lineRef, $offset, $length) = @_;
2019 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2022 my $no = $o + $offset;
2023 my $nl = $l + $length;
2024 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2028 sub fix_inserted_deleted_lines {
2029 my ($linesRef, $insertedRef, $deletedRef) = @_;
2031 my $range_last_linenr = 0;
2032 my $delta_offset = 0;
2037 my $next_insert = 0;
2038 my $next_delete = 0;
2042 my $inserted = @{$insertedRef}[$next_insert++];
2043 my $deleted = @{$deletedRef}[$next_delete++];
2045 foreach my $old_line (@{$linesRef}) {
2047 my $line = $old_line; #don't modify the array
2048 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2050 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2051 $range_last_linenr = $new_linenr;
2052 fixup_current_range(\$line, $delta_offset, 0);
2055 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2056 $deleted = @{$deletedRef}[$next_delete++];
2058 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2061 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2062 push(@lines, ${$inserted}{'LINE'});
2063 $inserted = @{$insertedRef}[$next_insert++];
2065 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2069 push(@lines, $line);
2079 sub fix_insert_line {
2080 my ($linenr, $line) = @_;
2086 push(@fixed_inserted, $inserted);
2089 sub fix_delete_line {
2090 my ($linenr, $line) = @_;
2097 push(@fixed_deleted, $deleted);
2101 my ($type, $msg) = @_;
2103 if (report("ERROR", $type, $msg)) {
2111 my ($type, $msg) = @_;
2113 if (report("WARNING", $type, $msg)) {
2121 my ($type, $msg) = @_;
2123 if ($check && report("CHECK", $type, $msg)) {
2131 sub check_absolute_file {
2132 my ($absolute, $herecurr) = @_;
2133 my $file = $absolute;
2135 ##print "absolute<$absolute>\n";
2137 # See if any suffix of this path is a path within the tree.
2138 while ($file =~ s@^[^/]*/@@) {
2139 if (-f "$root/$file") {
2140 ##print "file<$file>\n";
2148 # It is, so see if the prefix is acceptable.
2149 my $prefix = $absolute;
2150 substr($prefix, -length($file)) = '';
2152 ##print "prefix<$prefix>\n";
2153 if ($prefix ne ".../") {
2154 WARN("USE_RELATIVE_PATH",
2155 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2162 $string =~ s/^\s+|\s+$//g;
2170 $string =~ s/^\s+//;
2178 $string =~ s/\s+$//;
2183 sub string_find_replace {
2184 my ($string, $find, $replace) = @_;
2186 $string =~ s/$find/$replace/g;
2194 my $source_indent = 8;
2195 my $max_spaces_before_tab = $source_indent - 1;
2196 my $spaces_to_tab = " " x $source_indent;
2198 #convert leading spaces to tabs
2199 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2200 #Remove spaces before a tab
2201 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2206 sub pos_last_openparen {
2211 my $opens = $line =~ tr/\(/\(/;
2212 my $closes = $line =~ tr/\)/\)/;
2214 my $last_openparen = 0;
2216 if (($opens == 0) || ($closes >= $opens)) {
2220 my $len = length($line);
2222 for ($pos = 0; $pos < $len; $pos++) {
2223 my $string = substr($line, $pos);
2224 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2225 $pos += length($1) - 1;
2226 } elsif (substr($line, $pos, 1) eq '(') {
2227 $last_openparen = $pos;
2228 } elsif (index($string, '(') == -1) {
2233 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2237 my $filename = shift;
2243 my $stashrawline="";
2253 my $authorsignoff = 0;
2255 my $is_binding_patch = -1;
2256 my $in_header_lines = $file ? 0 : 1;
2257 my $in_commit_log = 0; #Scanning lines before patch
2258 my $has_commit_log = 0; #Encountered lines before patch
2259 my $commit_log_lines = 0; #Number of commit log lines
2260 my $commit_log_possible_stack_dump = 0;
2261 my $commit_log_long_line = 0;
2262 my $commit_log_has_diff = 0;
2263 my $reported_maintainer_file = 0;
2264 my $non_utf8_charset = 0;
2266 my $last_blank_line = 0;
2267 my $last_coalesced_string_linenr = -1;
2275 # Trace the real file/line as we go.
2280 my $context_function; #undef'd unless there's a known function
2282 my $comment_edge = 0;
2286 my $prev_values = 'E';
2289 my %suppress_ifbraces;
2290 my %suppress_whiletrailers;
2291 my %suppress_export;
2292 my $suppress_statement = 0;
2294 my %signatures = ();
2296 # Pre-scan the patch sanitizing the lines.
2297 # Pre-scan the patch looking for any __setup documentation.
2299 my @setup_docs = ();
2302 my $camelcase_file_seeded = 0;
2304 my $checklicenseline = 1;
2306 sanitise_line_reset();
2308 foreach my $rawline (@rawlines) {
2312 push(@fixed, $rawline) if ($fix);
2314 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2316 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2321 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2330 # Guestimate if this is a continuing comment. Run
2331 # the context looking for a comment "edge". If this
2332 # edge is a close comment then we must be in a comment
2336 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2337 next if (defined $rawlines[$ln - 1] &&
2338 $rawlines[$ln - 1] =~ /^-/);
2340 #print "RAW<$rawlines[$ln - 1]>\n";
2341 last if (!defined $rawlines[$ln - 1]);
2342 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2343 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2348 if (defined $edge && $edge eq '*/') {
2352 # Guestimate if this is a continuing comment. If this
2353 # is the start of a diff block and this line starts
2354 # ' *' then it is very likely a comment.
2355 if (!defined $edge &&
2356 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2361 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2362 sanitise_line_reset($in_comment);
2364 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2365 # Standardise the strings and chars within the input to
2366 # simplify matching -- only bother with positive lines.
2367 $line = sanitise_line($rawline);
2369 push(@lines, $line);
2372 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2377 #print "==>$rawline\n";
2378 #print "-->$line\n";
2380 if ($setup_docs && $line =~ /^\+/) {
2381 push(@setup_docs, $line);
2390 foreach my $line (@lines) {
2393 my $sline = $line; #copy of $line
2394 $sline =~ s/$;/ /g; #with comments as spaces
2396 my $rawline = $rawlines[$linenr - 1];
2398 # check if it's a mode change, rename or start of a patch
2399 if (!$in_commit_log &&
2400 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2401 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2402 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2406 #extract the line range in the file after the patch is applied
2407 if (!$in_commit_log &&
2408 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2411 $first_line = $linenr + 1;
2421 %suppress_ifbraces = ();
2422 %suppress_whiletrailers = ();
2423 %suppress_export = ();
2424 $suppress_statement = 0;
2425 if ($context =~ /\b(\w+)\s*\(/) {
2426 $context_function = $1;
2428 undef $context_function;
2432 # track the line number as we move through the hunk, note that
2433 # new versions of GNU diff omit the leading space on completely
2434 # blank context lines so we need to count that too.
2435 } elsif ($line =~ /^( |\+|$)/) {
2437 $realcnt-- if ($realcnt != 0);
2439 # Measure the line length and indent.
2440 ($length, $indent) = line_stats($rawline);
2442 # Track the previous line.
2443 ($prevline, $stashline) = ($stashline, $line);
2444 ($previndent, $stashindent) = ($stashindent, $indent);
2445 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2447 #warn "line<$line>\n";
2449 } elsif ($realcnt == 1) {
2453 my $hunk_line = ($realcnt != 0);
2455 $here = "#$linenr: " if (!$file);
2456 $here = "#$realline: " if ($file);
2459 # extract the filename as it passes
2460 if ($line =~ /^diff --git.*?(\S+)$/) {
2462 $realfile =~ s@^([^/]*)/@@ if (!$file);
2465 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2467 $realfile =~ s@^([^/]*)/@@ if (!$file);
2471 if (!$file && $tree && $p1_prefix ne '' &&
2472 -e "$root/$p1_prefix") {
2473 WARN("PATCH_PREFIX",
2474 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2477 if ($realfile =~ m@^include/asm/@) {
2478 ERROR("MODIFIED_INCLUDE_ASM",
2479 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2484 #make up the handle for any error we report on this line
2486 $prefix = "$realfile:$realline: "
2489 $prefix = "$filename:$realline: ";
2491 $prefix = "$filename:$linenr: ";
2496 if (is_maintained_obsolete($realfile)) {
2498 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2500 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2503 $check = $check_orig;
2505 $checklicenseline = 1;
2507 if ($realfile !~ /^MAINTAINERS/) {
2508 my $last_binding_patch = $is_binding_patch;
2510 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2512 if (($last_binding_patch != -1) &&
2513 ($last_binding_patch ^ $is_binding_patch)) {
2514 WARN("DT_SPLIT_BINDING_PATCH",
2515 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2522 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2524 my $hereline = "$here\n$rawline\n";
2525 my $herecurr = "$here\n$rawline\n";
2526 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2528 $cnt_lines++ if ($realcnt != 0);
2530 # Verify the existence of a commit log if appropriate
2531 # 2 is used because a $signature is counted in $commit_log_lines
2532 if ($in_commit_log) {
2533 if ($line !~ /^\s*$/) {
2534 $commit_log_lines++; #could be a $signature
2536 } elsif ($has_commit_log && $commit_log_lines < 2) {
2537 WARN("COMMIT_MESSAGE",
2538 "Missing commit description - Add an appropriate one\n");
2539 $commit_log_lines = 2; #warn only once
2542 # Check if the commit log has what seems like a diff which can confuse patch
2543 if ($in_commit_log && !$commit_log_has_diff &&
2544 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2545 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2546 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2547 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2548 ERROR("DIFF_IN_COMMIT_MSG",
2549 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2550 $commit_log_has_diff = 1;
2553 # Check for incorrect file permissions
2554 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2555 my $permhere = $here . "FILE: $realfile\n";
2556 if ($realfile !~ m@scripts/@ &&
2557 $realfile !~ /\.(py|pl|awk|sh)$/) {
2558 ERROR("EXECUTE_PERMISSIONS",
2559 "do not set execute permissions for source files\n" . $permhere);
2563 # Check the patch for a From:
2564 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2566 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2570 # Check the patch for a signoff:
2571 if ($line =~ /^\s*signed-off-by:/i) {
2574 if ($author ne '') {
2577 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2583 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2584 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2585 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2586 $reported_maintainer_file = 1;
2589 # Check signature styles
2590 if (!$in_header_lines &&
2591 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2592 my $space_before = $1;
2594 my $space_after = $3;
2596 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2598 if ($sign_off !~ /$signature_tags/) {
2599 WARN("BAD_SIGN_OFF",
2600 "Non-standard signature: $sign_off\n" . $herecurr);
2602 if (defined $space_before && $space_before ne "") {
2603 if (WARN("BAD_SIGN_OFF",
2604 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2606 $fixed[$fixlinenr] =
2607 "$ucfirst_sign_off $email";
2610 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2611 if (WARN("BAD_SIGN_OFF",
2612 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2614 $fixed[$fixlinenr] =
2615 "$ucfirst_sign_off $email";
2619 if (!defined $space_after || $space_after ne " ") {
2620 if (WARN("BAD_SIGN_OFF",
2621 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2623 $fixed[$fixlinenr] =
2624 "$ucfirst_sign_off $email";
2628 my ($email_name, $email_address, $comment) = parse_email($email);
2629 my $suggested_email = format_email(($email_name, $email_address));
2630 if ($suggested_email eq "") {
2631 ERROR("BAD_SIGN_OFF",
2632 "Unrecognized email address: '$email'\n" . $herecurr);
2634 my $dequoted = $suggested_email;
2635 $dequoted =~ s/^"//;
2636 $dequoted =~ s/" </ </;
2637 # Don't force email to have quotes
2638 # Allow just an angle bracketed address
2639 if ("$dequoted$comment" ne $email &&
2640 "<$email_address>$comment" ne $email &&
2641 "$suggested_email$comment" ne $email) {
2642 WARN("BAD_SIGN_OFF",
2643 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2647 # Check for duplicate signatures
2648 my $sig_nospace = $line;
2649 $sig_nospace =~ s/\s//g;
2650 $sig_nospace = lc($sig_nospace);
2651 if (defined $signatures{$sig_nospace}) {
2652 WARN("BAD_SIGN_OFF",
2653 "Duplicate signature\n" . $herecurr);
2655 $signatures{$sig_nospace} = 1;
2659 # Check email subject for common tools that don't need to be mentioned
2660 if ($in_header_lines &&
2661 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2662 WARN("EMAIL_SUBJECT",
2663 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2666 # Check for unwanted Gerrit info
2667 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2668 ERROR("GERRIT_CHANGE_ID",
2669 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2672 # Check if the commit log is in a possible stack dump
2673 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2674 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2675 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2677 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2678 # stack dump address
2679 $commit_log_possible_stack_dump = 1;
2682 # Check for line lengths > 75 in commit log, warn once
2683 if ($in_commit_log && !$commit_log_long_line &&
2684 length($line) > 75 &&
2685 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2686 # file delta changes
2687 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2689 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2690 # A Fixes: or Link: line
2691 $commit_log_possible_stack_dump)) {
2692 WARN("COMMIT_LOG_LONG_LINE",
2693 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2694 $commit_log_long_line = 1;
2697 # Reset possible stack dump if a blank line is found
2698 if ($in_commit_log && $commit_log_possible_stack_dump &&
2700 $commit_log_possible_stack_dump = 0;
2703 # Check for git id commit length and improperly formed commit descriptions
2704 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2705 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2706 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2707 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2708 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2709 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2710 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2711 my $init_char = "c";
2712 my $orig_commit = "";
2719 my $id = '0123456789ab';
2720 my $orig_desc = "commit description";
2721 my $description = "";
2723 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2725 $orig_commit = lc($2);
2726 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2727 $orig_commit = lc($1);
2730 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2731 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2732 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2733 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2734 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2737 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2738 defined $rawlines[$linenr] &&
2739 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2742 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2743 defined $rawlines[$linenr] &&
2744 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2745 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2747 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2748 $orig_desc .= " " . $1;
2752 ($id, $description) = git_commit_info($orig_commit,
2756 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2757 ERROR("GIT_COMMIT_ID",
2758 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2762 # Check for added, moved or deleted files
2763 if (!$reported_maintainer_file && !$in_commit_log &&
2764 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2765 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2766 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2767 (defined($1) || defined($2))))) {
2769 $reported_maintainer_file = 1;
2770 WARN("FILE_PATH_CHANGES",
2771 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2774 # Check for wrappage within a valid hunk of the file
2775 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2776 ERROR("CORRUPTED_PATCH",
2777 "patch seems to be corrupt (line wrapped?)\n" .
2778 $herecurr) if (!$emitted_corrupt++);
2781 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2782 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2783 $rawline !~ m/^$UTF8*$/) {
2784 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2786 my $blank = copy_spacing($rawline);
2787 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2788 my $hereptr = "$hereline$ptr\n";
2791 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2794 # Check if it's the start of a commit log
2795 # (not a header line and we haven't seen the patch filename)
2796 if ($in_header_lines && $realfile =~ /^$/ &&
2797 !($rawline =~ /^\s+(?:\S|$)/ ||
2798 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2799 $in_header_lines = 0;
2801 $has_commit_log = 1;
2804 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2805 # declined it, i.e defined some charset where it is missing.
2806 if ($in_header_lines &&
2807 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2809 $non_utf8_charset = 1;
2812 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2813 $rawline =~ /$NON_ASCII_UTF8/) {
2814 WARN("UTF8_BEFORE_PATCH",
2815 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2818 # Check for absolute kernel paths in commit message
2819 if ($tree && $in_commit_log) {
2820 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2823 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2824 check_absolute_file($1, $herecurr)) {
2827 check_absolute_file($file, $herecurr);
2832 # Check for various typo / spelling mistakes
2833 if (defined($misspellings) &&
2834 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2835 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2837 my $typo_fix = $spelling_fix{lc($typo)};
2838 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2839 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2840 my $msg_level = \&WARN;
2841 $msg_level = \&CHK if ($file);
2842 if (&{$msg_level}("TYPO_SPELLING",
2843 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2845 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2850 # ignore non-hunk lines and lines being removed
2851 next if (!$hunk_line || $line =~ /^-/);
2853 #trailing whitespace
2854 if ($line =~ /^\+.*\015/) {
2855 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2856 if (ERROR("DOS_LINE_ENDINGS",
2857 "DOS line endings\n" . $herevet) &&
2859 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2861 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2862 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2863 if (ERROR("TRAILING_WHITESPACE",
2864 "trailing whitespace\n" . $herevet) &&
2866 $fixed[$fixlinenr] =~ s/\s+$//;
2872 # Check for FSF mailing addresses.
2873 if ($rawline =~ /\bwrite to the Free/i ||
2874 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2875 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2876 $rawline =~ /\b51\s+Franklin\s+St/i) {
2877 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2878 my $msg_level = \&ERROR;
2879 $msg_level = \&CHK if ($file);
2880 &{$msg_level}("FSF_MAILING_ADDRESS",
2881 "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)
2884 # check for Kconfig help text having a real description
2885 # Only applies when adding the entry originally, after that we do not have
2886 # sufficient context to determine whether it is indeed long enough.
2887 if ($realfile =~ /Kconfig/ &&
2888 # 'choice' is usually the last thing on the line (though
2889 # Kconfig supports named choices), so use a word boundary
2890 # (\b) rather than a whitespace character (\s)
2891 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2894 my $ln = $linenr + 1;
2898 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2899 $f = $lines[$ln - 1];
2900 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2901 $is_end = $lines[$ln - 1] =~ /^\+/;
2903 next if ($f =~ /^-/);
2904 last if (!$file && $f =~ /^\@\@/);
2906 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2908 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2909 if ($lines[$ln - 1] =~ "---help---") {
2910 WARN("CONFIG_DESCRIPTION",
2911 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2919 next if ($f =~ /^$/);
2921 # This only checks context lines in the patch
2922 # and so hopefully shouldn't trigger false
2923 # positives, even though some of these are
2924 # common words in help texts
2925 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2926 if|endif|menu|endmenu|source)\b/x) {
2932 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2933 WARN("CONFIG_DESCRIPTION",
2934 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2936 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2939 # check for MAINTAINERS entries that don't have the right form
2940 if ($realfile =~ /^MAINTAINERS$/ &&
2941 $rawline =~ /^\+[A-Z]:/ &&
2942 $rawline !~ /^\+[A-Z]:\t\S/) {
2943 if (WARN("MAINTAINERS_STYLE",
2944 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2946 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2950 # discourage the use of boolean for type definition attributes of Kconfig options
2951 if ($realfile =~ /Kconfig/ &&
2952 $line =~ /^\+\s*\bboolean\b/) {
2953 WARN("CONFIG_TYPE_BOOLEAN",
2954 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2957 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2958 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2961 'EXTRA_AFLAGS' => 'asflags-y',
2962 'EXTRA_CFLAGS' => 'ccflags-y',
2963 'EXTRA_CPPFLAGS' => 'cppflags-y',
2964 'EXTRA_LDFLAGS' => 'ldflags-y',
2967 WARN("DEPRECATED_VARIABLE",
2968 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2971 # check for DT compatible documentation
2972 if (defined $root &&
2973 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2974 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2976 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2978 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2979 my $vp_file = $dt_path . "vendor-prefixes.txt";
2981 foreach my $compat (@compats) {
2982 my $compat2 = $compat;
2983 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2984 my $compat3 = $compat;
2985 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2986 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2988 WARN("UNDOCUMENTED_DT_STRING",
2989 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2992 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2994 `grep -Eq "^$vendor\\b" $vp_file`;
2996 WARN("UNDOCUMENTED_DT_STRING",
2997 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3002 # check for using SPDX license tag at beginning of files
3003 if ($realline == $checklicenseline) {
3004 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3005 $checklicenseline = 2;
3006 } elsif ($rawline =~ /^\+/) {
3008 if ($realfile =~ /\.(h|s|S)$/) {
3010 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3012 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3014 } elsif ($realfile =~ /\.rst$/) {
3018 if ($comment !~ /^$/ &&
3019 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3020 WARN("SPDX_LICENSE_TAG",
3021 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3022 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3023 my $spdx_license = $1;
3024 if (!is_SPDX_License_valid($spdx_license)) {
3025 WARN("SPDX_LICENSE_TAG",
3026 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3032 # check we are in a valid source file if not then ignore this hunk
3033 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3035 # line length limit (with some exclusions)
3037 # There are a few types of lines that may extend beyond $max_line_length:
3038 # logging functions like pr_info that end in a string
3039 # lines with a single string
3040 # #defines that are a single string
3041 # lines with an RFC3986 like URL
3043 # There are 3 different line length message types:
3044 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3045 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3046 # LONG_LINE all other lines longer than $max_line_length
3048 # if LONG_LINE is ignored, the other 2 types are also ignored
3051 if ($line =~ /^\+/ && $length > $max_line_length) {
3052 my $msg_type = "LONG_LINE";
3054 # Check the allowed long line types first
3056 # logging functions that end in a string that starts
3057 # before $max_line_length
3058 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3059 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3062 # lines with only strings (w/ possible termination)
3063 # #defines with only strings
3064 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3065 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3068 # More special cases
3069 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3070 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3073 # URL ($rawline is used in case the URL is in a comment)
3074 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3077 # Otherwise set the alternate message types
3079 # a comment starts before $max_line_length
3080 } elsif ($line =~ /($;[\s$;]*)$/ &&
3081 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3082 $msg_type = "LONG_LINE_COMMENT"
3084 # a quoted string starts before $max_line_length
3085 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3086 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3087 $msg_type = "LONG_LINE_STRING"
3090 if ($msg_type ne "" &&
3091 (show_type("LONG_LINE") || show_type($msg_type))) {
3093 "line over $max_line_length characters\n" . $herecurr);
3097 # check for adding lines without a newline.
3098 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3099 WARN("MISSING_EOF_NEWLINE",
3100 "adding a line without newline at end of file\n" . $herecurr);
3103 # check we are in a valid source file C or perl if not then ignore this hunk
3104 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3106 # at the beginning of a line any tabs must come first and anything
3107 # more than 8 must use tabs.
3108 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3109 $rawline =~ /^\+\s* \s*/) {
3110 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3112 if (ERROR("CODE_INDENT",
3113 "code indent should use tabs where possible\n" . $herevet) &&
3115 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3119 # check for space before tabs.
3120 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3121 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3122 if (WARN("SPACE_BEFORE_TAB",
3123 "please, no space before tabs\n" . $herevet) &&
3125 while ($fixed[$fixlinenr] =~
3126 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3127 while ($fixed[$fixlinenr] =~
3128 s/(^\+.*) +\t/$1\t/) {}
3132 # check for assignments on the start of a line
3133 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3134 CHK("ASSIGNMENT_CONTINUATIONS",
3135 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3138 # check for && or || at the start of a line
3139 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3140 CHK("LOGICAL_CONTINUATIONS",
3141 "Logical continuations should be on the previous line\n" . $hereprev);
3144 # check indentation starts on a tab stop
3145 if ($perl_version_ok &&
3146 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3147 my $indent = length($1);
3150 "Statements should start on a tabstop\n" . $herecurr) &&
3152 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3157 # check multi-line statement indentation matches previous line
3158 if ($perl_version_ok &&
3159 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3160 $prevline =~ /^\+(\t*)(.*)$/;
3164 my $pos = pos_last_openparen($rest);
3166 $line =~ /^(\+| )([ \t]*)/;
3169 my $goodtabindent = $oldindent .
3172 my $goodspaceindent = $oldindent . " " x $pos;
3174 if ($newindent ne $goodtabindent &&
3175 $newindent ne $goodspaceindent) {
3177 if (CHK("PARENTHESIS_ALIGNMENT",
3178 "Alignment should match open parenthesis\n" . $hereprev) &&
3179 $fix && $line =~ /^\+/) {
3180 $fixed[$fixlinenr] =~
3181 s/^\+[ \t]*/\+$goodtabindent/;
3187 # check for space after cast like "(int) foo" or "(struct foo) bar"
3188 # avoid checking a few false positives:
3189 # "sizeof(<type>)" or "__alignof__(<type>)"
3190 # function pointer declarations like "(*foo)(int) = bar;"
3191 # structure definitions like "(struct foo) { 0 };"
3192 # multiline macros that define functions
3193 # known attributes or the __attribute__ keyword
3194 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3195 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3197 "No space is necessary after a cast\n" . $herecurr) &&
3199 $fixed[$fixlinenr] =~
3200 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3204 # Block comment styles
3205 # Networking with an initial /*
3206 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3207 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3208 $rawline =~ /^\+[ \t]*\*/ &&
3210 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3211 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3214 # Block comments use * on subsequent lines
3215 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3216 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3217 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3218 $rawline =~ /^\+/ && #line is new
3219 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3220 WARN("BLOCK_COMMENT_STYLE",
3221 "Block comments use * on subsequent lines\n" . $hereprev);
3224 # Block comments use */ on trailing lines
3225 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3226 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3227 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3228 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3229 WARN("BLOCK_COMMENT_STYLE",
3230 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3233 # Block comment * alignment
3234 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3235 $line =~ /^\+[ \t]*$;/ && #leading comment
3236 $rawline =~ /^\+[ \t]*\*/ && #leading *
3237 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3238 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3239 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3241 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3243 $oldindent = expand_tabs($1);
3245 $prevrawline =~ m@^\+(.*/?)\*@;
3246 $oldindent = expand_tabs($1);
3248 $rawline =~ m@^\+([ \t]*)\*@;
3250 $newindent = expand_tabs($newindent);
3251 if (length($oldindent) ne length($newindent)) {
3252 WARN("BLOCK_COMMENT_STYLE",
3253 "Block comments should align the * on each line\n" . $hereprev);
3257 # check for missing blank lines after struct/union declarations
3258 # with exceptions for various attributes and macros
3259 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3261 !($line =~ /^\+\s*$/ ||
3262 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3263 $line =~ /^\+\s*MODULE_/i ||
3264 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3265 $line =~ /^\+[a-z_]*init/ ||
3266 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3267 $line =~ /^\+\s*DECLARE/ ||
3268 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3269 $line =~ /^\+\s*__setup/)) {
3270 if (CHK("LINE_SPACING",
3271 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3273 fix_insert_line($fixlinenr, "\+");
3277 # check for multiple consecutive blank lines
3278 if ($prevline =~ /^[\+ ]\s*$/ &&
3279 $line =~ /^\+\s*$/ &&
3280 $last_blank_line != ($linenr - 1)) {
3281 if (CHK("LINE_SPACING",
3282 "Please don't use multiple blank lines\n" . $hereprev) &&
3284 fix_delete_line($fixlinenr, $rawline);
3287 $last_blank_line = $linenr;
3290 # check for missing blank lines after declarations
3291 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3292 # actual declarations
3293 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3294 # function pointer declarations
3295 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3296 # foo bar; where foo is some local typedef or #define
3297 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3298 # known declaration macros
3299 $prevline =~ /^\+\s+$declaration_macros/) &&
3300 # for "else if" which can look like "$Ident $Ident"
3301 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3302 # other possible extensions of declaration lines
3303 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3304 # not starting a section or a macro "\" extended line
3305 $prevline =~ /(?:\{\s*|\\)$/) &&
3306 # looks like a declaration
3307 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3308 # function pointer declarations
3309 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3310 # foo bar; where foo is some local typedef or #define
3311 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3312 # known declaration macros
3313 $sline =~ /^\+\s+$declaration_macros/ ||
3314 # start of struct or union or enum
3315 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3316 # start or end of block or continuation of declaration
3317 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3318 # bitfield continuation
3319 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3320 # other possible extensions of declaration lines
3321 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3322 # indentation of previous and current line are the same
3323 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3324 if (WARN("LINE_SPACING",
3325 "Missing a blank line after declarations\n" . $hereprev) &&
3327 fix_insert_line($fixlinenr, "\+");
3331 # check for spaces at the beginning of a line.
3333 # 1) within comments
3334 # 2) indented preprocessor commands
3336 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3337 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3338 if (WARN("LEADING_SPACE",
3339 "please, no spaces at the start of a line\n" . $herevet) &&
3341 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3345 # check we are in a valid C source file if not then ignore this hunk
3346 next if ($realfile !~ /\.(h|c)$/);
3348 # check for unusual line ending [ or (
3349 if ($line =~ /^\+.*([\[\(])\s*$/) {
3350 CHK("OPEN_ENDED_LINE",
3351 "Lines should not end with a '$1'\n" . $herecurr);
3354 # check if this appears to be the start function declaration, save the name
3355 if ($sline =~ /^\+\{\s*$/ &&
3356 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3357 $context_function = $1;
3360 # check if this appears to be the end of function declaration
3361 if ($sline =~ /^\+\}\s*$/) {
3362 undef $context_function;
3365 # check indentation of any line with a bare else
3366 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3367 # if the previous line is a break or return and is indented 1 tab more...
3368 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3369 my $tabs = length($1) + 1;
3370 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3371 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3372 defined $lines[$linenr] &&
3373 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3374 WARN("UNNECESSARY_ELSE",
3375 "else is not generally useful after a break or return\n" . $hereprev);
3379 # check indentation of a line with a break;
3380 # if the previous line is a goto or return and is indented the same # of tabs
3381 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3383 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3384 WARN("UNNECESSARY_BREAK",
3385 "break is not useful after a goto or return\n" . $hereprev);
3389 # check for RCS/CVS revision markers
3390 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3392 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3395 # check for old HOTPLUG __dev<foo> section markings
3396 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3397 WARN("HOTPLUG_SECTION",
3398 "Using $1 is unnecessary\n" . $herecurr);
3401 # Check for potential 'bare' types
3402 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3404 #print "LINE<$line>\n";
3405 if ($linenr > $suppress_statement &&
3406 $realcnt && $sline =~ /.\s*\S/) {
3407 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3408 ctx_statement_block($linenr, $realcnt, 0);
3409 $stat =~ s/\n./\n /g;
3410 $cond =~ s/\n./\n /g;
3412 #print "linenr<$linenr> <$stat>\n";
3413 # If this statement has no statement boundaries within
3414 # it there is no point in retrying a statement scan
3415 # until we hit end of it.
3416 my $frag = $stat; $frag =~ s/;+\s*$//;
3417 if ($frag !~ /(?:{|;)/) {
3418 #print "skip<$line_nr_next>\n";
3419 $suppress_statement = $line_nr_next;
3422 # Find the real next line.
3423 $realline_next = $line_nr_next;
3424 if (defined $realline_next &&
3425 (!defined $lines[$realline_next - 1] ||
3426 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3433 # Ignore goto labels.
3434 if ($s =~ /$Ident:\*$/s) {
3436 # Ignore functions being called
3437 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3439 } elsif ($s =~ /^.\s*else\b/s) {
3441 # declarations always start with types
3442 } 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) {
3445 possible($type, "A:" . $s);
3447 # definitions in global scope can only start with types
3448 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3449 possible($1, "B:" . $s);
3452 # any (foo ... *) is a pointer cast, and foo is a type
3453 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3454 possible($1, "C:" . $s);
3457 # Check for any sort of function declaration.
3458 # int foo(something bar, other baz);
3459 # void (*store_gdt)(x86_descr_ptr *);
3460 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3461 my ($name_len) = length($1);
3464 substr($ctx, 0, $name_len + 1, '');
3465 $ctx =~ s/\)[^\)]*$//;
3467 for my $arg (split(/\s*,\s*/, $ctx)) {
3468 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3470 possible($1, "D:" . $s);
3478 # Checks which may be anchored in the context.
3481 # Check for switch () and associated case and default
3482 # statements should be at the same indent.
3483 if ($line=~/\bswitch\s*\(.*\)/) {
3486 my @ctx = ctx_block_outer($linenr, $realcnt);
3488 for my $ctx (@ctx) {
3489 my ($clen, $cindent) = line_stats($ctx);
3490 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3491 $indent != $cindent) {
3492 $err .= "$sep$ctx\n";
3499 ERROR("SWITCH_CASE_INDENT_LEVEL",
3500 "switch and case should be at the same indent\n$hereline$err");
3504 # if/while/etc brace do not go on next line, unless defining a do while loop,
3505 # or if that brace on the next line is for something else
3506 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3507 my $pre_ctx = "$1$2";
3509 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3511 if ($line =~ /^\+\t{6,}/) {
3512 WARN("DEEP_INDENTATION",
3513 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3516 my $ctx_cnt = $realcnt - $#ctx - 1;
3517 my $ctx = join("\n", @ctx);
3519 my $ctx_ln = $linenr;
3520 my $ctx_skip = $realcnt;
3522 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3523 defined $lines[$ctx_ln - 1] &&
3524 $lines[$ctx_ln - 1] =~ /^-/)) {
3525 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3526 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3530 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3531 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3533 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3535 "that open brace { should be on the previous line\n" .
3536 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3538 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3539 $ctx =~ /\)\s*\;\s*$/ &&
3540 defined $lines[$ctx_ln - 1])
3542 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3543 if ($nindent > $indent) {
3544 WARN("TRAILING_SEMICOLON",
3545 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3546 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3551 # Check relative indent for conditionals and blocks.
3552 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3553 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3554 ctx_statement_block($linenr, $realcnt, 0)
3555 if (!defined $stat);
3556 my ($s, $c) = ($stat, $cond);
3558 substr($s, 0, length($c), '');
3560 # remove inline comments
3564 # Find out how long the conditional actually is.
3565 my @newlines = ($c =~ /\n/gs);
3566 my $cond_lines = 1 + $#newlines;
3568 # Make sure we remove the line prefixes as we have
3569 # none on the first line, and are going to readd them
3572 while ($s =~ /\n\s+\\\n/) {
3573 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3576 # We want to check the first line inside the block
3577 # starting at the end of the conditional, so remove:
3578 # 1) any blank line termination
3579 # 2) any opening brace { on end of the line
3581 my $continuation = 0;
3583 $s =~ s/^.*\bdo\b//;
3585 if ($s =~ s/^\s*\\//) {
3588 if ($s =~ s/^\s*?\n//) {
3593 # Also ignore a loop construct at the end of a
3594 # preprocessor statement.
3595 if (($prevline =~ /^.\s*#\s*define\s/ ||
3596 $prevline =~ /\\\s*$/) && $continuation == 0) {
3602 while ($cond_ptr != $cond_lines) {
3603 $cond_ptr = $cond_lines;
3605 # If we see an #else/#elif then the code
3607 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3612 # 1) blank lines, they should be at 0,
3613 # 2) preprocessor lines, and
3615 if ($continuation ||
3617 $s =~ /^\s*#\s*?/ ||
3618 $s =~ /^\s*$Ident\s*:/) {
3619 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3620 if ($s =~ s/^.*?\n//) {
3626 my (undef, $sindent) = line_stats("+" . $s);
3627 my $stat_real = raw_line($linenr, $cond_lines);
3629 # Check if either of these lines are modified, else
3630 # this is not this patch's fault.
3631 if (!defined($stat_real) ||
3632 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3635 if (defined($stat_real) && $cond_lines > 1) {
3636 $stat_real = "[...]\n$stat_real";
3639 #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";
3641 if ($check && $s ne '' &&
3642 (($sindent % 8) != 0 ||
3643 ($sindent < $indent) ||
3644 ($sindent == $indent &&
3645 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3646 ($sindent > $indent + 8))) {
3647 WARN("SUSPECT_CODE_INDENT",
3648 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3652 # Track the 'values' across context and added lines.
3653 my $opline = $line; $opline =~ s/^./ /;
3654 my ($curr_values, $curr_vars) =
3655 annotate_values($opline . "\n", $prev_values);
3656 $curr_values = $prev_values . $curr_values;
3658 my $outline = $opline; $outline =~ s/\t/ /g;
3659 print "$linenr > .$outline\n";
3660 print "$linenr > $curr_values\n";
3661 print "$linenr > $curr_vars\n";
3663 $prev_values = substr($curr_values, -1);
3665 #ignore lines not being added
3666 next if ($line =~ /^[^\+]/);
3668 # check for dereferences that span multiple lines
3669 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3670 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3671 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3673 $line =~ /^.\s*($Lval)/;
3676 WARN("MULTILINE_DEREFERENCE",
3677 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3680 # check for declarations of signed or unsigned without int
3681 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3684 $var = "" if (!defined $var);
3685 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3689 $pointer = "" if (!defined $pointer);
3691 if (WARN("UNSPECIFIED_INT",
3692 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3694 my $decl = trim($sign) . " int ";
3695 my $comp_pointer = $pointer;
3696 $comp_pointer =~ s/\s//g;
3697 $decl .= $comp_pointer;
3698 $decl = rtrim($decl) if ($var eq "");
3699 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3704 # TEST: allow direct testing of the type matcher.
3706 if ($line =~ /^.\s*$Declare\s*$/) {
3708 "TEST: is type\n" . $herecurr);
3709 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3710 ERROR("TEST_NOT_TYPE",
3711 "TEST: is not type ($1 is)\n". $herecurr);
3715 # TEST: allow direct testing of the attribute matcher.
3717 if ($line =~ /^.\s*$Modifier\s*$/) {
3719 "TEST: is attr\n" . $herecurr);
3720 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3721 ERROR("TEST_NOT_ATTR",
3722 "TEST: is not attr ($1 is)\n". $herecurr);
3727 # check for initialisation to aggregates open brace on the next line
3728 if ($line =~ /^.\s*{/ &&
3729 $prevline =~ /(?:^|[^=])=\s*$/) {
3730 if (ERROR("OPEN_BRACE",
3731 "that open brace { should be on the previous line\n" . $hereprev) &&
3732 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3733 fix_delete_line($fixlinenr - 1, $prevrawline);
3734 fix_delete_line($fixlinenr, $rawline);
3735 my $fixedline = $prevrawline;
3736 $fixedline =~ s/\s*=\s*$/ = {/;
3737 fix_insert_line($fixlinenr, $fixedline);
3739 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3740 fix_insert_line($fixlinenr, $fixedline);
3745 # Checks which are anchored on the added line.
3748 # check for malformed paths in #include statements (uses RAW line)
3749 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3751 if ($path =~ m{//}) {
3752 ERROR("MALFORMED_INCLUDE",
3753 "malformed #include filename\n" . $herecurr);
3755 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3756 ERROR("UAPI_INCLUDE",
3757 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3761 # no C99 // comments
3762 if ($line =~ m{//}) {
3763 if (ERROR("C99_COMMENTS",
3764 "do not use C99 // comments\n" . $herecurr) &&
3766 my $line = $fixed[$fixlinenr];
3767 if ($line =~ /\/\/(.*)$/) {
3768 my $comment = trim($1);
3769 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3773 # Remove C99 comments.
3775 $opline =~ s@//.*@@;
3777 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3778 # the whole statement.
3779 #print "APW <$lines[$realline_next - 1]>\n";
3780 if (defined $realline_next &&
3781 exists $lines[$realline_next - 1] &&
3782 !defined $suppress_export{$realline_next} &&
3783 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3784 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3785 # Handle definitions which produce identifiers with
3788 # EXPORT_SYMBOL(something_foo);
3790 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3791 $name =~ /^${Ident}_$2/) {
3792 #print "FOO C name<$name>\n";
3793 $suppress_export{$realline_next} = 1;
3795 } elsif ($stat !~ /(?:
3797 ^.DEFINE_$Ident\(\Q$name\E\)|
3798 ^.DECLARE_$Ident\(\Q$name\E\)|
3799 ^.LIST_HEAD\(\Q$name\E\)|
3800 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3801 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3803 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3804 $suppress_export{$realline_next} = 2;
3806 $suppress_export{$realline_next} = 1;
3809 if (!defined $suppress_export{$linenr} &&
3810 $prevline =~ /^.\s*$/ &&
3811 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3812 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3813 #print "FOO B <$lines[$linenr - 1]>\n";
3814 $suppress_export{$linenr} = 2;
3816 if (defined $suppress_export{$linenr} &&
3817 $suppress_export{$linenr} == 2) {
3818 WARN("EXPORT_SYMBOL",
3819 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3822 # check for global initialisers.
3823 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3824 if (ERROR("GLOBAL_INITIALISERS",
3825 "do not initialise globals to $1\n" . $herecurr) &&
3827 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3830 # check for static initialisers.
3831 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3832 if (ERROR("INITIALISED_STATIC",
3833 "do not initialise statics to $1\n" .
3836 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3840 # check for misordered declarations of char/short/int/long with signed/unsigned
3841 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3843 WARN("MISORDERED_TYPE",
3844 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3847 # check for unnecessary <signed> int declarations of short/long/long long
3848 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3849 my $type = trim($1);
3850 next if ($type !~ /\bint\b/);
3851 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3852 my $new_type = $type;
3853 $new_type =~ s/\b\s*int\s*\b/ /;
3854 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3855 $new_type =~ s/^const\s+//;
3856 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3857 $new_type = "const $new_type" if ($type =~ /^const\b/);
3858 $new_type =~ s/\s+/ /g;
3859 $new_type = trim($new_type);
3860 if (WARN("UNNECESSARY_INT",
3861 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3863 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3867 # check for static const char * arrays.
3868 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3869 WARN("STATIC_CONST_CHAR_ARRAY",
3870 "static const char * array should probably be static const char * const\n" .
3874 # check for static char foo[] = "bar" declarations.
3875 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3876 WARN("STATIC_CONST_CHAR_ARRAY",
3877 "static char array declaration should probably be static const char\n" .
3881 # check for const <foo> const where <foo> is not a pointer or array type
3882 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3884 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3886 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3887 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3889 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3893 # check for non-global char *foo[] = {"bar", ...} declarations.
3894 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3895 WARN("STATIC_CONST_CHAR_ARRAY",
3896 "char * array declaration might be better as static const\n" .
3900 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3901 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3903 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3905 if (WARN("ARRAY_SIZE",
3906 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3908 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3913 # check for function declarations without arguments like "int foo()"
3914 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3915 if (ERROR("FUNCTION_WITHOUT_ARGS",
3916 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3918 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3922 # check for new typedefs, only function parameters and sparse annotations
3924 if ($line =~ /\btypedef\s/ &&
3925 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3926 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3927 $line !~ /\b$typeTypedefs\b/ &&
3928 $line !~ /\b__bitwise\b/) {
3929 WARN("NEW_TYPEDEFS",
3930 "do not add new typedefs\n" . $herecurr);
3933 # * goes on variable not on type
3935 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3937 my ($ident, $from, $to) = ($1, $2, $2);
3939 # Should start with a space.
3940 $to =~ s/^(\S)/ $1/;
3941 # Should not end with a space.
3943 # '*'s should not have spaces between.
3944 while ($to =~ s/\*\s+\*/\*\*/) {
3947 ## print "1: from<$from> to<$to> ident<$ident>\n";
3949 if (ERROR("POINTER_LOCATION",
3950 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3952 my $sub_from = $ident;
3953 my $sub_to = $ident;
3954 $sub_to =~ s/\Q$from\E/$to/;
3955 $fixed[$fixlinenr] =~
3956 s@\Q$sub_from\E@$sub_to@;
3960 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3962 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3964 # Should start with a space.
3965 $to =~ s/^(\S)/ $1/;
3966 # Should not end with a space.
3968 # '*'s should not have spaces between.
3969 while ($to =~ s/\*\s+\*/\*\*/) {
3971 # Modifiers should have spaces.
3972 $to =~ s/(\b$Modifier$)/$1 /;
3974 ## print "2: from<$from> to<$to> ident<$ident>\n";
3975 if ($from ne $to && $ident !~ /^$Modifier$/) {
3976 if (ERROR("POINTER_LOCATION",
3977 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3980 my $sub_from = $match;
3981 my $sub_to = $match;
3982 $sub_to =~ s/\Q$from\E/$to/;
3983 $fixed[$fixlinenr] =~
3984 s@\Q$sub_from\E@$sub_to@;
3989 # avoid BUG() or BUG_ON()
3990 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3991 my $msg_level = \&WARN;
3992 $msg_level = \&CHK if ($file);
3993 &{$msg_level}("AVOID_BUG",
3994 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3997 # avoid LINUX_VERSION_CODE
3998 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3999 WARN("LINUX_VERSION_CODE",
4000 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4003 # check for uses of printk_ratelimit
4004 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4005 WARN("PRINTK_RATELIMITED",
4006 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4009 # printk should use KERN_* levels
4010 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4011 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4012 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4015 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4017 my $level = lc($orig);
4018 $level = "warn" if ($level eq "warning");
4019 my $level2 = $level;
4020 $level2 = "dbg" if ($level eq "debug");
4021 WARN("PREFER_PR_LEVEL",
4022 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4025 if ($line =~ /\bpr_warning\s*\(/) {
4026 if (WARN("PREFER_PR_LEVEL",
4027 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4029 $fixed[$fixlinenr] =~
4030 s/\bpr_warning\b/pr_warn/;
4034 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4036 my $level = lc($orig);
4037 $level = "warn" if ($level eq "warning");
4038 $level = "dbg" if ($level eq "debug");
4039 WARN("PREFER_DEV_LEVEL",
4040 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4043 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4044 # number of false positives, but assembly files are not checked, so at
4045 # least the arch entry code will not trigger this warning.
4046 if ($line =~ /\bENOSYS\b/) {
4048 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4051 # function brace can't be on same line, except for #defines of do while,
4052 # or if closed on same line
4053 if ($perl_version_ok &&
4054 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4055 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4057 if (ERROR("OPEN_BRACE",
4058 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4060 fix_delete_line($fixlinenr, $rawline);
4061 my $fixed_line = $rawline;
4062 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4065 fix_insert_line($fixlinenr, ltrim($line1));
4066 fix_insert_line($fixlinenr, "\+{");
4067 if ($line2 !~ /^\s*$/) {
4068 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4073 # open braces for enum, union and struct go on the same line.
4074 if ($line =~ /^.\s*{/ &&
4075 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4076 if (ERROR("OPEN_BRACE",
4077 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4078 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4079 fix_delete_line($fixlinenr - 1, $prevrawline);
4080 fix_delete_line($fixlinenr, $rawline);
4081 my $fixedline = rtrim($prevrawline) . " {";
4082 fix_insert_line($fixlinenr, $fixedline);
4083 $fixedline = $rawline;
4084 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4085 if ($fixedline !~ /^\+\s*$/) {
4086 fix_insert_line($fixlinenr, $fixedline);
4091 # missing space after union, struct or enum definition
4092 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4094 "missing space after $1 definition\n" . $herecurr) &&
4096 $fixed[$fixlinenr] =~
4097 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4101 # Function pointer declarations
4102 # check spacing between type, funcptr, and args
4103 # canonical declaration is "type (*funcptr)(args...)"
4104 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4106 my $pre_pointer_space = $2;
4107 my $post_pointer_space = $3;
4109 my $post_funcname_space = $5;
4110 my $pre_args_space = $6;
4112 # the $Declare variable will capture all spaces after the type
4113 # so check it for a missing trailing missing space but pointer return types
4114 # don't need a space so don't warn for those.
4115 my $post_declare_space = "";
4116 if ($declare =~ /(\s+)$/) {
4117 $post_declare_space = $1;
4118 $declare = rtrim($declare);
4120 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4122 "missing space after return type\n" . $herecurr);
4123 $post_declare_space = " ";
4126 # unnecessary space "type (*funcptr)(args...)"
4127 # This test is not currently implemented because these declarations are
4129 # int foo(int bar, ...)
4130 # and this is form shouldn't/doesn't generate a checkpatch warning.
4132 # elsif ($declare =~ /\s{2,}$/) {
4134 # "Multiple spaces after return type\n" . $herecurr);
4137 # unnecessary space "type ( *funcptr)(args...)"
4138 if (defined $pre_pointer_space &&
4139 $pre_pointer_space =~ /^\s/) {
4141 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4144 # unnecessary space "type (* funcptr)(args...)"
4145 if (defined $post_pointer_space &&
4146 $post_pointer_space =~ /^\s/) {
4148 "Unnecessary space before function pointer name\n" . $herecurr);
4151 # unnecessary space "type (*funcptr )(args...)"
4152 if (defined $post_funcname_space &&
4153 $post_funcname_space =~ /^\s/) {
4155 "Unnecessary space after function pointer name\n" . $herecurr);
4158 # unnecessary space "type (*funcptr) (args...)"
4159 if (defined $pre_args_space &&
4160 $pre_args_space =~ /^\s/) {
4162 "Unnecessary space before function pointer arguments\n" . $herecurr);
4165 if (show_type("SPACING") && $fix) {
4166 $fixed[$fixlinenr] =~
4167 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4171 # check for spacing round square brackets; allowed:
4172 # 1. with a type on the left -- int [] a;
4173 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4174 # 3. inside a curly brace -- = { [0...10] = 5 }
4175 while ($line =~ /(.*?\s)\[/g) {
4176 my ($where, $prefix) = ($-[1], $1);
4177 if ($prefix !~ /$Type\s+$/ &&
4178 ($where != 0 || $prefix !~ /^.\s+$/) &&
4179 $prefix !~ /[{,:]\s+$/) {
4180 if (ERROR("BRACKET_SPACE",
4181 "space prohibited before open square bracket '['\n" . $herecurr) &&
4183 $fixed[$fixlinenr] =~
4184 s/^(\+.*?)\s+\[/$1\[/;
4189 # check for spaces between functions and their parentheses.
4190 while ($line =~ /($Ident)\s+\(/g) {
4192 my $ctx_before = substr($line, 0, $-[1]);
4193 my $ctx = "$ctx_before$name";
4195 # Ignore those directives where spaces _are_ permitted.
4197 if|for|while|switch|return|case|
4198 volatile|__volatile__|
4199 __attribute__|format|__extension__|
4202 # cpp #define statements have non-optional spaces, ie
4203 # if there is a space between the name and the open
4204 # parenthesis it is simply not a parameter group.
4205 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4207 # cpp #elif statement condition may start with a (
4208 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4210 # If this whole things ends with a type its most
4211 # likely a typedef for a function.
4212 } elsif ($ctx =~ /$Type$/) {
4216 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4218 $fixed[$fixlinenr] =~
4219 s/\b$name\s+\(/$name\(/;
4224 # Check operator spacing.
4225 if (!($line=~/\#\s*include/)) {
4226 my $fixed_line = "";
4230 <<=|>>=|<=|>=|==|!=|
4231 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4232 =>|->|<<|>>|<|>|=|!|~|
4233 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4236 my @elements = split(/($ops|;)/, $opline);
4238 ## print("element count: <" . $#elements . ">\n");
4239 ## foreach my $el (@elements) {
4240 ## print("el: <$el>\n");
4243 my @fix_elements = ();
4246 foreach my $el (@elements) {
4247 push(@fix_elements, substr($rawline, $off, length($el)));
4248 $off += length($el);
4253 my $blank = copy_spacing($opline);
4254 my $last_after = -1;
4256 for (my $n = 0; $n < $#elements; $n += 2) {
4258 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4260 ## print("n: <$n> good: <$good>\n");
4262 $off += length($elements[$n]);
4264 # Pick up the preceding and succeeding characters.
4265 my $ca = substr($opline, 0, $off);
4267 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4268 $cc = substr($opline, $off + length($elements[$n + 1]));
4270 my $cb = "$ca$;$cc";
4273 $a = 'V' if ($elements[$n] ne '');
4274 $a = 'W' if ($elements[$n] =~ /\s$/);
4275 $a = 'C' if ($elements[$n] =~ /$;$/);
4276 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4277 $a = 'O' if ($elements[$n] eq '');
4278 $a = 'E' if ($ca =~ /^\s*$/);
4280 my $op = $elements[$n + 1];
4283 if (defined $elements[$n + 2]) {
4284 $c = 'V' if ($elements[$n + 2] ne '');
4285 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4286 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4287 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4288 $c = 'O' if ($elements[$n + 2] eq '');
4289 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4294 my $ctx = "${a}x${c}";
4296 my $at = "(ctx:$ctx)";
4298 my $ptr = substr($blank, 0, $off) . "^";
4299 my $hereptr = "$hereline$ptr\n";
4301 # Pull out the value of this operator.
4302 my $op_type = substr($curr_values, $off + 1, 1);
4304 # Get the full operator variant.
4305 my $opv = $op . substr($curr_vars, $off, 1);
4307 # Ignore operators passed as parameters.
4308 if ($op_type ne 'V' &&
4309 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4312 # } elsif ($op =~ /^$;+$/) {
4314 # ; should have either the end of line or a space or \ after it
4315 } elsif ($op eq ';') {
4316 if ($ctx !~ /.x[WEBC]/ &&
4317 $cc !~ /^\\/ && $cc !~ /^;/) {
4318 if (ERROR("SPACING",
4319 "space required after that '$op' $at\n" . $hereptr)) {
4320 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4326 } elsif ($op eq '//') {
4328 # : when part of a bitfield
4329 } elsif ($opv eq ':B') {
4330 # skip the bitfield test for now
4334 } elsif ($op eq '->') {
4335 if ($ctx =~ /Wx.|.xW/) {
4336 if (ERROR("SPACING",
4337 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4338 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4339 if (defined $fix_elements[$n + 2]) {
4340 $fix_elements[$n + 2] =~ s/^\s+//;
4346 # , must not have a space before and must have a space on the right.
4347 } elsif ($op eq ',') {
4348 my $rtrim_before = 0;
4349 my $space_after = 0;
4350 if ($ctx =~ /Wx./) {
4351 if (ERROR("SPACING",
4352 "space prohibited before that '$op' $at\n" . $hereptr)) {
4357 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4358 if (ERROR("SPACING",
4359 "space required after that '$op' $at\n" . $hereptr)) {
4365 if ($rtrim_before || $space_after) {
4366 if ($rtrim_before) {
4367 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4369 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4376 # '*' as part of a type definition -- reported already.
4377 } elsif ($opv eq '*_') {
4378 #warn "'*' is part of type\n";
4380 # unary operators should have a space before and
4381 # none after. May be left adjacent to another
4382 # unary operator, or a cast
4383 } elsif ($op eq '!' || $op eq '~' ||
4384 $opv eq '*U' || $opv eq '-U' ||
4385 $opv eq '&U' || $opv eq '&&U') {
4386 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4387 if (ERROR("SPACING",
4388 "space required before that '$op' $at\n" . $hereptr)) {
4389 if ($n != $last_after + 2) {
4390 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4395 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4396 # A unary '*' may be const
4398 } elsif ($ctx =~ /.xW/) {
4399 if (ERROR("SPACING",
4400 "space prohibited after that '$op' $at\n" . $hereptr)) {
4401 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4402 if (defined $fix_elements[$n + 2]) {
4403 $fix_elements[$n + 2] =~ s/^\s+//;
4409 # unary ++ and unary -- are allowed no space on one side.
4410 } elsif ($op eq '++' or $op eq '--') {
4411 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4412 if (ERROR("SPACING",
4413 "space required one side of that '$op' $at\n" . $hereptr)) {
4414 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4418 if ($ctx =~ /Wx[BE]/ ||
4419 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4420 if (ERROR("SPACING",
4421 "space prohibited before that '$op' $at\n" . $hereptr)) {
4422 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4426 if ($ctx =~ /ExW/) {
4427 if (ERROR("SPACING",
4428 "space prohibited after that '$op' $at\n" . $hereptr)) {
4429 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4430 if (defined $fix_elements[$n + 2]) {
4431 $fix_elements[$n + 2] =~ s/^\s+//;
4437 # << and >> may either have or not have spaces both sides
4438 } elsif ($op eq '<<' or $op eq '>>' or
4439 $op eq '&' or $op eq '^' or $op eq '|' or
4440 $op eq '+' or $op eq '-' or
4441 $op eq '*' or $op eq '/' or
4445 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4447 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4448 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4449 $fix_elements[$n + 2] =~ s/^\s+//;
4452 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4454 "space preferred before that '$op' $at\n" . $hereptr)) {
4455 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4459 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4460 if (ERROR("SPACING",
4461 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4462 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4463 if (defined $fix_elements[$n + 2]) {
4464 $fix_elements[$n + 2] =~ s/^\s+//;
4470 # A colon needs no spaces before when it is
4471 # terminating a case value or a label.
4472 } elsif ($opv eq ':C' || $opv eq ':L') {
4473 if ($ctx =~ /Wx./) {
4474 if (ERROR("SPACING",
4475 "space prohibited before that '$op' $at\n" . $hereptr)) {
4476 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4481 # All the others need spaces both sides.
4482 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4485 # Ignore email addresses <foo@bar>
4487 $cc =~ /^\S+\@\S+>/) ||
4489 $ca =~ /<\S+\@\S+$/))
4494 # for asm volatile statements
4495 # ignore a colon with another
4496 # colon immediately before or after
4498 ($ca =~ /:$/ || $cc =~ /^:/)) {
4502 # messages are ERROR, but ?: are CHK
4504 my $msg_level = \&ERROR;
4505 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4507 if (&{$msg_level}("SPACING",
4508 "spaces required around that '$op' $at\n" . $hereptr)) {
4509 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4510 if (defined $fix_elements[$n + 2]) {
4511 $fix_elements[$n + 2] =~ s/^\s+//;
4517 $off += length($elements[$n + 1]);
4519 ## print("n: <$n> GOOD: <$good>\n");
4521 $fixed_line = $fixed_line . $good;
4524 if (($#elements % 2) == 0) {
4525 $fixed_line = $fixed_line . $fix_elements[$#elements];
4528 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4529 $fixed[$fixlinenr] = $fixed_line;
4535 # check for whitespace before a non-naked semicolon
4536 if ($line =~ /^\+.*\S\s+;\s*$/) {
4538 "space prohibited before semicolon\n" . $herecurr) &&
4540 1 while $fixed[$fixlinenr] =~
4541 s/^(\+.*\S)\s+;/$1;/;
4545 # check for multiple assignments
4546 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4547 CHK("MULTIPLE_ASSIGNMENTS",
4548 "multiple assignments should be avoided\n" . $herecurr);
4551 ## # check for multiple declarations, allowing for a function declaration
4553 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4554 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4556 ## # Remove any bracketed sections to ensure we do not
4557 ## # falsly report the parameters of functions.
4559 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4561 ## if ($ln =~ /,/) {
4562 ## WARN("MULTIPLE_DECLARATION",
4563 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4567 #need space before brace following if, while, etc
4568 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4569 $line =~ /\b(?:else|do)\{/) {
4570 if (ERROR("SPACING",
4571 "space required before the open brace '{'\n" . $herecurr) &&
4573 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4577 ## # check for blank lines before declarations
4578 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4579 ## $prevrawline =~ /^.\s*$/) {
4581 ## "No blank lines before declarations\n" . $hereprev);
4585 # closing brace should have a space following it when it has anything
4587 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4588 if (ERROR("SPACING",
4589 "space required after that close brace '}'\n" . $herecurr) &&
4591 $fixed[$fixlinenr] =~
4592 s/}((?!(?:,|;|\)))\S)/} $1/;
4596 # check spacing on square brackets
4597 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4598 if (ERROR("SPACING",
4599 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4601 $fixed[$fixlinenr] =~
4605 if ($line =~ /\s\]/) {
4606 if (ERROR("SPACING",
4607 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4609 $fixed[$fixlinenr] =~
4614 # check spacing on parentheses
4615 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4616 $line !~ /for\s*\(\s+;/) {
4617 if (ERROR("SPACING",
4618 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4620 $fixed[$fixlinenr] =~
4624 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4625 $line !~ /for\s*\(.*;\s+\)/ &&
4626 $line !~ /:\s+\)/) {
4627 if (ERROR("SPACING",
4628 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4630 $fixed[$fixlinenr] =~
4635 # check unnecessary parentheses around addressof/dereference single $Lvals
4636 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4638 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4640 if (CHK("UNNECESSARY_PARENTHESES",
4641 "Unnecessary parentheses around $var\n" . $herecurr) &&
4643 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4647 # check for unnecessary parentheses around function pointer uses
4648 # ie: (foo->bar)(); should be foo->bar();
4649 # but not "if (foo->bar) (" to avoid some false positives
4650 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4652 if (CHK("UNNECESSARY_PARENTHESES",
4653 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4655 my $var2 = deparenthesize($var);
4657 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4661 # check for unnecessary parentheses around comparisons in if uses
4662 # when !drivers/staging or command-line uses --strict
4663 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4664 $perl_version_ok && defined($stat) &&
4665 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4667 my $test = substr($2, 1, -1);
4669 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4671 # avoid parentheses around potential macro args
4672 next if ($match =~ /^\s*\w+\s*$/);
4673 if (!defined($herectx)) {
4674 $herectx = $here . "\n";
4675 my $cnt = statement_rawlines($if_stat);
4676 for (my $n = 0; $n < $cnt; $n++) {
4677 my $rl = raw_line($linenr, $n);
4678 $herectx .= $rl . "\n";
4679 last if $rl =~ /^[ \+].*\{/;
4682 CHK("UNNECESSARY_PARENTHESES",
4683 "Unnecessary parentheses around '$match'\n" . $herectx);
4687 #goto labels aren't indented, allow a single space however
4688 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4689 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4690 if (WARN("INDENTED_LABEL",
4691 "labels should not be indented\n" . $herecurr) &&
4693 $fixed[$fixlinenr] =~
4698 # return is not a function
4699 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4701 if ($perl_version_ok &&
4702 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4704 $value = deparenthesize($value);
4705 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4706 ERROR("RETURN_PARENTHESES",
4707 "return is not a function, parentheses are not required\n" . $herecurr);
4709 } elsif ($spacing !~ /\s+/) {
4711 "space required before the open parenthesis '('\n" . $herecurr);
4715 # unnecessary return in a void function
4716 # at end-of-function, with the previous line a single leading tab, then return;
4717 # and the line before that not a goto label target like "out:"
4718 if ($sline =~ /^[ \+]}\s*$/ &&
4719 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4721 $lines[$linenr - 3] =~ /^[ +]/ &&
4722 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4724 "void function return statements are not generally useful\n" . $hereprev);
4727 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4728 if ($perl_version_ok &&
4729 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4730 my $openparens = $1;
4731 my $count = $openparens =~ tr@\(@\(@;
4733 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4734 my $comp = $4; #Not $1 because of $LvalOrFunc
4735 $msg = " - maybe == should be = ?" if ($comp eq "==");
4736 WARN("UNNECESSARY_PARENTHESES",
4737 "Unnecessary parentheses$msg\n" . $herecurr);
4741 # comparisons with a constant or upper case identifier on the left
4742 # avoid cases like "foo + BAR < baz"
4743 # only fix matches surrounded by parentheses to avoid incorrect
4744 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4745 if ($perl_version_ok &&
4746 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4751 my $newcomp = $comp;
4752 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4753 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4754 WARN("CONSTANT_COMPARISON",
4755 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4759 } elsif ($comp eq "<=") {
4761 } elsif ($comp eq ">") {
4763 } elsif ($comp eq ">=") {
4766 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4770 # Return of what appears to be an errno should normally be negative
4771 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4773 if ($name ne 'EOF' && $name ne 'ERROR') {
4774 WARN("USE_NEGATIVE_ERRNO",
4775 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4779 # Need a space before open parenthesis after if, while etc
4780 if ($line =~ /\b(if|while|for|switch)\(/) {
4781 if (ERROR("SPACING",
4782 "space required before the open parenthesis '('\n" . $herecurr) &&
4784 $fixed[$fixlinenr] =~
4785 s/\b(if|while|for|switch)\(/$1 \(/;
4789 # Check for illegal assignment in if conditional -- and check for trailing
4790 # statements after the conditional.
4791 if ($line =~ /do\s*(?!{)/) {
4792 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4793 ctx_statement_block($linenr, $realcnt, 0)
4794 if (!defined $stat);
4795 my ($stat_next) = ctx_statement_block($line_nr_next,
4796 $remain_next, $off_next);
4797 $stat_next =~ s/\n./\n /g;
4798 ##print "stat<$stat> stat_next<$stat_next>\n";
4800 if ($stat_next =~ /^\s*while\b/) {
4801 # If the statement carries leading newlines,
4802 # then count those as offsets.
4804 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4806 statement_rawlines($whitespace) - 1;
4808 $suppress_whiletrailers{$line_nr_next +
4812 if (!defined $suppress_whiletrailers{$linenr} &&
4813 defined($stat) && defined($cond) &&
4814 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4815 my ($s, $c) = ($stat, $cond);
4817 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4818 ERROR("ASSIGN_IN_IF",
4819 "do not use assignment in if condition\n" . $herecurr);
4822 # Find out what is on the end of the line after the
4824 substr($s, 0, length($c), '');
4826 $s =~ s/$;//g; # Remove any comments
4827 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4828 $c !~ /}\s*while\s*/)
4830 # Find out how long the conditional actually is.
4831 my @newlines = ($c =~ /\n/gs);
4832 my $cond_lines = 1 + $#newlines;
4835 $stat_real = raw_line($linenr, $cond_lines)
4836 . "\n" if ($cond_lines);
4837 if (defined($stat_real) && $cond_lines > 1) {
4838 $stat_real = "[...]\n$stat_real";
4841 ERROR("TRAILING_STATEMENTS",
4842 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4846 # Check for bitwise tests written as boolean
4858 WARN("HEXADECIMAL_BOOLEAN_TEST",
4859 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4862 # if and else should not have general statements after it
4863 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4865 $s =~ s/$;//g; # Remove any comments
4866 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4867 ERROR("TRAILING_STATEMENTS",
4868 "trailing statements should be on next line\n" . $herecurr);
4871 # if should not continue a brace
4872 if ($line =~ /}\s*if\b/) {
4873 ERROR("TRAILING_STATEMENTS",
4874 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4877 # case and default should not have general statements after them
4878 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4880 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4884 ERROR("TRAILING_STATEMENTS",
4885 "trailing statements should be on next line\n" . $herecurr);
4888 # Check for }<nl>else {, these must be at the same
4889 # indent level to be relevant to each other.
4890 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4891 $previndent == $indent) {
4892 if (ERROR("ELSE_AFTER_BRACE",
4893 "else should follow close brace '}'\n" . $hereprev) &&
4894 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4895 fix_delete_line($fixlinenr - 1, $prevrawline);
4896 fix_delete_line($fixlinenr, $rawline);
4897 my $fixedline = $prevrawline;
4898 $fixedline =~ s/}\s*$//;
4899 if ($fixedline !~ /^\+\s*$/) {
4900 fix_insert_line($fixlinenr, $fixedline);
4902 $fixedline = $rawline;
4903 $fixedline =~ s/^(.\s*)else/$1} else/;
4904 fix_insert_line($fixlinenr, $fixedline);
4908 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4909 $previndent == $indent) {
4910 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4912 # Find out what is on the end of the line after the
4914 substr($s, 0, length($c), '');
4917 if ($s =~ /^\s*;/) {
4918 if (ERROR("WHILE_AFTER_BRACE",
4919 "while should follow close brace '}'\n" . $hereprev) &&
4920 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4921 fix_delete_line($fixlinenr - 1, $prevrawline);
4922 fix_delete_line($fixlinenr, $rawline);
4923 my $fixedline = $prevrawline;
4924 my $trailing = $rawline;
4925 $trailing =~ s/^\+//;
4926 $trailing = trim($trailing);
4927 $fixedline =~ s/}\s*$/} $trailing/;
4928 fix_insert_line($fixlinenr, $fixedline);
4933 #Specific variable tests
4934 while ($line =~ m{($Constant|$Lval)}g) {
4937 #gcc binary extension
4938 if ($var =~ /^$Binary$/) {
4939 if (WARN("GCC_BINARY_CONSTANT",
4940 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4942 my $hexval = sprintf("0x%x", oct($var));
4943 $fixed[$fixlinenr] =~
4944 s/\b$var\b/$hexval/;
4949 if ($var !~ /^$Constant$/ &&
4950 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4951 #Ignore Page<foo> variants
4952 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4953 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4954 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4955 #Ignore some three character SI units explicitly, like MiB and KHz
4956 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4957 while ($var =~ m{($Ident)}g) {
4959 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4961 seed_camelcase_includes();
4962 if (!$file && !$camelcase_file_seeded) {
4963 seed_camelcase_file($realfile);
4964 $camelcase_file_seeded = 1;
4967 if (!defined $camelcase{$word}) {
4968 $camelcase{$word} = 1;
4970 "Avoid CamelCase: <$word>\n" . $herecurr);
4976 #no spaces allowed after \ in define
4977 if ($line =~ /\#\s*define.*\\\s+$/) {
4978 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4979 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4981 $fixed[$fixlinenr] =~ s/\s+$//;
4985 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4986 # itself <asm/foo.h> (uses RAW line)
4987 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4989 my $checkfile = "include/linux/$file";
4990 if (-f "$root/$checkfile" &&
4991 $realfile ne $checkfile &&
4992 $1 !~ /$allowed_asm_includes/)
4994 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4995 if ($asminclude > 0) {
4996 if ($realfile =~ m{^arch/}) {
4997 CHK("ARCH_INCLUDE_LINUX",
4998 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5000 WARN("INCLUDE_LINUX",
5001 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5007 # multi-statement macros should be enclosed in a do while loop, grab the
5008 # first statement and ensure its the whole macro if its not enclosed
5009 # in a known good container
5010 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5011 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5014 my ($off, $dstat, $dcond, $rest);
5016 my $has_flow_statement = 0;
5017 my $has_arg_concat = 0;
5018 ($dstat, $dcond, $ln, $cnt, $off) =
5019 ctx_statement_block($linenr, $realcnt, 0);
5021 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5022 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5024 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5025 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5027 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5028 my $define_args = $1;
5029 my $define_stmt = $dstat;
5032 if (defined $define_args && $define_args ne "") {
5033 $define_args = substr($define_args, 1, length($define_args) - 2);
5034 $define_args =~ s/\s*//g;
5035 $define_args =~ s/\\\+?//g;
5036 @def_args = split(",", $define_args);
5040 $dstat =~ s/\\\n.//g;
5041 $dstat =~ s/^\s*//s;
5042 $dstat =~ s/\s*$//s;
5044 # Flatten any parentheses and braces
5045 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5046 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5047 $dstat =~ s/.\[[^\[\]]*\]/1/)
5051 # Flatten any obvious string concatentation.
5052 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5053 $dstat =~ s/$Ident\s*($String)/$1/)
5057 # Make asm volatile uses seem like a generic function
5058 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5060 my $exceptions = qr{
5073 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5076 my $stmt_cnt = statement_rawlines($ctx);
5077 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5080 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5081 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5082 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5083 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5084 $dstat !~ /$exceptions/ &&
5085 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5086 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5087 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5088 $dstat !~ /^for\s*$Constant$/ && # for (...)
5089 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5090 $dstat !~ /^do\s*{/ && # do {...
5091 $dstat !~ /^\(\{/ && # ({...
5092 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5094 if ($dstat =~ /^\s*if\b/) {
5095 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5096 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5097 } elsif ($dstat =~ /;/) {
5098 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5099 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5101 ERROR("COMPLEX_MACRO",
5102 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5107 # Make $define_stmt single line, comment-free, etc
5108 my @stmt_array = split('\n', $define_stmt);
5111 foreach my $l (@stmt_array) {
5116 } elsif ($l =~ /^[\+ ]/) {
5117 $define_stmt .= substr($l, 1);
5120 $define_stmt =~ s/$;//g;
5121 $define_stmt =~ s/\s+/ /g;
5122 $define_stmt = trim($define_stmt);
5124 # check if any macro arguments are reused (ignore '...' and 'type')
5125 foreach my $arg (@def_args) {
5126 next if ($arg =~ /\.\.\./);
5127 next if ($arg =~ /^type$/i);
5128 my $tmp_stmt = $define_stmt;
5129 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5130 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5131 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5132 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5134 CHK("MACRO_ARG_REUSE",
5135 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5137 # check if any macro arguments may have other precedence issues
5138 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5139 ((defined($1) && $1 ne ',') ||
5140 (defined($2) && $2 ne ','))) {
5141 CHK("MACRO_ARG_PRECEDENCE",
5142 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5146 # check for macros with flow control, but without ## concatenation
5147 # ## concatenation is commonly a macro that defines a function so ignore those
5148 if ($has_flow_statement && !$has_arg_concat) {
5149 my $cnt = statement_rawlines($ctx);
5150 my $herectx = get_stat_here($linenr, $cnt, $here);
5152 WARN("MACRO_WITH_FLOW_CONTROL",
5153 "Macros with flow control statements should be avoided\n" . "$herectx");
5156 # check for line continuations outside of #defines, preprocessor #, and asm
5159 if ($prevline !~ /^..*\\$/ &&
5160 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5161 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5162 $line =~ /^\+.*\\$/) {
5163 WARN("LINE_CONTINUATIONS",
5164 "Avoid unnecessary line continuations\n" . $herecurr);
5168 # do {} while (0) macro tests:
5169 # single-statement macros do not need to be enclosed in do while (0) loop,
5170 # macro should not end with a semicolon
5171 if ($perl_version_ok &&
5172 $realfile !~ m@/vmlinux.lds.h$@ &&
5173 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5176 my ($off, $dstat, $dcond, $rest);
5178 ($dstat, $dcond, $ln, $cnt, $off) =
5179 ctx_statement_block($linenr, $realcnt, 0);
5182 $dstat =~ s/\\\n.//g;
5185 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5190 my $cnt = statement_rawlines($ctx);
5191 my $herectx = get_stat_here($linenr, $cnt, $here);
5193 if (($stmts =~ tr/;/;/) == 1 &&
5194 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5195 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5196 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5198 if (defined $semis && $semis ne "") {
5199 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5200 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5202 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5204 my $cnt = statement_rawlines($ctx);
5205 my $herectx = get_stat_here($linenr, $cnt, $here);
5207 WARN("TRAILING_SEMICOLON",
5208 "macros should not use a trailing semicolon\n" . "$herectx");
5212 # check for redundant bracing round if etc
5213 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5214 my ($level, $endln, @chunks) =
5215 ctx_statement_full($linenr, $realcnt, 1);
5216 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5217 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5218 if ($#chunks > 0 && $level == 0) {
5222 my $herectx = $here . "\n";
5223 my $ln = $linenr - 1;
5224 for my $chunk (@chunks) {
5225 my ($cond, $block) = @{$chunk};
5227 # If the condition carries leading newlines, then count those as offsets.
5228 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5229 my $offset = statement_rawlines($whitespace) - 1;
5231 $allowed[$allow] = 0;
5232 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5234 # We have looked at and allowed this specific line.
5235 $suppress_ifbraces{$ln + $offset} = 1;
5237 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5238 $ln += statement_rawlines($block) - 1;
5240 substr($block, 0, length($cond), '');
5242 $seen++ if ($block =~ /^\s*{/);
5244 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5245 if (statement_lines($cond) > 1) {
5246 #print "APW: ALLOWED: cond<$cond>\n";
5247 $allowed[$allow] = 1;
5249 if ($block =~/\b(?:if|for|while)\b/) {
5250 #print "APW: ALLOWED: block<$block>\n";
5251 $allowed[$allow] = 1;
5253 if (statement_block_size($block) > 1) {
5254 #print "APW: ALLOWED: lines block<$block>\n";
5255 $allowed[$allow] = 1;
5260 my $sum_allowed = 0;
5261 foreach (@allowed) {
5264 if ($sum_allowed == 0) {
5266 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5267 } elsif ($sum_allowed != $allow &&
5270 "braces {} should be used on all arms of this statement\n" . $herectx);
5275 if (!defined $suppress_ifbraces{$linenr - 1} &&
5276 $line =~ /\b(if|while|for|else)\b/) {
5279 # Check the pre-context.
5280 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5281 #print "APW: ALLOWED: pre<$1>\n";
5285 my ($level, $endln, @chunks) =
5286 ctx_statement_full($linenr, $realcnt, $-[0]);
5288 # Check the condition.
5289 my ($cond, $block) = @{$chunks[0]};
5290 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5291 if (defined $cond) {
5292 substr($block, 0, length($cond), '');
5294 if (statement_lines($cond) > 1) {
5295 #print "APW: ALLOWED: cond<$cond>\n";
5298 if ($block =~/\b(?:if|for|while)\b/) {
5299 #print "APW: ALLOWED: block<$block>\n";
5302 if (statement_block_size($block) > 1) {
5303 #print "APW: ALLOWED: lines block<$block>\n";
5306 # Check the post-context.
5307 if (defined $chunks[1]) {
5308 my ($cond, $block) = @{$chunks[1]};
5309 if (defined $cond) {
5310 substr($block, 0, length($cond), '');
5312 if ($block =~ /^\s*\{/) {
5313 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5317 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5318 my $cnt = statement_rawlines($block);
5319 my $herectx = get_stat_here($linenr, $cnt, $here);
5322 "braces {} are not necessary for single statement blocks\n" . $herectx);
5326 # check for single line unbalanced braces
5327 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5328 $sline =~ /^.\s*else\s*\{\s*$/) {
5329 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5332 # check for unnecessary blank lines around braces
5333 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5335 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5336 $fix && $prevrawline =~ /^\+/) {
5337 fix_delete_line($fixlinenr - 1, $prevrawline);
5340 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5342 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5344 fix_delete_line($fixlinenr, $rawline);
5348 # no volatiles please
5349 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5350 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5352 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5355 # Check for user-visible strings broken across lines, which breaks the ability
5356 # to grep for the string. Make exceptions when the previous string ends in a
5357 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5358 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5359 if ($line =~ /^\+\s*$String/ &&
5360 $prevline =~ /"\s*$/ &&
5361 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5362 if (WARN("SPLIT_STRING",
5363 "quoted string split across lines\n" . $hereprev) &&
5365 $prevrawline =~ /^\+.*"\s*$/ &&
5366 $last_coalesced_string_linenr != $linenr - 1) {
5367 my $extracted_string = get_quoted_string($line, $rawline);
5368 my $comma_close = "";
5369 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5373 fix_delete_line($fixlinenr - 1, $prevrawline);
5374 fix_delete_line($fixlinenr, $rawline);
5375 my $fixedline = $prevrawline;
5376 $fixedline =~ s/"\s*$//;
5377 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5378 fix_insert_line($fixlinenr - 1, $fixedline);
5379 $fixedline = $rawline;
5380 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5381 if ($fixedline !~ /\+\s*$/) {
5382 fix_insert_line($fixlinenr, $fixedline);
5384 $last_coalesced_string_linenr = $linenr;
5388 # check for missing a space in a string concatenation
5389 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5390 WARN('MISSING_SPACE',
5391 "break quoted strings at a space character\n" . $hereprev);
5394 # check for an embedded function name in a string when the function is known
5395 # This does not work very well for -f --file checking as it depends on patch
5396 # context providing the function name or a single line form for in-file
5397 # function declarations
5398 if ($line =~ /^\+.*$String/ &&
5399 defined($context_function) &&
5400 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5401 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5402 WARN("EMBEDDED_FUNCTION_NAME",
5403 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5406 # check for spaces before a quoted newline
5407 if ($rawline =~ /^.*\".*\s\\n/) {
5408 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5409 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5411 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5416 # concatenated string without spaces between elements
5417 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5418 if (CHK("CONCATENATED_STRING",
5419 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5421 while ($line =~ /($String)/g) {
5422 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5423 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5424 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5429 # uncoalesced string fragments
5430 if ($line =~ /$String\s*"/) {
5431 if (WARN("STRING_FRAGMENTS",
5432 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5434 while ($line =~ /($String)(?=\s*")/g) {
5435 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5436 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5441 # check for non-standard and hex prefixed decimal printf formats
5442 my $show_L = 1; #don't show the same defect twice
5444 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5445 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5446 $string =~ s/%%/__/g;
5448 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5450 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5454 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5456 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5459 # check for 0x<decimal>
5460 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5461 ERROR("PRINTF_0XDECIMAL",
5462 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5466 # check for line continuations in quoted strings with odd counts of "
5467 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5468 WARN("LINE_CONTINUATIONS",
5469 "Avoid line continuations in quoted strings\n" . $herecurr);
5473 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5475 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5479 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5481 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5484 # check for needless "if (<foo>) fn(<foo>)" uses
5485 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5486 my $tested = quotemeta($1);
5487 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5488 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5490 if (WARN('NEEDLESS_IF',
5491 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5494 my $leading_tabs = "";
5495 my $new_leading_tabs = "";
5496 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5501 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5502 $new_leading_tabs = $1;
5503 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5510 fix_delete_line($fixlinenr - 1, $prevrawline);
5511 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5517 # check for unnecessary "Out of Memory" messages
5518 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5519 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5520 (defined $1 || defined $3) &&
5523 my $testline = $lines[$linenr - 3];
5525 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5526 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5528 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)/) {
5530 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5534 # check for logging functions with KERN_<LEVEL>
5535 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5536 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5538 if (WARN("UNNECESSARY_KERN_LEVEL",
5539 "Possible unnecessary $level\n" . $herecurr) &&
5541 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5545 # check for logging continuations
5546 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5547 WARN("LOGGING_CONTINUATION",
5548 "Avoid logging continuation uses where feasible\n" . $herecurr);
5551 # check for mask then right shift without a parentheses
5552 if ($perl_version_ok &&
5553 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5554 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5555 WARN("MASK_THEN_SHIFT",
5556 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5559 # check for pointer comparisons to NULL
5560 if ($perl_version_ok) {
5561 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5564 $equal = "" if ($4 eq "!=");
5565 if (CHK("COMPARISON_TO_NULL",
5566 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5568 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5573 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5574 if ($line =~ /(\b$InitAttribute\b)/) {
5576 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5579 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5580 ERROR("MISPLACED_INIT",
5581 "$attr should be placed after $var\n" . $herecurr)) ||
5582 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5583 WARN("MISPLACED_INIT",
5584 "$attr should be placed after $var\n" . $herecurr))) &&
5586 $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;
5591 # check for $InitAttributeData (ie: __initdata) with const
5592 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5594 $attr =~ /($InitAttributePrefix)(.*)/;
5595 my $attr_prefix = $1;
5597 if (ERROR("INIT_ATTRIBUTE",
5598 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5600 $fixed[$fixlinenr] =~
5601 s/$InitAttributeData/${attr_prefix}initconst/;
5605 # check for $InitAttributeConst (ie: __initconst) without const
5606 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5608 if (ERROR("INIT_ATTRIBUTE",
5609 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5611 my $lead = $fixed[$fixlinenr] =~
5612 /(^\+\s*(?:static\s+))/;
5614 $lead = "$lead " if ($lead !~ /^\+$/);
5615 $lead = "${lead}const ";
5616 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5620 # check for __read_mostly with const non-pointer (should just be const)
5621 if ($line =~ /\b__read_mostly\b/ &&
5622 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5623 if (ERROR("CONST_READ_MOSTLY",
5624 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5626 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5630 # don't use __constant_<foo> functions outside of include/uapi/
5631 if ($realfile !~ m@^include/uapi/@ &&
5632 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5633 my $constant_func = $1;
5634 my $func = $constant_func;
5635 $func =~ s/^__constant_//;
5636 if (WARN("CONSTANT_CONVERSION",
5637 "$constant_func should be $func\n" . $herecurr) &&
5639 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5643 # prefer usleep_range over udelay
5644 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5646 # ignore udelay's < 10, however
5647 if (! ($delay < 10) ) {
5649 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5651 if ($delay > 2000) {
5653 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5657 # warn about unexpectedly long msleep's
5658 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5661 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5665 # check for comparisons of jiffies
5666 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5667 WARN("JIFFIES_COMPARISON",
5668 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5671 # check for comparisons of get_jiffies_64()
5672 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5673 WARN("JIFFIES_COMPARISON",
5674 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5677 # warn about #ifdefs in C files
5678 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5679 # print "#ifdef in C files should be avoided\n";
5680 # print "$herecurr";
5684 # warn about spacing in #ifdefs
5685 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5686 if (ERROR("SPACING",
5687 "exactly one space required after that #$1\n" . $herecurr) &&
5689 $fixed[$fixlinenr] =~
5690 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5695 # check for spinlock_t definitions without a comment.
5696 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5697 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5699 if (!ctx_has_comment($first_line, $linenr)) {
5700 CHK("UNCOMMENTED_DEFINITION",
5701 "$1 definition without comment\n" . $herecurr);
5704 # check for memory barriers without a comment.
5710 read_barrier_depends
5712 my $barrier_stems = qr{
5720 my $all_barriers = qr{
5722 smp_(?:$barrier_stems)|
5723 virt_(?:$barrier_stems)
5726 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5727 if (!ctx_has_comment($first_line, $linenr)) {
5728 WARN("MEMORY_BARRIER",
5729 "memory barrier without comment\n" . $herecurr);
5733 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5735 if ($realfile !~ m@^include/asm-generic/@ &&
5736 $realfile !~ m@/barrier\.h$@ &&
5737 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5738 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5739 WARN("MEMORY_BARRIER",
5740 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5743 # check for waitqueue_active without a comment.
5744 if ($line =~ /\bwaitqueue_active\s*\(/) {
5745 if (!ctx_has_comment($first_line, $linenr)) {
5746 WARN("WAITQUEUE_ACTIVE",
5747 "waitqueue_active without comment\n" . $herecurr);
5751 # check for smp_read_barrier_depends and read_barrier_depends
5752 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5753 WARN("READ_BARRIER_DEPENDS",
5754 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5757 # check of hardware specific defines
5758 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5760 "architecture specific defines should be avoided\n" . $herecurr);
5763 # check that the storage class is not after a type
5764 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5765 WARN("STORAGE_CLASS",
5766 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5768 # Check that the storage class is at the beginning of a declaration
5769 if ($line =~ /\b$Storage\b/ &&
5770 $line !~ /^.\s*$Storage/ &&
5771 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5772 $1 !~ /[\,\)]\s*$/) {
5773 WARN("STORAGE_CLASS",
5774 "storage class should be at the beginning of the declaration\n" . $herecurr);
5777 # check the location of the inline attribute, that it is between
5778 # storage class and type.
5779 if ($line =~ /\b$Type\s+$Inline\b/ ||
5780 $line =~ /\b$Inline\s+$Storage\b/) {
5781 ERROR("INLINE_LOCATION",
5782 "inline keyword should sit between storage class and type\n" . $herecurr);
5785 # Check for __inline__ and __inline, prefer inline
5786 if ($realfile !~ m@\binclude/uapi/@ &&
5787 $line =~ /\b(__inline__|__inline)\b/) {
5789 "plain inline is preferred over $1\n" . $herecurr) &&
5791 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5796 # Check for __attribute__ packed, prefer __packed
5797 if ($realfile !~ m@\binclude/uapi/@ &&
5798 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5799 WARN("PREFER_PACKED",
5800 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5803 # Check for __attribute__ aligned, prefer __aligned
5804 if ($realfile !~ m@\binclude/uapi/@ &&
5805 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5806 WARN("PREFER_ALIGNED",
5807 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5810 # Check for __attribute__ format(printf, prefer __printf
5811 if ($realfile !~ m@\binclude/uapi/@ &&
5812 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5813 if (WARN("PREFER_PRINTF",
5814 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5816 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5821 # Check for __attribute__ format(scanf, prefer __scanf
5822 if ($realfile !~ m@\binclude/uapi/@ &&
5823 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5824 if (WARN("PREFER_SCANF",
5825 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5827 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5831 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5832 if ($perl_version_ok &&
5833 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5834 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5835 $line =~ /\b__weak\b/)) {
5836 ERROR("WEAK_DECLARATION",
5837 "Using weak declarations can have unintended link defects\n" . $herecurr);
5840 # check for c99 types like uint8_t used outside of uapi/ and tools/
5841 if ($realfile !~ m@\binclude/uapi/@ &&
5842 $realfile !~ m@\btools/@ &&
5843 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5845 if ($type =~ /\b($typeC99Typedefs)\b/) {
5847 my $kernel_type = 'u';
5848 $kernel_type = 's' if ($type =~ /^_*[si]/);
5851 if (CHK("PREFER_KERNEL_TYPES",
5852 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5854 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5859 # check for cast of C90 native int or longer types constants
5860 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5863 if (WARN("TYPECAST_INT_CONSTANT",
5864 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5867 my $newconst = $const;
5868 $newconst =~ s/${Int_type}$//;
5869 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5870 if ($cast =~ /\blong\s+long\b/) {
5872 } elsif ($cast =~ /\blong\b/) {
5875 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5879 # check for sizeof(&)
5880 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5881 WARN("SIZEOF_ADDRESS",
5882 "sizeof(& should be avoided\n" . $herecurr);
5885 # check for sizeof without parenthesis
5886 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5887 if (WARN("SIZEOF_PARENTHESIS",
5888 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5890 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5894 # check for struct spinlock declarations
5895 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5896 WARN("USE_SPINLOCK_T",
5897 "struct spinlock should be spinlock_t\n" . $herecurr);
5900 # check for seq_printf uses that could be seq_puts
5901 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5902 my $fmt = get_quoted_string($line, $rawline);
5905 if (WARN("PREFER_SEQ_PUTS",
5906 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5908 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5913 # check for vsprintf extension %p<foo> misuses
5914 if ($perl_version_ok &&
5916 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5917 $1 !~ /^_*volatile_*$/) {
5920 my $lc = $stat =~ tr@\n@@;
5921 $lc = $lc + $linenr;
5922 for (my $count = $linenr; $count <= $lc; $count++) {
5925 my $bad_specifier = "";
5926 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5929 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5932 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5933 $bad_specifier = $specifier;
5936 if ($extension eq "x" && !defined($stat_real)) {
5937 if (!defined($stat_real)) {
5938 $stat_real = get_stat_real($linenr, $lc);
5940 WARN("VSPRINTF_SPECIFIER_PX",
5941 "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");
5944 if ($bad_specifier ne "") {
5945 my $stat_real = get_stat_real($linenr, $lc);
5946 my $ext_type = "Invalid";
5948 if ($bad_specifier =~ /p[Ff]/) {
5949 $ext_type = "Deprecated";
5950 $use = " - use %pS instead";
5951 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5954 WARN("VSPRINTF_POINTER_EXTENSION",
5955 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5960 # Check for misused memsets
5961 if ($perl_version_ok &&
5963 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5969 if ($ms_size =~ /^(0x|)0$/i) {
5971 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5972 } elsif ($ms_size =~ /^(0x|)1$/i) {
5974 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5978 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5979 # if ($perl_version_ok &&
5981 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5982 # if (WARN("PREFER_ETHER_ADDR_COPY",
5983 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5985 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5989 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5990 # if ($perl_version_ok &&
5992 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5993 # WARN("PREFER_ETHER_ADDR_EQUAL",
5994 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5997 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5998 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5999 # if ($perl_version_ok &&
6001 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6005 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6006 # if (WARN("PREFER_ETH_ZERO_ADDR",
6007 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6009 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6011 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6012 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6013 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6015 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6020 # typecasts on min/max could be min_t/max_t
6021 if ($perl_version_ok &&
6023 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6024 if (defined $2 || defined $7) {
6026 my $cast1 = deparenthesize($2);
6028 my $cast2 = deparenthesize($7);
6032 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6033 $cast = "$cast1 or $cast2";
6034 } elsif ($cast1 ne "") {
6040 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6044 # check usleep_range arguments
6045 if ($perl_version_ok &&
6047 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6051 WARN("USLEEP_RANGE",
6052 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6053 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6055 WARN("USLEEP_RANGE",
6056 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6060 # check for naked sscanf
6061 if ($perl_version_ok &&
6063 $line =~ /\bsscanf\b/ &&
6064 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6065 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6066 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6067 my $lc = $stat =~ tr@\n@@;
6068 $lc = $lc + $linenr;
6069 my $stat_real = get_stat_real($linenr, $lc);
6070 WARN("NAKED_SSCANF",
6071 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6074 # check for simple sscanf that should be kstrto<foo>
6075 if ($perl_version_ok &&
6077 $line =~ /\bsscanf\b/) {
6078 my $lc = $stat =~ tr@\n@@;
6079 $lc = $lc + $linenr;
6080 my $stat_real = get_stat_real($linenr, $lc);
6081 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6083 my $count = $format =~ tr@%@%@;
6085 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6086 WARN("SSCANF_TO_KSTRTO",
6087 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6092 # check for new externs in .h files.
6093 if ($realfile =~ /\.h$/ &&
6094 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6095 if (CHK("AVOID_EXTERNS",
6096 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6098 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6102 # check for new externs in .c files.
6103 if ($realfile =~ /\.c$/ && defined $stat &&
6104 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6106 my $function_name = $1;
6107 my $paren_space = $2;
6110 if (defined $cond) {
6111 substr($s, 0, length($cond), '');
6113 if ($s =~ /^\s*;/ &&
6114 $function_name ne 'uninitialized_var')
6116 WARN("AVOID_EXTERNS",
6117 "externs should be avoided in .c files\n" . $herecurr);
6120 if ($paren_space =~ /\n/) {
6121 WARN("FUNCTION_ARGUMENTS",
6122 "arguments for function declarations should follow identifier\n" . $herecurr);
6125 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6126 $stat =~ /^.\s*extern\s+/)
6128 WARN("AVOID_EXTERNS",
6129 "externs should be avoided in .c files\n" . $herecurr);
6132 # check for function declarations that have arguments without identifier names
6133 if (defined $stat &&
6134 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6136 my $args = trim($1);
6137 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6139 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6140 WARN("FUNCTION_ARGUMENTS",
6141 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6146 # check for function definitions
6147 if ($perl_version_ok &&
6149 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6150 $context_function = $1;
6152 # check for multiline function definition with misplaced open brace
6154 my $cnt = statement_rawlines($stat);
6155 my $herectx = $here . "\n";
6156 for (my $n = 0; $n < $cnt; $n++) {
6157 my $rl = raw_line($linenr, $n);
6158 $herectx .= $rl . "\n";
6159 $ok = 1 if ($rl =~ /^[ \+]\{/);
6160 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6161 last if $rl =~ /^[ \+].*\{/;
6165 "open brace '{' following function definitions go on the next line\n" . $herectx);
6169 # checks for new __setup's
6170 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6173 if (!grep(/$name/, @setup_docs)) {
6174 CHK("UNDOCUMENTED_SETUP",
6175 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6179 # check for pointless casting of kmalloc return
6180 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6181 WARN("UNNECESSARY_CASTS",
6182 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6186 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6187 if ($perl_version_ok &&
6188 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6189 CHK("ALLOC_SIZEOF_STRUCT",
6190 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6193 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6194 if ($perl_version_ok &&
6196 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6200 my $newfunc = "kmalloc_array";
6201 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6204 if ($a1 =~ /^sizeof\s*\S/) {
6208 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6209 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6210 my $cnt = statement_rawlines($stat);
6211 my $herectx = get_stat_here($linenr, $cnt, $here);
6213 if (WARN("ALLOC_WITH_MULTIPLY",
6214 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6217 $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;
6222 # check for krealloc arg reuse
6223 if ($perl_version_ok &&
6224 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6226 WARN("KREALLOC_ARG_REUSE",
6227 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6230 # check for alloc argument mismatch
6231 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6232 WARN("ALLOC_ARRAY_ARGS",
6233 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6236 # check for multiple semicolons
6237 if ($line =~ /;\s*;\s*$/) {
6238 if (WARN("ONE_SEMICOLON",
6239 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6241 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6245 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6246 if ($realfile !~ m@^include/uapi/@ &&
6247 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6249 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6250 if (CHK("BIT_MACRO",
6251 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6253 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6257 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6258 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6260 if (WARN("PREFER_IS_ENABLED",
6261 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6263 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6267 # check for case / default statements not preceded by break/fallthrough/switch
6268 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6270 my $has_statement = 0;
6272 my $prevline = $linenr;
6273 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6275 my $rline = $rawlines[$prevline - 1];
6276 my $fline = $lines[$prevline - 1];
6277 last if ($fline =~ /^\@\@/);
6278 next if ($fline =~ /^\-/);
6279 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6280 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6281 next if ($fline =~ /^.[\s$;]*$/);
6284 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6286 if (!$has_break && $has_statement) {
6287 WARN("MISSING_BREAK",
6288 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6292 # check for switch/default statements without a break;
6293 if ($perl_version_ok &&
6295 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6296 my $cnt = statement_rawlines($stat);
6297 my $herectx = get_stat_here($linenr, $cnt, $here);
6299 WARN("DEFAULT_NO_BREAK",
6300 "switch default: should use break\n" . $herectx);
6303 # check for gcc specific __FUNCTION__
6304 if ($line =~ /\b__FUNCTION__\b/) {
6305 if (WARN("USE_FUNC",
6306 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6308 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6312 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6313 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6315 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6318 # check for use of yield()
6319 if ($line =~ /\byield\s*\(\s*\)/) {
6321 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6324 # check for comparisons against true and false
6325 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6333 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6335 my $type = lc($otype);
6336 if ($type =~ /^(?:true|false)$/) {
6337 if (("$test" eq "==" && "$type" eq "true") ||
6338 ("$test" eq "!=" && "$type" eq "false")) {
6342 CHK("BOOL_COMPARISON",
6343 "Using comparison to $otype is error prone\n" . $herecurr);
6345 ## maybe suggesting a correct construct would better
6346 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6351 # check for bool bitfields
6352 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6353 WARN("BOOL_BITFIELD",
6354 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6357 # check for bool use in .h files
6358 if ($realfile =~ /\.h$/ &&
6359 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6361 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6364 # check for semaphores initialized locked
6365 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6366 WARN("CONSIDER_COMPLETION",
6367 "consider using a completion\n" . $herecurr);
6370 # recommend kstrto* over simple_strto* and strict_strto*
6371 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6372 WARN("CONSIDER_KSTRTO",
6373 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6376 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6377 if ($line =~ /^.\s*__initcall\s*\(/) {
6378 WARN("USE_DEVICE_INITCALL",
6379 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6382 # check for various structs that are normally const (ops, kgdb, device_tree)
6383 # and avoid what seem like struct definitions 'struct foo {'
6384 if ($line !~ /\bconst\b/ &&
6385 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6386 WARN("CONST_STRUCT",
6387 "struct $1 should normally be const\n" . $herecurr);
6390 # use of NR_CPUS is usually wrong
6391 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6392 if ($line =~ /\bNR_CPUS\b/ &&
6393 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6394 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6395 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6396 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6397 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6400 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6403 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6404 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6405 ERROR("DEFINE_ARCH_HAS",
6406 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6409 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6410 if ($perl_version_ok &&
6411 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6412 WARN("LIKELY_MISUSE",
6413 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6416 # whine mightly about in_atomic
6417 if ($line =~ /\bin_atomic\s*\(/) {
6418 if ($realfile =~ m@^drivers/@) {
6420 "do not use in_atomic in drivers\n" . $herecurr);
6421 } elsif ($realfile !~ m@^kernel/@) {
6423 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6427 # check for mutex_trylock_recursive usage
6428 if ($line =~ /mutex_trylock_recursive/) {
6430 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6433 # check for lockdep_set_novalidate_class
6434 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6435 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6436 if ($realfile !~ m@^kernel/lockdep@ &&
6437 $realfile !~ m@^include/linux/lockdep@ &&
6438 $realfile !~ m@^drivers/base/core@) {
6440 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6444 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6445 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6446 WARN("EXPORTED_WORLD_WRITABLE",
6447 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6450 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6451 # and whether or not function naming is typical and if
6452 # DEVICE_ATTR permissions uses are unusual too
6453 if ($perl_version_ok &&
6455 $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*\)/) {
6460 my $octal_perms = perms_to_octal($perms);
6461 if ($show =~ /^${var}_show$/ &&
6462 $store =~ /^${var}_store$/ &&
6463 $octal_perms eq "0644") {
6464 if (WARN("DEVICE_ATTR_RW",
6465 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6467 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6469 } elsif ($show =~ /^${var}_show$/ &&
6470 $store =~ /^NULL$/ &&
6471 $octal_perms eq "0444") {
6472 if (WARN("DEVICE_ATTR_RO",
6473 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6475 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6477 } elsif ($show =~ /^NULL$/ &&
6478 $store =~ /^${var}_store$/ &&
6479 $octal_perms eq "0200") {
6480 if (WARN("DEVICE_ATTR_WO",
6481 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6483 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6485 } elsif ($octal_perms eq "0644" ||
6486 $octal_perms eq "0444" ||
6487 $octal_perms eq "0200") {
6488 my $newshow = "$show";
6489 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6490 my $newstore = $store;
6491 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6493 if ($show ne $newshow) {
6494 $rename .= " '$show' to '$newshow'";
6496 if ($store ne $newstore) {
6497 $rename .= " '$store' to '$newstore'";
6499 WARN("DEVICE_ATTR_FUNCTIONS",
6500 "Consider renaming function(s)$rename\n" . $herecurr);
6502 WARN("DEVICE_ATTR_PERMS",
6503 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6507 # Mode permission misuses where it seems decimal should be octal
6508 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6509 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6510 # specific definition of not visible in sysfs.
6511 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6512 # use the default permissions
6513 if ($perl_version_ok &&
6515 $line =~ /$mode_perms_search/) {
6516 foreach my $entry (@mode_permission_funcs) {
6517 my $func = $entry->[0];
6518 my $arg_pos = $entry->[1];
6520 my $lc = $stat =~ tr@\n@@;
6521 $lc = $lc + $linenr;
6522 my $stat_real = get_stat_real($linenr, $lc);
6527 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6529 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6530 if ($stat =~ /$test/) {
6532 $val = $6 if ($skip_args ne "");
6533 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6534 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6535 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6536 ERROR("NON_OCTAL_PERMISSIONS",
6537 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6539 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6540 ERROR("EXPORTED_WORLD_WRITABLE",
6541 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6547 # check for uses of S_<PERMS> that could be octal for readability
6548 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6550 my $octal = perms_to_octal($oval);
6551 if (WARN("SYMBOLIC_PERMS",
6552 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6554 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6558 # validate content of MODULE_LICENSE against list from include/linux/module.h
6559 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6560 my $extracted_string = get_quoted_string($line, $rawline);
6561 my $valid_licenses = qr{
6564 GPL\ and\ additional\ rights|
6570 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6571 WARN("MODULE_LICENSE",
6572 "unknown module license " . $extracted_string . "\n" . $herecurr);
6577 # If we have no input at all, then there is nothing to report on
6578 # so just keep quiet.
6579 if ($#rawlines == -1) {
6583 # In mailback mode only produce a report in the negative, for
6584 # things that appear to be patches.
6585 if ($mailback && ($clean == 1 || !$is_patch)) {
6589 # This is not a patch, and we are are in 'no-patch' mode so
6591 if (!$chk_patch && !$is_patch) {
6595 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6596 ERROR("NOT_UNIFIED_DIFF",
6597 "Does not appear to be a unified-diff format patch\n");
6599 if ($is_patch && $has_commit_log && $chk_signoff) {
6600 if ($signoff == 0) {
6601 ERROR("MISSING_SIGN_OFF",
6602 "Missing Signed-off-by: line(s)\n");
6603 } elsif (!$authorsignoff) {
6604 WARN("NO_AUTHOR_SIGN_OFF",
6605 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6609 print report_dump();
6610 if ($summary && !($clean == 1 && $quiet == 1)) {
6611 print "$filename " if ($summary_file);
6612 print "total: $cnt_error errors, $cnt_warn warnings, " .
6613 (($check)? "$cnt_chk checks, " : "") .
6614 "$cnt_lines lines checked\n";
6618 # If there were any defects found and not already fixing them
6619 if (!$clean and !$fix) {
6622 NOTE: For some of the reported defects, checkpatch may be able to
6623 mechanically convert to the typical style using --fix or --fix-inplace.
6626 # If there were whitespace errors which cleanpatch can fix
6627 # then suggest that.
6628 if ($rpt_cleaners) {
6632 NOTE: Whitespace errors detected.
6633 You may wish to use scripts/cleanpatch or scripts/cleanfile
6638 if ($clean == 0 && $fix &&
6639 ("@rawlines" ne "@fixed" ||
6640 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6641 my $newfile = $filename;
6642 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6646 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6648 open($f, '>', $newfile)
6649 or die "$P: Can't open $newfile for write\n";
6650 foreach my $fixed_line (@fixed) {
6653 if ($linecount > 3) {
6654 $fixed_line =~ s/^\+//;
6655 print $f $fixed_line . "\n";
6658 print $f $fixed_line . "\n";
6666 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6668 Do _NOT_ trust the results written to this file.
6669 Do _NOT_ submit these changes without inspecting them for correctness.
6671 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6672 No warranties, expressed or implied...
6680 print "$vname has no obvious style problems and is ready for submission.\n";
6682 print "$vname has style problems, please review.\n";