2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 80;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile = "";
64 my $allow_c99_comments = 1;
70 Usage: $P [OPTION]... [FILE]...
75 --no-tree run without a kernel tree
76 --no-signoff do not check for 'Signed-off-by' line
77 --patch treat FILE as patchfile (default)
78 --emacs emacs compile window format
79 --terse one line per report
80 --showfile emit diffed file position, not input file position
81 -g, --git treat FILE as a single commit or git revision range
82 single git commit with:
86 multiple git commits with:
90 git merges are ignored
91 -f, --file treat FILE as regular source file
92 --subjective, --strict enable more subjective tests
93 --list-types list the possible message types
94 --types TYPE(,TYPE2...) show only these comma separated message types
95 --ignore TYPE(,TYPE2...) ignore various comma separated message types
96 --show-types show the specific message type in the output
97 --max-line-length=n set the maximum line length, if exceeded, warn
98 --min-conf-desc-length=n set the min description length, if shorter, warn
99 --root=PATH PATH to the kernel tree root
100 --no-summary suppress the per-file summary
101 --mailback only produce a report in case of warnings/errors
102 --summary-file include the filename in summary
103 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
104 'values', 'possible', 'type', and 'attr' (default
106 --test-only=WORD report only warnings/errors containing WORD
108 --fix EXPERIMENTAL - may create horrible results
109 If correctable single-line errors exist, create
110 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
111 with potential errors corrected to the preferred
113 --fix-inplace EXPERIMENTAL - may create horrible results
114 Is the same as --fix, but overwrites the input
115 file. It's your fault if there's no backup or git
116 --ignore-perl-version override checking of perl version. expect
118 --codespell Use the codespell dictionary for spelling/typos
119 (default:/usr/share/codespell/dictionary.txt)
120 --codespellfile Use this codespell dictionary
121 --typedefsfile Read additional types from this file
122 --color[=WHEN] Use colors 'always', 'never', or only when output
123 is a terminal ('auto'). Default is 'auto'.
124 -h, --help, --version display this help and exit
126 When FILE is - read standard input.
134 return grep { !$seen{$_}++ } @_;
144 open(my $script, '<', abs_path($P)) or
145 die "$P: Can't read '$P' $!\n";
147 my $text = <$script>;
151 # Also catch when type or level is passed through a variable
152 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
155 @types = sort(uniq(@types));
156 print("#\tMessage type\n\n");
157 foreach my $type (@types) {
158 print(++$count . "\t" . $type . "\n");
164 my $conf = which_conf($configuration_file);
167 open(my $conffile, '<', "$conf")
168 or warn "$P: Can't find a readable $configuration_file file $!\n";
170 while (<$conffile>) {
173 $line =~ s/\s*\n?$//g;
177 next if ($line =~ m/^\s*#/);
178 next if ($line =~ m/^\s*$/);
180 my @words = split(" ", $line);
181 foreach my $word (@words) {
182 last if ($word =~ m/^#/);
183 push (@conf_args, $word);
187 unshift(@ARGV, @conf_args) if @conf_args;
190 # Perl's Getopt::Long allows options to take optional arguments after a space.
191 # Prevent --color by itself from consuming other arguments
193 if ($_ eq "--color" || $_ eq "-color") {
194 $_ = "--color=$color";
199 'q|quiet+' => \$quiet,
201 'signoff!' => \$chk_signoff,
202 'patch!' => \$chk_patch,
205 'showfile!' => \$showfile,
208 'subjective!' => \$check,
209 'strict!' => \$check,
210 'ignore=s' => \@ignore,
212 'show-types!' => \$show_types,
213 'list-types!' => \$list_types,
214 'max-line-length=i' => \$max_line_length,
215 'min-conf-desc-length=i' => \$min_conf_desc_length,
217 'summary!' => \$summary,
218 'mailback!' => \$mailback,
219 'summary-file!' => \$summary_file,
221 'fix-inplace!' => \$fix_inplace,
222 'ignore-perl-version!' => \$ignore_perl_version,
223 'debug=s' => \%debug,
224 'test-only=s' => \$tst_only,
225 'codespell!' => \$codespell,
226 'codespellfile=s' => \$codespellfile,
227 'typedefsfile=s' => \$typedefsfile,
228 'color=s' => \$color,
229 'no-color' => \$color, #keep old behaviors of -nocolor
230 'nocolor' => \$color, #keep old behaviors of -nocolor
237 list_types(0) if ($list_types);
239 $fix = 1 if ($fix_inplace);
240 $check_orig = $check;
244 my $perl_version_ok = 1;
245 if ($^V && $^V lt $minimum_perl_version) {
246 $perl_version_ok = 0;
247 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
248 exit(1) if (!$ignore_perl_version);
251 #if no filenames are given, push '-' to read patch from stdin
256 if ($color =~ /^[01]$/) {
258 } elsif ($color =~ /^always$/i) {
260 } elsif ($color =~ /^never$/i) {
262 } elsif ($color =~ /^auto$/i) {
263 $color = (-t STDOUT);
265 die "Invalid color mode: $color\n";
268 sub hash_save_array_words {
269 my ($hashRef, $arrayRef) = @_;
271 my @array = split(/,/, join(',', @$arrayRef));
272 foreach my $word (@array) {
273 $word =~ s/\s*\n?$//g;
276 $word =~ tr/[a-z]/[A-Z]/;
278 next if ($word =~ m/^\s*#/);
279 next if ($word =~ m/^\s*$/);
285 sub hash_show_words {
286 my ($hashRef, $prefix) = @_;
288 if (keys %$hashRef) {
289 print "\nNOTE: $prefix message types:";
290 foreach my $word (sort keys %$hashRef) {
297 hash_save_array_words(\%ignore_type, \@ignore);
298 hash_save_array_words(\%use_type, \@use);
301 my $dbg_possible = 0;
304 for my $key (keys %debug) {
306 eval "\${dbg_$key} = '$debug{$key}';";
310 my $rpt_cleaners = 0;
319 if (!top_of_kernel_tree($root)) {
320 die "$P: $root: --root does not point at a valid tree\n";
323 if (top_of_kernel_tree('.')) {
325 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
326 top_of_kernel_tree($1)) {
331 if (!defined $root) {
332 print "Must be run from the top-level dir. of a kernel tree\n";
337 my $emitted_corrupt = 0;
340 [A-Za-z_][A-Za-z\d_]*
341 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
343 our $Storage = qr{extern|static|asmlinkage};
357 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
358 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
359 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
360 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
361 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
363 # Notes to $Attribute:
364 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
385 ____cacheline_aligned|
386 ____cacheline_aligned_in_smp|
387 ____cacheline_internodealigned_in_smp|
391 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
392 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
393 our $Lval = qr{$Ident(?:$Member)*};
395 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
396 our $Binary = qr{(?i)0b[01]+$Int_type?};
397 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
398 our $Int = qr{[0-9]+$Int_type?};
399 our $Octal = qr{0[0-7]+$Int_type?};
400 our $String = qr{"[X\t]*"};
401 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
402 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
403 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
404 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
405 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
406 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
407 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
408 our $Arithmetic = qr{\+|-|\*|\/|%};
412 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
415 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
419 our $NonptrTypeMisordered;
420 our $NonptrTypeWithAttr;
424 our $DeclareMisordered;
426 our $NON_ASCII_UTF8 = qr{
427 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
428 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
429 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
430 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
431 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
432 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
433 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
437 [\x09\x0A\x0D\x20-\x7E] # ASCII
441 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
442 our $typeOtherOSTypedefs = qr{(?x:
443 u_(?:char|short|int|long) | # bsd
444 u(?:nchar|short|int|long) # sysv
446 our $typeKernelTypedefs = qr{(?x:
447 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
450 our $typeTypedefs = qr{(?x:
452 $typeOtherOSTypedefs\b|
453 $typeKernelTypedefs\b
456 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
458 our $logFunctions = qr{(?x:
459 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
460 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
462 WARN(?:_RATELIMIT|_ONCE|)|
465 seq_vprintf|seq_printf|seq_puts
468 our $signature_tags = qr{(?xi:
479 our @typeListMisordered = (
480 qr{char\s+(?:un)?signed},
481 qr{int\s+(?:(?:un)?signed\s+)?short\s},
482 qr{int\s+short(?:\s+(?:un)?signed)},
483 qr{short\s+int(?:\s+(?:un)?signed)},
484 qr{(?:un)?signed\s+int\s+short},
485 qr{short\s+(?:un)?signed},
486 qr{long\s+int\s+(?:un)?signed},
487 qr{int\s+long\s+(?:un)?signed},
488 qr{long\s+(?:un)?signed\s+int},
489 qr{int\s+(?:un)?signed\s+long},
490 qr{int\s+(?:un)?signed},
491 qr{int\s+long\s+long\s+(?:un)?signed},
492 qr{long\s+long\s+int\s+(?:un)?signed},
493 qr{long\s+long\s+(?:un)?signed\s+int},
494 qr{long\s+long\s+(?:un)?signed},
495 qr{long\s+(?:un)?signed},
500 qr{(?:(?:un)?signed\s+)?char},
501 qr{(?:(?:un)?signed\s+)?short\s+int},
502 qr{(?:(?:un)?signed\s+)?short},
503 qr{(?:(?:un)?signed\s+)?int},
504 qr{(?:(?:un)?signed\s+)?long\s+int},
505 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
506 qr{(?:(?:un)?signed\s+)?long\s+long},
507 qr{(?:(?:un)?signed\s+)?long},
516 qr{${Ident}_handler},
517 qr{${Ident}_handler_fn},
521 our $C90_int_types = qr{(?x:
522 long\s+long\s+int\s+(?:un)?signed|
523 long\s+long\s+(?:un)?signed\s+int|
524 long\s+long\s+(?:un)?signed|
525 (?:(?:un)?signed\s+)?long\s+long\s+int|
526 (?:(?:un)?signed\s+)?long\s+long|
527 int\s+long\s+long\s+(?:un)?signed|
528 int\s+(?:(?:un)?signed\s+)?long\s+long|
530 long\s+int\s+(?:un)?signed|
531 long\s+(?:un)?signed\s+int|
532 long\s+(?:un)?signed|
533 (?:(?:un)?signed\s+)?long\s+int|
534 (?:(?:un)?signed\s+)?long|
535 int\s+long\s+(?:un)?signed|
536 int\s+(?:(?:un)?signed\s+)?long|
539 (?:(?:un)?signed\s+)?int
542 our @typeListFile = ();
543 our @typeListWithAttr = (
545 qr{struct\s+$InitAttribute\s+$Ident},
546 qr{union\s+$InitAttribute\s+$Ident},
549 our @modifierList = (
552 our @modifierListFile = ();
554 our @mode_permission_funcs = (
556 ["module_param_(?:array|named|string)", 4],
557 ["module_param_array_named", 5],
558 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
559 ["proc_create(?:_data|)", 2],
560 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
561 ["IIO_DEV_ATTR_[A-Z_]+", 1],
562 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
563 ["SENSOR_TEMPLATE(?:_2|)", 3],
567 #Create a search pattern for all these functions to speed up a loop below
568 our $mode_perms_search = "";
569 foreach my $entry (@mode_permission_funcs) {
570 $mode_perms_search .= '|' if ($mode_perms_search ne "");
571 $mode_perms_search .= $entry->[0];
573 $mode_perms_search = "(?:${mode_perms_search})";
575 our $mode_perms_world_writable = qr{
583 our %mode_permission_string_types = (
602 #Create a search pattern for all these strings to speed up a loop below
603 our $mode_perms_string_search = "";
604 foreach my $entry (keys %mode_permission_string_types) {
605 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
606 $mode_perms_string_search .= $entry;
608 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
609 our $multi_mode_perms_string_search = qr{
610 ${single_mode_perms_string_search}
611 (?:\s*\|\s*${single_mode_perms_string_search})*
617 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
624 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
625 $curpos = pos($string);
628 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
630 $to |= $mode_permission_string_types{$match};
631 $val .= '\s*\|\s*' if ($val ne "");
635 $oval =~ s/^\s*\|\s*//;
636 $oval =~ s/\s*\|\s*$//;
637 return sprintf("%04o", $to);
640 our $allowed_asm_includes = qr{(?x:
646 # memory.h: ARM has a custom one
648 # Load common spelling mistakes and build regular expression list.
652 if (open(my $spelling, '<', $spelling_file)) {
653 while (<$spelling>) {
656 $line =~ s/\s*\n?$//g;
659 next if ($line =~ m/^\s*#/);
660 next if ($line =~ m/^\s*$/);
662 my ($suspect, $fix) = split(/\|\|/, $line);
664 $spelling_fix{$suspect} = $fix;
668 warn "No typos will be found - file '$spelling_file': $!\n";
672 if (open(my $spelling, '<', $codespellfile)) {
673 while (<$spelling>) {
676 $line =~ s/\s*\n?$//g;
679 next if ($line =~ m/^\s*#/);
680 next if ($line =~ m/^\s*$/);
681 next if ($line =~ m/, disabled/i);
685 my ($suspect, $fix) = split(/->/, $line);
687 $spelling_fix{$suspect} = $fix;
691 warn "No codespell typos will be found - file '$codespellfile': $!\n";
695 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
698 my ($wordsRef, $file) = @_;
700 if (open(my $words, '<', $file)) {
704 $line =~ s/\s*\n?$//g;
707 next if ($line =~ m/^\s*#/);
708 next if ($line =~ m/^\s*$/);
710 print("$file: '$line' invalid - ignored\n");
714 $$wordsRef .= '|' if ($$wordsRef ne "");
724 my $const_structs = "";
725 read_words(\$const_structs, $conststructsfile)
726 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
728 my $typeOtherTypedefs = "";
729 if (length($typedefsfile)) {
730 read_words(\$typeOtherTypedefs, $typedefsfile)
731 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
733 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
736 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
737 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
738 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
739 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
740 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
746 (?:$Modifier\s+|const\s+)*
748 (?:typeof|__typeof__)\s*\([^\)]*\)|
752 (?:\s+$Modifier|\s+const)*
754 $NonptrTypeMisordered = qr{
755 (?:$Modifier\s+|const\s+)*
759 (?:\s+$Modifier|\s+const)*
761 $NonptrTypeWithAttr = qr{
762 (?:$Modifier\s+|const\s+)*
764 (?:typeof|__typeof__)\s*\([^\)]*\)|
768 (?:\s+$Modifier|\s+const)*
772 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
773 (?:\s+$Inline|\s+$Modifier)*
775 $TypeMisordered = qr{
776 $NonptrTypeMisordered
777 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
778 (?:\s+$Inline|\s+$Modifier)*
780 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
781 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
785 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
787 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
788 # requires at least perl version v5.10.0
789 # Any use must be runtime checked with $^V
791 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
792 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
793 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
795 our $declaration_macros = qr{(?x:
796 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
797 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
798 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
799 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
804 return "" if (!defined($string));
806 while ($string =~ /^\s*\(.*\)\s*$/) {
807 $string =~ s@^\s*\(\s*@@;
808 $string =~ s@\s*\)\s*$@@;
811 $string =~ s@\s+@ @g;
816 sub seed_camelcase_file {
819 return if (!(-f $file));
823 open(my $include_file, '<', "$file")
824 or warn "$P: Can't read '$file' $!\n";
825 my $text = <$include_file>;
826 close($include_file);
828 my @lines = split('\n', $text);
830 foreach my $line (@lines) {
831 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
832 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
834 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
836 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
842 sub is_maintained_obsolete {
845 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
847 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
849 return $status =~ /obsolete/i;
852 sub is_SPDX_License_valid {
855 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
857 my $root_path = abs_path($root);
858 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
859 return 0 if ($status ne "");
863 my $camelcase_seeded = 0;
864 sub seed_camelcase_includes {
865 return if ($camelcase_seeded);
868 my $camelcase_cache = "";
869 my @include_files = ();
871 $camelcase_seeded = 1;
874 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
875 chomp $git_last_include_commit;
876 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
878 my $last_mod_date = 0;
879 $files = `find $root/include -name "*.h"`;
880 @include_files = split('\n', $files);
881 foreach my $file (@include_files) {
882 my $date = POSIX::strftime("%Y%m%d%H%M",
883 localtime((stat $file)[9]));
884 $last_mod_date = $date if ($last_mod_date < $date);
886 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
889 if ($camelcase_cache ne "" && -f $camelcase_cache) {
890 open(my $camelcase_file, '<', "$camelcase_cache")
891 or warn "$P: Can't read '$camelcase_cache' $!\n";
892 while (<$camelcase_file>) {
896 close($camelcase_file);
902 $files = `git ls-files "include/*.h"`;
903 @include_files = split('\n', $files);
906 foreach my $file (@include_files) {
907 seed_camelcase_file($file);
910 if ($camelcase_cache ne "") {
911 unlink glob ".checkpatch-camelcase.*";
912 open(my $camelcase_file, '>', "$camelcase_cache")
913 or warn "$P: Can't write '$camelcase_cache' $!\n";
914 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
915 print $camelcase_file ("$_\n");
917 close($camelcase_file);
921 sub git_commit_info {
922 my ($commit, $id, $desc) = @_;
924 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
926 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
927 $output =~ s/^\s*//gm;
928 my @lines = split("\n", $output);
930 return ($id, $desc) if ($#lines < 0);
932 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
933 # Maybe one day convert this block of bash into something that returns
934 # all matching commit ids, but it's very slow...
936 # echo "checking commits $1..."
937 # git rev-list --remotes | grep -i "^$1" |
938 # while read line ; do
939 # git log --format='%H %s' -1 $line |
940 # echo "commit $(cut -c 1-12,41-)"
942 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
945 $id = substr($lines[0], 0, 12);
946 $desc = substr($lines[0], 41);
952 $chk_signoff = 0 if ($file);
957 my @fixed_inserted = ();
958 my @fixed_deleted = ();
961 # If input is git commits, extract all commits from the commit expressions.
962 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
963 die "$P: No git repository found\n" if ($git && !-e ".git");
967 foreach my $commit_expr (@ARGV) {
969 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
970 $git_range = "-$2 $1";
971 } elsif ($commit_expr =~ m/\.\./) {
972 $git_range = "$commit_expr";
974 $git_range = "-1 $commit_expr";
976 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
977 foreach my $line (split(/\n/, $lines)) {
978 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
979 next if (!defined($1) || !defined($2));
982 unshift(@commits, $sha1);
983 $git_commits{$sha1} = $subject;
986 die "$P: no git commits after extraction!\n" if (@commits == 0);
991 for my $filename (@ARGV) {
994 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
995 die "$P: $filename: git format-patch failed - $!\n";
997 open($FILE, '-|', "diff -u /dev/null $filename") ||
998 die "$P: $filename: diff failed - $!\n";
999 } elsif ($filename eq '-') {
1000 open($FILE, '<&STDIN');
1002 open($FILE, '<', "$filename") ||
1003 die "$P: $filename: open failed - $!\n";
1005 if ($filename eq '-') {
1006 $vname = 'Your patch';
1008 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1014 push(@rawlines, $_);
1018 if ($#ARGV > 0 && $quiet == 0) {
1019 print '-' x length($vname) . "\n";
1021 print '-' x length($vname) . "\n";
1024 if (!process($filename)) {
1030 @fixed_inserted = ();
1031 @fixed_deleted = ();
1033 @modifierListFile = ();
1039 hash_show_words(\%use_type, "Used");
1040 hash_show_words(\%ignore_type, "Ignored");
1042 if (!$perl_version_ok) {
1045 NOTE: perl $^V is not modern enough to detect all possible issues.
1046 An upgrade to at least perl $minimum_perl_version is suggested.
1052 NOTE: If any of the errors are false positives, please report
1053 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1060 sub top_of_kernel_tree {
1064 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1065 "README", "Documentation", "arch", "include", "drivers",
1066 "fs", "init", "ipc", "kernel", "lib", "scripts",
1069 foreach my $check (@tree_check) {
1070 if (! -e $root . '/' . $check) {
1078 my ($formatted_email) = @_;
1084 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1087 $comment = $3 if defined $3;
1088 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1090 $comment = $2 if defined $2;
1091 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1093 $comment = $2 if defined $2;
1094 $formatted_email =~ s/\Q$address\E.*$//;
1095 $name = $formatted_email;
1096 $name = trim($name);
1097 $name =~ s/^\"|\"$//g;
1098 # If there's a name left after stripping spaces and
1099 # leading quotes, and the address doesn't have both
1100 # leading and trailing angle brackets, the address
1102 # "joe smith joe@smith.com" bad
1103 # "joe smith <joe@smith.com" bad
1104 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1111 $name = trim($name);
1112 $name =~ s/^\"|\"$//g;
1113 $address = trim($address);
1114 $address =~ s/^\<|\>$//g;
1116 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1117 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1118 $name = "\"$name\"";
1121 return ($name, $address, $comment);
1125 my ($name, $address) = @_;
1127 my $formatted_email;
1129 $name = trim($name);
1130 $name =~ s/^\"|\"$//g;
1131 $address = trim($address);
1133 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1134 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1135 $name = "\"$name\"";
1138 if ("$name" eq "") {
1139 $formatted_email = "$address";
1141 $formatted_email = "$name <$address>";
1144 return $formatted_email;
1150 foreach my $path (split(/:/, $ENV{PATH})) {
1151 if (-e "$path/$bin") {
1152 return "$path/$bin";
1162 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1163 if (-e "$path/$conf") {
1164 return "$path/$conf";
1176 for my $c (split(//, $str)) {
1180 for (; ($n % 8) != 0; $n++) {
1192 (my $res = shift) =~ tr/\t/ /c;
1199 # Drop the diff line leader and expand tabs
1201 $line = expand_tabs($line);
1203 # Pick the indent from the front of the line.
1204 my ($white) = ($line =~ /^(\s*)/);
1206 return (length($line), length($white));
1209 my $sanitise_quote = '';
1211 sub sanitise_line_reset {
1212 my ($in_comment) = @_;
1215 $sanitise_quote = '*/';
1217 $sanitise_quote = '';
1230 # Always copy over the diff marker.
1231 $res = substr($line, 0, 1);
1233 for ($off = 1; $off < length($line); $off++) {
1234 $c = substr($line, $off, 1);
1236 # Comments we are whacking completely including the begin
1237 # and end, all to $;.
1238 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1239 $sanitise_quote = '*/';
1241 substr($res, $off, 2, "$;$;");
1245 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1246 $sanitise_quote = '';
1247 substr($res, $off, 2, "$;$;");
1251 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1252 $sanitise_quote = '//';
1254 substr($res, $off, 2, $sanitise_quote);
1259 # A \ in a string means ignore the next character.
1260 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1262 substr($res, $off, 2, 'XX');
1267 if ($c eq "'" || $c eq '"') {
1268 if ($sanitise_quote eq '') {
1269 $sanitise_quote = $c;
1271 substr($res, $off, 1, $c);
1273 } elsif ($sanitise_quote eq $c) {
1274 $sanitise_quote = '';
1278 #print "c<$c> SQ<$sanitise_quote>\n";
1279 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1280 substr($res, $off, 1, $;);
1281 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1282 substr($res, $off, 1, $;);
1283 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1284 substr($res, $off, 1, 'X');
1286 substr($res, $off, 1, $c);
1290 if ($sanitise_quote eq '//') {
1291 $sanitise_quote = '';
1294 # The pathname on a #include may be surrounded by '<' and '>'.
1295 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1296 my $clean = 'X' x length($1);
1297 $res =~ s@\<.*\>@<$clean>@;
1299 # The whole of a #error is a string.
1300 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1301 my $clean = 'X' x length($1);
1302 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1305 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1307 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1313 sub get_quoted_string {
1314 my ($line, $rawline) = @_;
1316 return "" if (!defined($line) || !defined($rawline));
1317 return "" if ($line !~ m/($String)/g);
1318 return substr($rawline, $-[0], $+[0] - $-[0]);
1321 sub ctx_statement_block {
1322 my ($linenr, $remain, $off) = @_;
1323 my $line = $linenr - 1;
1326 my $coff = $off - 1;
1340 @stack = (['', 0]) if ($#stack == -1);
1342 #warn "CSB: blk<$blk> remain<$remain>\n";
1343 # If we are about to drop off the end, pull in more
1346 for (; $remain > 0; $line++) {
1347 last if (!defined $lines[$line]);
1348 next if ($lines[$line] =~ /^-/);
1351 $blk .= $lines[$line] . "\n";
1352 $len = length($blk);
1356 # Bail if there is no further context.
1357 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1361 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1367 $c = substr($blk, $off, 1);
1368 $remainder = substr($blk, $off);
1370 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1372 # Handle nested #if/#else.
1373 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1374 push(@stack, [ $type, $level ]);
1375 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1376 ($type, $level) = @{$stack[$#stack - 1]};
1377 } elsif ($remainder =~ /^#\s*endif\b/) {
1378 ($type, $level) = @{pop(@stack)};
1381 # Statement ends at the ';' or a close '}' at the
1383 if ($level == 0 && $c eq ';') {
1387 # An else is really a conditional as long as its not else if
1388 if ($level == 0 && $coff_set == 0 &&
1389 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1390 $remainder =~ /^(else)(?:\s|{)/ &&
1391 $remainder !~ /^else\s+if\b/) {
1392 $coff = $off + length($1) - 1;
1394 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1395 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1398 if (($type eq '' || $type eq '(') && $c eq '(') {
1402 if ($type eq '(' && $c eq ')') {
1404 $type = ($level != 0)? '(' : '';
1406 if ($level == 0 && $coff < $soff) {
1409 #warn "CSB: mark coff<$coff>\n";
1412 if (($type eq '' || $type eq '{') && $c eq '{') {
1416 if ($type eq '{' && $c eq '}') {
1418 $type = ($level != 0)? '{' : '';
1421 if (substr($blk, $off + 1, 1) eq ';') {
1427 # Preprocessor commands end at the newline unless escaped.
1428 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1436 # We are truly at the end, so shuffle to the next line.
1443 my $statement = substr($blk, $soff, $off - $soff + 1);
1444 my $condition = substr($blk, $soff, $coff - $soff + 1);
1446 #warn "STATEMENT<$statement>\n";
1447 #warn "CONDITION<$condition>\n";
1449 #print "coff<$coff> soff<$off> loff<$loff>\n";
1451 return ($statement, $condition,
1452 $line, $remain + 1, $off - $loff + 1, $level);
1455 sub statement_lines {
1458 # Strip the diff line prefixes and rip blank lines at start and end.
1459 $stmt =~ s/(^|\n)./$1/g;
1463 my @stmt_lines = ($stmt =~ /\n/g);
1465 return $#stmt_lines + 2;
1468 sub statement_rawlines {
1471 my @stmt_lines = ($stmt =~ /\n/g);
1473 return $#stmt_lines + 2;
1476 sub statement_block_size {
1479 $stmt =~ s/(^|\n)./$1/g;
1485 my @stmt_lines = ($stmt =~ /\n/g);
1486 my @stmt_statements = ($stmt =~ /;/g);
1488 my $stmt_lines = $#stmt_lines + 2;
1489 my $stmt_statements = $#stmt_statements + 1;
1491 if ($stmt_lines > $stmt_statements) {
1494 return $stmt_statements;
1498 sub ctx_statement_full {
1499 my ($linenr, $remain, $off) = @_;
1500 my ($statement, $condition, $level);
1504 # Grab the first conditional/block pair.
1505 ($statement, $condition, $linenr, $remain, $off, $level) =
1506 ctx_statement_block($linenr, $remain, $off);
1507 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1508 push(@chunks, [ $condition, $statement ]);
1509 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1510 return ($level, $linenr, @chunks);
1513 # Pull in the following conditional/block pairs and see if they
1514 # could continue the statement.
1516 ($statement, $condition, $linenr, $remain, $off, $level) =
1517 ctx_statement_block($linenr, $remain, $off);
1518 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1519 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1521 push(@chunks, [ $condition, $statement ]);
1524 return ($level, $linenr, @chunks);
1528 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1530 my $start = $linenr - 1;
1537 my @stack = ($level);
1538 for ($line = $start; $remain > 0; $line++) {
1539 next if ($rawlines[$line] =~ /^-/);
1542 $blk .= $rawlines[$line];
1544 # Handle nested #if/#else.
1545 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1546 push(@stack, $level);
1547 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1548 $level = $stack[$#stack - 1];
1549 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1550 $level = pop(@stack);
1553 foreach my $c (split(//, $lines[$line])) {
1554 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1560 if ($c eq $close && $level > 0) {
1562 last if ($level == 0);
1563 } elsif ($c eq $open) {
1568 if (!$outer || $level <= 1) {
1569 push(@res, $rawlines[$line]);
1572 last if ($level == 0);
1575 return ($level, @res);
1577 sub ctx_block_outer {
1578 my ($linenr, $remain) = @_;
1580 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1584 my ($linenr, $remain) = @_;
1586 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1590 my ($linenr, $remain, $off) = @_;
1592 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1595 sub ctx_block_level {
1596 my ($linenr, $remain) = @_;
1598 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1600 sub ctx_statement_level {
1601 my ($linenr, $remain, $off) = @_;
1603 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1606 sub ctx_locate_comment {
1607 my ($first_line, $end_line) = @_;
1609 # Catch a comment on the end of the line itself.
1610 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1611 return $current_comment if (defined $current_comment);
1613 # Look through the context and try and figure out if there is a
1616 $current_comment = '';
1617 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1618 my $line = $rawlines[$linenr - 1];
1620 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1623 if ($line =~ m@/\*@) {
1626 if (!$in_comment && $current_comment ne '') {
1627 $current_comment = '';
1629 $current_comment .= $line . "\n" if ($in_comment);
1630 if ($line =~ m@\*/@) {
1635 chomp($current_comment);
1636 return($current_comment);
1638 sub ctx_has_comment {
1639 my ($first_line, $end_line) = @_;
1640 my $cmt = ctx_locate_comment($first_line, $end_line);
1642 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1643 ##print "CMMT: $cmt\n";
1645 return ($cmt ne '');
1649 my ($linenr, $cnt) = @_;
1651 my $offset = $linenr - 1;
1656 $line = $rawlines[$offset++];
1657 next if (defined($line) && $line =~ /^-/);
1665 my ($linenr, $lc) = @_;
1667 my $stat_real = raw_line($linenr, 0);
1668 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1669 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1676 my ($linenr, $cnt, $here) = @_;
1678 my $herectx = $here . "\n";
1679 for (my $n = 0; $n < $cnt; $n++) {
1680 $herectx .= raw_line($linenr, $n) . "\n";
1691 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1694 $coded = sprintf("^%c", unpack('C', $2) + 64);
1703 my $av_preprocessor = 0;
1708 sub annotate_reset {
1709 $av_preprocessor = 0;
1711 @av_paren_type = ('E');
1712 $av_pend_colon = 'O';
1715 sub annotate_values {
1716 my ($stream, $type) = @_;
1719 my $var = '_' x length($stream);
1722 print "$stream\n" if ($dbg_values > 1);
1724 while (length($cur)) {
1725 @av_paren_type = ('E') if ($#av_paren_type < 0);
1726 print " <" . join('', @av_paren_type) .
1727 "> <$type> <$av_pending>" if ($dbg_values > 1);
1728 if ($cur =~ /^(\s+)/o) {
1729 print "WS($1)\n" if ($dbg_values > 1);
1730 if ($1 =~ /\n/ && $av_preprocessor) {
1731 $type = pop(@av_paren_type);
1732 $av_preprocessor = 0;
1735 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1736 print "CAST($1)\n" if ($dbg_values > 1);
1737 push(@av_paren_type, $type);
1740 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1741 print "DECLARE($1)\n" if ($dbg_values > 1);
1744 } elsif ($cur =~ /^($Modifier)\s*/) {
1745 print "MODIFIER($1)\n" if ($dbg_values > 1);
1748 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1749 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1750 $av_preprocessor = 1;
1751 push(@av_paren_type, $type);
1757 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1758 print "UNDEF($1)\n" if ($dbg_values > 1);
1759 $av_preprocessor = 1;
1760 push(@av_paren_type, $type);
1762 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1763 print "PRE_START($1)\n" if ($dbg_values > 1);
1764 $av_preprocessor = 1;
1766 push(@av_paren_type, $type);
1767 push(@av_paren_type, $type);
1770 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1771 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1772 $av_preprocessor = 1;
1774 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1778 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1779 print "PRE_END($1)\n" if ($dbg_values > 1);
1781 $av_preprocessor = 1;
1783 # Assume all arms of the conditional end as this
1784 # one does, and continue as if the #endif was not here.
1785 pop(@av_paren_type);
1786 push(@av_paren_type, $type);
1789 } elsif ($cur =~ /^(\\\n)/o) {
1790 print "PRECONT($1)\n" if ($dbg_values > 1);
1792 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1793 print "ATTR($1)\n" if ($dbg_values > 1);
1794 $av_pending = $type;
1797 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1798 print "SIZEOF($1)\n" if ($dbg_values > 1);
1804 } elsif ($cur =~ /^(if|while|for)\b/o) {
1805 print "COND($1)\n" if ($dbg_values > 1);
1809 } elsif ($cur =~/^(case)/o) {
1810 print "CASE($1)\n" if ($dbg_values > 1);
1811 $av_pend_colon = 'C';
1814 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1815 print "KEYWORD($1)\n" if ($dbg_values > 1);
1818 } elsif ($cur =~ /^(\()/o) {
1819 print "PAREN('$1')\n" if ($dbg_values > 1);
1820 push(@av_paren_type, $av_pending);
1824 } elsif ($cur =~ /^(\))/o) {
1825 my $new_type = pop(@av_paren_type);
1826 if ($new_type ne '_') {
1828 print "PAREN('$1') -> $type\n"
1829 if ($dbg_values > 1);
1831 print "PAREN('$1')\n" if ($dbg_values > 1);
1834 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1835 print "FUNC($1)\n" if ($dbg_values > 1);
1839 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1840 if (defined $2 && $type eq 'C' || $type eq 'T') {
1841 $av_pend_colon = 'B';
1842 } elsif ($type eq 'E') {
1843 $av_pend_colon = 'L';
1845 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1848 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1849 print "IDENT($1)\n" if ($dbg_values > 1);
1852 } elsif ($cur =~ /^($Assignment)/o) {
1853 print "ASSIGN($1)\n" if ($dbg_values > 1);
1856 } elsif ($cur =~/^(;|{|})/) {
1857 print "END($1)\n" if ($dbg_values > 1);
1859 $av_pend_colon = 'O';
1861 } elsif ($cur =~/^(,)/) {
1862 print "COMMA($1)\n" if ($dbg_values > 1);
1865 } elsif ($cur =~ /^(\?)/o) {
1866 print "QUESTION($1)\n" if ($dbg_values > 1);
1869 } elsif ($cur =~ /^(:)/o) {
1870 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1872 substr($var, length($res), 1, $av_pend_colon);
1873 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1878 $av_pend_colon = 'O';
1880 } elsif ($cur =~ /^(\[)/o) {
1881 print "CLOSE($1)\n" if ($dbg_values > 1);
1884 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1887 print "OPV($1)\n" if ($dbg_values > 1);
1894 substr($var, length($res), 1, $variant);
1897 } elsif ($cur =~ /^($Operators)/o) {
1898 print "OP($1)\n" if ($dbg_values > 1);
1899 if ($1 ne '++' && $1 ne '--') {
1903 } elsif ($cur =~ /(^.)/o) {
1904 print "C($1)\n" if ($dbg_values > 1);
1907 $cur = substr($cur, length($1));
1908 $res .= $type x length($1);
1912 return ($res, $var);
1916 my ($possible, $line) = @_;
1917 my $notPermitted = qr{(?:
1934 ^(?:typedef|struct|enum)\b
1936 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1937 if ($possible !~ $notPermitted) {
1938 # Check for modifiers.
1939 $possible =~ s/\s*$Storage\s*//g;
1940 $possible =~ s/\s*$Sparse\s*//g;
1941 if ($possible =~ /^\s*$/) {
1943 } elsif ($possible =~ /\s/) {
1944 $possible =~ s/\s*$Type\s*//g;
1945 for my $modifier (split(' ', $possible)) {
1946 if ($modifier !~ $notPermitted) {
1947 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1948 push(@modifierListFile, $modifier);
1953 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1954 push(@typeListFile, $possible);
1958 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1967 $type =~ tr/[a-z]/[A-Z]/;
1969 return defined $use_type{$type} if (scalar keys %use_type > 0);
1971 return !defined $ignore_type{$type};
1975 my ($level, $type, $msg) = @_;
1977 if (!show_type($type) ||
1978 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1983 if ($level eq 'ERROR') {
1985 } elsif ($level eq 'WARNING') {
1991 $output .= $prefix . $level . ':';
1993 $output .= BLUE if ($color);
1994 $output .= "$type:";
1996 $output .= RESET if ($color);
1997 $output .= ' ' . $msg . "\n";
2000 my @lines = split("\n", $output, -1);
2001 splice(@lines, 1, 1);
2002 $output = join("\n", @lines);
2004 $output = (split('\n', $output))[0] . "\n" if ($terse);
2006 push(our @report, $output);
2015 sub fixup_current_range {
2016 my ($lineRef, $offset, $length) = @_;
2018 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2021 my $no = $o + $offset;
2022 my $nl = $l + $length;
2023 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2027 sub fix_inserted_deleted_lines {
2028 my ($linesRef, $insertedRef, $deletedRef) = @_;
2030 my $range_last_linenr = 0;
2031 my $delta_offset = 0;
2036 my $next_insert = 0;
2037 my $next_delete = 0;
2041 my $inserted = @{$insertedRef}[$next_insert++];
2042 my $deleted = @{$deletedRef}[$next_delete++];
2044 foreach my $old_line (@{$linesRef}) {
2046 my $line = $old_line; #don't modify the array
2047 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2049 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2050 $range_last_linenr = $new_linenr;
2051 fixup_current_range(\$line, $delta_offset, 0);
2054 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2055 $deleted = @{$deletedRef}[$next_delete++];
2057 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2060 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2061 push(@lines, ${$inserted}{'LINE'});
2062 $inserted = @{$insertedRef}[$next_insert++];
2064 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2068 push(@lines, $line);
2078 sub fix_insert_line {
2079 my ($linenr, $line) = @_;
2085 push(@fixed_inserted, $inserted);
2088 sub fix_delete_line {
2089 my ($linenr, $line) = @_;
2096 push(@fixed_deleted, $deleted);
2100 my ($type, $msg) = @_;
2102 if (report("ERROR", $type, $msg)) {
2110 my ($type, $msg) = @_;
2112 if (report("WARNING", $type, $msg)) {
2120 my ($type, $msg) = @_;
2122 if ($check && report("CHECK", $type, $msg)) {
2130 sub check_absolute_file {
2131 my ($absolute, $herecurr) = @_;
2132 my $file = $absolute;
2134 ##print "absolute<$absolute>\n";
2136 # See if any suffix of this path is a path within the tree.
2137 while ($file =~ s@^[^/]*/@@) {
2138 if (-f "$root/$file") {
2139 ##print "file<$file>\n";
2147 # It is, so see if the prefix is acceptable.
2148 my $prefix = $absolute;
2149 substr($prefix, -length($file)) = '';
2151 ##print "prefix<$prefix>\n";
2152 if ($prefix ne ".../") {
2153 WARN("USE_RELATIVE_PATH",
2154 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2161 $string =~ s/^\s+|\s+$//g;
2169 $string =~ s/^\s+//;
2177 $string =~ s/\s+$//;
2182 sub string_find_replace {
2183 my ($string, $find, $replace) = @_;
2185 $string =~ s/$find/$replace/g;
2193 my $source_indent = 8;
2194 my $max_spaces_before_tab = $source_indent - 1;
2195 my $spaces_to_tab = " " x $source_indent;
2197 #convert leading spaces to tabs
2198 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2199 #Remove spaces before a tab
2200 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2205 sub pos_last_openparen {
2210 my $opens = $line =~ tr/\(/\(/;
2211 my $closes = $line =~ tr/\)/\)/;
2213 my $last_openparen = 0;
2215 if (($opens == 0) || ($closes >= $opens)) {
2219 my $len = length($line);
2221 for ($pos = 0; $pos < $len; $pos++) {
2222 my $string = substr($line, $pos);
2223 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2224 $pos += length($1) - 1;
2225 } elsif (substr($line, $pos, 1) eq '(') {
2226 $last_openparen = $pos;
2227 } elsif (index($string, '(') == -1) {
2232 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2236 my $filename = shift;
2242 my $stashrawline="";
2252 my $authorsignoff = 0;
2254 my $in_header_lines = $file ? 0 : 1;
2255 my $in_commit_log = 0; #Scanning lines before patch
2256 my $has_commit_log = 0; #Encountered lines before patch
2257 my $commit_log_lines = 0; #Number of commit log lines
2258 my $commit_log_possible_stack_dump = 0;
2259 my $commit_log_long_line = 0;
2260 my $commit_log_has_diff = 0;
2261 my $reported_maintainer_file = 0;
2262 my $non_utf8_charset = 0;
2264 my $last_blank_line = 0;
2265 my $last_coalesced_string_linenr = -1;
2273 # Trace the real file/line as we go.
2278 my $context_function; #undef'd unless there's a known function
2280 my $comment_edge = 0;
2284 my $prev_values = 'E';
2287 my %suppress_ifbraces;
2288 my %suppress_whiletrailers;
2289 my %suppress_export;
2290 my $suppress_statement = 0;
2292 my %signatures = ();
2294 # Pre-scan the patch sanitizing the lines.
2295 # Pre-scan the patch looking for any __setup documentation.
2297 my @setup_docs = ();
2300 my $camelcase_file_seeded = 0;
2302 my $checklicenseline = 1;
2304 sanitise_line_reset();
2306 foreach my $rawline (@rawlines) {
2310 push(@fixed, $rawline) if ($fix);
2312 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2314 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2319 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2328 # Guestimate if this is a continuing comment. Run
2329 # the context looking for a comment "edge". If this
2330 # edge is a close comment then we must be in a comment
2334 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2335 next if (defined $rawlines[$ln - 1] &&
2336 $rawlines[$ln - 1] =~ /^-/);
2338 #print "RAW<$rawlines[$ln - 1]>\n";
2339 last if (!defined $rawlines[$ln - 1]);
2340 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2341 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2346 if (defined $edge && $edge eq '*/') {
2350 # Guestimate if this is a continuing comment. If this
2351 # is the start of a diff block and this line starts
2352 # ' *' then it is very likely a comment.
2353 if (!defined $edge &&
2354 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2359 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2360 sanitise_line_reset($in_comment);
2362 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2363 # Standardise the strings and chars within the input to
2364 # simplify matching -- only bother with positive lines.
2365 $line = sanitise_line($rawline);
2367 push(@lines, $line);
2370 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2375 #print "==>$rawline\n";
2376 #print "-->$line\n";
2378 if ($setup_docs && $line =~ /^\+/) {
2379 push(@setup_docs, $line);
2388 foreach my $line (@lines) {
2391 my $sline = $line; #copy of $line
2392 $sline =~ s/$;/ /g; #with comments as spaces
2394 my $rawline = $rawlines[$linenr - 1];
2396 # check if it's a mode change, rename or start of a patch
2397 if (!$in_commit_log &&
2398 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2399 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2400 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2404 #extract the line range in the file after the patch is applied
2405 if (!$in_commit_log &&
2406 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2409 $first_line = $linenr + 1;
2419 %suppress_ifbraces = ();
2420 %suppress_whiletrailers = ();
2421 %suppress_export = ();
2422 $suppress_statement = 0;
2423 if ($context =~ /\b(\w+)\s*\(/) {
2424 $context_function = $1;
2426 undef $context_function;
2430 # track the line number as we move through the hunk, note that
2431 # new versions of GNU diff omit the leading space on completely
2432 # blank context lines so we need to count that too.
2433 } elsif ($line =~ /^( |\+|$)/) {
2435 $realcnt-- if ($realcnt != 0);
2437 # Measure the line length and indent.
2438 ($length, $indent) = line_stats($rawline);
2440 # Track the previous line.
2441 ($prevline, $stashline) = ($stashline, $line);
2442 ($previndent, $stashindent) = ($stashindent, $indent);
2443 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2445 #warn "line<$line>\n";
2447 } elsif ($realcnt == 1) {
2451 my $hunk_line = ($realcnt != 0);
2453 $here = "#$linenr: " if (!$file);
2454 $here = "#$realline: " if ($file);
2457 # extract the filename as it passes
2458 if ($line =~ /^diff --git.*?(\S+)$/) {
2460 $realfile =~ s@^([^/]*)/@@ if (!$file);
2463 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2465 $realfile =~ s@^([^/]*)/@@ if (!$file);
2469 if (!$file && $tree && $p1_prefix ne '' &&
2470 -e "$root/$p1_prefix") {
2471 WARN("PATCH_PREFIX",
2472 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2475 if ($realfile =~ m@^include/asm/@) {
2476 ERROR("MODIFIED_INCLUDE_ASM",
2477 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2482 #make up the handle for any error we report on this line
2484 $prefix = "$realfile:$realline: "
2487 $prefix = "$filename:$realline: ";
2489 $prefix = "$filename:$linenr: ";
2494 if (is_maintained_obsolete($realfile)) {
2496 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2498 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2501 $check = $check_orig;
2503 $checklicenseline = 1;
2507 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2509 my $hereline = "$here\n$rawline\n";
2510 my $herecurr = "$here\n$rawline\n";
2511 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2513 $cnt_lines++ if ($realcnt != 0);
2515 # Verify the existence of a commit log if appropriate
2516 # 2 is used because a $signature is counted in $commit_log_lines
2517 if ($in_commit_log) {
2518 if ($line !~ /^\s*$/) {
2519 $commit_log_lines++; #could be a $signature
2521 } elsif ($has_commit_log && $commit_log_lines < 2) {
2522 WARN("COMMIT_MESSAGE",
2523 "Missing commit description - Add an appropriate one\n");
2524 $commit_log_lines = 2; #warn only once
2527 # Check if the commit log has what seems like a diff which can confuse patch
2528 if ($in_commit_log && !$commit_log_has_diff &&
2529 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2530 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2531 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2532 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2533 ERROR("DIFF_IN_COMMIT_MSG",
2534 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2535 $commit_log_has_diff = 1;
2538 # Check for incorrect file permissions
2539 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2540 my $permhere = $here . "FILE: $realfile\n";
2541 if ($realfile !~ m@scripts/@ &&
2542 $realfile !~ /\.(py|pl|awk|sh)$/) {
2543 ERROR("EXECUTE_PERMISSIONS",
2544 "do not set execute permissions for source files\n" . $permhere);
2548 # Check the patch for a From:
2549 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2551 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2555 # Check the patch for a signoff:
2556 if ($line =~ /^\s*signed-off-by:/i) {
2559 if ($author ne '') {
2562 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2568 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2569 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2570 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2571 $reported_maintainer_file = 1;
2574 # Check signature styles
2575 if (!$in_header_lines &&
2576 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2577 my $space_before = $1;
2579 my $space_after = $3;
2581 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2583 if ($sign_off !~ /$signature_tags/) {
2584 WARN("BAD_SIGN_OFF",
2585 "Non-standard signature: $sign_off\n" . $herecurr);
2587 if (defined $space_before && $space_before ne "") {
2588 if (WARN("BAD_SIGN_OFF",
2589 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2591 $fixed[$fixlinenr] =
2592 "$ucfirst_sign_off $email";
2595 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2596 if (WARN("BAD_SIGN_OFF",
2597 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2599 $fixed[$fixlinenr] =
2600 "$ucfirst_sign_off $email";
2604 if (!defined $space_after || $space_after ne " ") {
2605 if (WARN("BAD_SIGN_OFF",
2606 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2608 $fixed[$fixlinenr] =
2609 "$ucfirst_sign_off $email";
2613 my ($email_name, $email_address, $comment) = parse_email($email);
2614 my $suggested_email = format_email(($email_name, $email_address));
2615 if ($suggested_email eq "") {
2616 ERROR("BAD_SIGN_OFF",
2617 "Unrecognized email address: '$email'\n" . $herecurr);
2619 my $dequoted = $suggested_email;
2620 $dequoted =~ s/^"//;
2621 $dequoted =~ s/" </ </;
2622 # Don't force email to have quotes
2623 # Allow just an angle bracketed address
2624 if ("$dequoted$comment" ne $email &&
2625 "<$email_address>$comment" ne $email &&
2626 "$suggested_email$comment" ne $email) {
2627 WARN("BAD_SIGN_OFF",
2628 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2632 # Check for duplicate signatures
2633 my $sig_nospace = $line;
2634 $sig_nospace =~ s/\s//g;
2635 $sig_nospace = lc($sig_nospace);
2636 if (defined $signatures{$sig_nospace}) {
2637 WARN("BAD_SIGN_OFF",
2638 "Duplicate signature\n" . $herecurr);
2640 $signatures{$sig_nospace} = 1;
2644 # Check email subject for common tools that don't need to be mentioned
2645 if ($in_header_lines &&
2646 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2647 WARN("EMAIL_SUBJECT",
2648 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2651 # Check for unwanted Gerrit info
2652 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2653 ERROR("GERRIT_CHANGE_ID",
2654 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2657 # Check if the commit log is in a possible stack dump
2658 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2659 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2660 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2662 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2663 # stack dump address
2664 $commit_log_possible_stack_dump = 1;
2667 # Check for line lengths > 75 in commit log, warn once
2668 if ($in_commit_log && !$commit_log_long_line &&
2669 length($line) > 75 &&
2670 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2671 # file delta changes
2672 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2674 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2675 # A Fixes: or Link: line
2676 $commit_log_possible_stack_dump)) {
2677 WARN("COMMIT_LOG_LONG_LINE",
2678 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2679 $commit_log_long_line = 1;
2682 # Reset possible stack dump if a blank line is found
2683 if ($in_commit_log && $commit_log_possible_stack_dump &&
2685 $commit_log_possible_stack_dump = 0;
2688 # Check for git id commit length and improperly formed commit descriptions
2689 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2690 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2691 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2692 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2693 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2694 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2695 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2696 my $init_char = "c";
2697 my $orig_commit = "";
2704 my $id = '0123456789ab';
2705 my $orig_desc = "commit description";
2706 my $description = "";
2708 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2710 $orig_commit = lc($2);
2711 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2712 $orig_commit = lc($1);
2715 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2716 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2717 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2718 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2719 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2722 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2723 defined $rawlines[$linenr] &&
2724 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2727 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2728 defined $rawlines[$linenr] &&
2729 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2730 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2732 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2733 $orig_desc .= " " . $1;
2737 ($id, $description) = git_commit_info($orig_commit,
2741 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2742 ERROR("GIT_COMMIT_ID",
2743 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2747 # Check for added, moved or deleted files
2748 if (!$reported_maintainer_file && !$in_commit_log &&
2749 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2750 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2751 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2752 (defined($1) || defined($2))))) {
2754 $reported_maintainer_file = 1;
2755 WARN("FILE_PATH_CHANGES",
2756 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2759 # Check for wrappage within a valid hunk of the file
2760 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2761 ERROR("CORRUPTED_PATCH",
2762 "patch seems to be corrupt (line wrapped?)\n" .
2763 $herecurr) if (!$emitted_corrupt++);
2766 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2767 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2768 $rawline !~ m/^$UTF8*$/) {
2769 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2771 my $blank = copy_spacing($rawline);
2772 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2773 my $hereptr = "$hereline$ptr\n";
2776 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2779 # Check if it's the start of a commit log
2780 # (not a header line and we haven't seen the patch filename)
2781 if ($in_header_lines && $realfile =~ /^$/ &&
2782 !($rawline =~ /^\s+(?:\S|$)/ ||
2783 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2784 $in_header_lines = 0;
2786 $has_commit_log = 1;
2789 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2790 # declined it, i.e defined some charset where it is missing.
2791 if ($in_header_lines &&
2792 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2794 $non_utf8_charset = 1;
2797 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2798 $rawline =~ /$NON_ASCII_UTF8/) {
2799 WARN("UTF8_BEFORE_PATCH",
2800 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2803 # Check for absolute kernel paths in commit message
2804 if ($tree && $in_commit_log) {
2805 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2808 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2809 check_absolute_file($1, $herecurr)) {
2812 check_absolute_file($file, $herecurr);
2817 # Check for various typo / spelling mistakes
2818 if (defined($misspellings) &&
2819 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2820 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2822 my $typo_fix = $spelling_fix{lc($typo)};
2823 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2824 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2825 my $msg_level = \&WARN;
2826 $msg_level = \&CHK if ($file);
2827 if (&{$msg_level}("TYPO_SPELLING",
2828 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2830 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2835 # ignore non-hunk lines and lines being removed
2836 next if (!$hunk_line || $line =~ /^-/);
2838 #trailing whitespace
2839 if ($line =~ /^\+.*\015/) {
2840 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2841 if (ERROR("DOS_LINE_ENDINGS",
2842 "DOS line endings\n" . $herevet) &&
2844 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2846 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2847 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2848 if (ERROR("TRAILING_WHITESPACE",
2849 "trailing whitespace\n" . $herevet) &&
2851 $fixed[$fixlinenr] =~ s/\s+$//;
2857 # Check for FSF mailing addresses.
2858 if ($rawline =~ /\bwrite to the Free/i ||
2859 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2860 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2861 $rawline =~ /\b51\s+Franklin\s+St/i) {
2862 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2863 my $msg_level = \&ERROR;
2864 $msg_level = \&CHK if ($file);
2865 &{$msg_level}("FSF_MAILING_ADDRESS",
2866 "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)
2869 # check for Kconfig help text having a real description
2870 # Only applies when adding the entry originally, after that we do not have
2871 # sufficient context to determine whether it is indeed long enough.
2872 if ($realfile =~ /Kconfig/ &&
2873 # 'choice' is usually the last thing on the line (though
2874 # Kconfig supports named choices), so use a word boundary
2875 # (\b) rather than a whitespace character (\s)
2876 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2879 my $ln = $linenr + 1;
2883 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2884 $f = $lines[$ln - 1];
2885 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2886 $is_end = $lines[$ln - 1] =~ /^\+/;
2888 next if ($f =~ /^-/);
2889 last if (!$file && $f =~ /^\@\@/);
2891 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2893 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2894 if ($lines[$ln - 1] =~ "---help---") {
2895 WARN("CONFIG_DESCRIPTION",
2896 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2904 next if ($f =~ /^$/);
2906 # This only checks context lines in the patch
2907 # and so hopefully shouldn't trigger false
2908 # positives, even though some of these are
2909 # common words in help texts
2910 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2911 if|endif|menu|endmenu|source)\b/x) {
2917 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2918 WARN("CONFIG_DESCRIPTION",
2919 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2921 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2924 # check for MAINTAINERS entries that don't have the right form
2925 if ($realfile =~ /^MAINTAINERS$/ &&
2926 $rawline =~ /^\+[A-Z]:/ &&
2927 $rawline !~ /^\+[A-Z]:\t\S/) {
2928 if (WARN("MAINTAINERS_STYLE",
2929 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2931 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2935 # discourage the use of boolean for type definition attributes of Kconfig options
2936 if ($realfile =~ /Kconfig/ &&
2937 $line =~ /^\+\s*\bboolean\b/) {
2938 WARN("CONFIG_TYPE_BOOLEAN",
2939 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2942 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2943 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2946 'EXTRA_AFLAGS' => 'asflags-y',
2947 'EXTRA_CFLAGS' => 'ccflags-y',
2948 'EXTRA_CPPFLAGS' => 'cppflags-y',
2949 'EXTRA_LDFLAGS' => 'ldflags-y',
2952 WARN("DEPRECATED_VARIABLE",
2953 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2956 # check for DT compatible documentation
2957 if (defined $root &&
2958 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2959 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2961 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2963 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2964 my $vp_file = $dt_path . "vendor-prefixes.txt";
2966 foreach my $compat (@compats) {
2967 my $compat2 = $compat;
2968 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2969 my $compat3 = $compat;
2970 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2971 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2973 WARN("UNDOCUMENTED_DT_STRING",
2974 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2977 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2979 `grep -Eq "^$vendor\\b" $vp_file`;
2981 WARN("UNDOCUMENTED_DT_STRING",
2982 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2987 # check for using SPDX license tag at beginning of files
2988 if ($realline == $checklicenseline) {
2989 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
2990 $checklicenseline = 2;
2991 } elsif ($rawline =~ /^\+/) {
2993 if ($realfile =~ /\.(h|s|S)$/) {
2995 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
2997 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
2999 } elsif ($realfile =~ /\.rst$/) {
3003 if ($comment !~ /^$/ &&
3004 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3005 WARN("SPDX_LICENSE_TAG",
3006 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3007 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3008 my $spdx_license = $1;
3009 if (!is_SPDX_License_valid($spdx_license)) {
3010 WARN("SPDX_LICENSE_TAG",
3011 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3017 # check we are in a valid source file if not then ignore this hunk
3018 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3020 # line length limit (with some exclusions)
3022 # There are a few types of lines that may extend beyond $max_line_length:
3023 # logging functions like pr_info that end in a string
3024 # lines with a single string
3025 # #defines that are a single string
3026 # lines with an RFC3986 like URL
3028 # There are 3 different line length message types:
3029 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3030 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3031 # LONG_LINE all other lines longer than $max_line_length
3033 # if LONG_LINE is ignored, the other 2 types are also ignored
3036 if ($line =~ /^\+/ && $length > $max_line_length) {
3037 my $msg_type = "LONG_LINE";
3039 # Check the allowed long line types first
3041 # logging functions that end in a string that starts
3042 # before $max_line_length
3043 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3044 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3047 # lines with only strings (w/ possible termination)
3048 # #defines with only strings
3049 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3050 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3053 # More special cases
3054 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3055 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3058 # URL ($rawline is used in case the URL is in a comment)
3059 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3062 # Otherwise set the alternate message types
3064 # a comment starts before $max_line_length
3065 } elsif ($line =~ /($;[\s$;]*)$/ &&
3066 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3067 $msg_type = "LONG_LINE_COMMENT"
3069 # a quoted string starts before $max_line_length
3070 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3071 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3072 $msg_type = "LONG_LINE_STRING"
3075 if ($msg_type ne "" &&
3076 (show_type("LONG_LINE") || show_type($msg_type))) {
3078 "line over $max_line_length characters\n" . $herecurr);
3082 # check for adding lines without a newline.
3083 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3084 WARN("MISSING_EOF_NEWLINE",
3085 "adding a line without newline at end of file\n" . $herecurr);
3088 # check we are in a valid source file C or perl if not then ignore this hunk
3089 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3091 # at the beginning of a line any tabs must come first and anything
3092 # more than 8 must use tabs.
3093 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3094 $rawline =~ /^\+\s* \s*/) {
3095 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3097 if (ERROR("CODE_INDENT",
3098 "code indent should use tabs where possible\n" . $herevet) &&
3100 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3104 # check for space before tabs.
3105 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3106 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3107 if (WARN("SPACE_BEFORE_TAB",
3108 "please, no space before tabs\n" . $herevet) &&
3110 while ($fixed[$fixlinenr] =~
3111 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3112 while ($fixed[$fixlinenr] =~
3113 s/(^\+.*) +\t/$1\t/) {}
3117 # check for assignments on the start of a line
3118 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3119 CHK("ASSIGNMENT_CONTINUATIONS",
3120 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3123 # check for && or || at the start of a line
3124 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3125 CHK("LOGICAL_CONTINUATIONS",
3126 "Logical continuations should be on the previous line\n" . $hereprev);
3129 # check indentation starts on a tab stop
3130 if ($perl_version_ok &&
3131 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3132 my $indent = length($1);
3135 "Statements should start on a tabstop\n" . $herecurr) &&
3137 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3142 # check multi-line statement indentation matches previous line
3143 if ($perl_version_ok &&
3144 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3145 $prevline =~ /^\+(\t*)(.*)$/;
3149 my $pos = pos_last_openparen($rest);
3151 $line =~ /^(\+| )([ \t]*)/;
3154 my $goodtabindent = $oldindent .
3157 my $goodspaceindent = $oldindent . " " x $pos;
3159 if ($newindent ne $goodtabindent &&
3160 $newindent ne $goodspaceindent) {
3162 if (CHK("PARENTHESIS_ALIGNMENT",
3163 "Alignment should match open parenthesis\n" . $hereprev) &&
3164 $fix && $line =~ /^\+/) {
3165 $fixed[$fixlinenr] =~
3166 s/^\+[ \t]*/\+$goodtabindent/;
3172 # check for space after cast like "(int) foo" or "(struct foo) bar"
3173 # avoid checking a few false positives:
3174 # "sizeof(<type>)" or "__alignof__(<type>)"
3175 # function pointer declarations like "(*foo)(int) = bar;"
3176 # structure definitions like "(struct foo) { 0 };"
3177 # multiline macros that define functions
3178 # known attributes or the __attribute__ keyword
3179 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3180 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3182 "No space is necessary after a cast\n" . $herecurr) &&
3184 $fixed[$fixlinenr] =~
3185 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3189 # Block comment styles
3190 # Networking with an initial /*
3191 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3192 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3193 $rawline =~ /^\+[ \t]*\*/ &&
3195 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3196 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3199 # Block comments use * on subsequent lines
3200 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3201 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3202 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3203 $rawline =~ /^\+/ && #line is new
3204 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3205 WARN("BLOCK_COMMENT_STYLE",
3206 "Block comments use * on subsequent lines\n" . $hereprev);
3209 # Block comments use */ on trailing lines
3210 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3211 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3212 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3213 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3214 WARN("BLOCK_COMMENT_STYLE",
3215 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3218 # Block comment * alignment
3219 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3220 $line =~ /^\+[ \t]*$;/ && #leading comment
3221 $rawline =~ /^\+[ \t]*\*/ && #leading *
3222 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3223 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3224 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3226 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3228 $oldindent = expand_tabs($1);
3230 $prevrawline =~ m@^\+(.*/?)\*@;
3231 $oldindent = expand_tabs($1);
3233 $rawline =~ m@^\+([ \t]*)\*@;
3235 $newindent = expand_tabs($newindent);
3236 if (length($oldindent) ne length($newindent)) {
3237 WARN("BLOCK_COMMENT_STYLE",
3238 "Block comments should align the * on each line\n" . $hereprev);
3242 # check for missing blank lines after struct/union declarations
3243 # with exceptions for various attributes and macros
3244 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3246 !($line =~ /^\+\s*$/ ||
3247 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3248 $line =~ /^\+\s*MODULE_/i ||
3249 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3250 $line =~ /^\+[a-z_]*init/ ||
3251 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3252 $line =~ /^\+\s*DECLARE/ ||
3253 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3254 $line =~ /^\+\s*__setup/)) {
3255 if (CHK("LINE_SPACING",
3256 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3258 fix_insert_line($fixlinenr, "\+");
3262 # check for multiple consecutive blank lines
3263 if ($prevline =~ /^[\+ ]\s*$/ &&
3264 $line =~ /^\+\s*$/ &&
3265 $last_blank_line != ($linenr - 1)) {
3266 if (CHK("LINE_SPACING",
3267 "Please don't use multiple blank lines\n" . $hereprev) &&
3269 fix_delete_line($fixlinenr, $rawline);
3272 $last_blank_line = $linenr;
3275 # check for missing blank lines after declarations
3276 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3277 # actual declarations
3278 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3279 # function pointer declarations
3280 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3281 # foo bar; where foo is some local typedef or #define
3282 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3283 # known declaration macros
3284 $prevline =~ /^\+\s+$declaration_macros/) &&
3285 # for "else if" which can look like "$Ident $Ident"
3286 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3287 # other possible extensions of declaration lines
3288 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3289 # not starting a section or a macro "\" extended line
3290 $prevline =~ /(?:\{\s*|\\)$/) &&
3291 # looks like a declaration
3292 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3293 # function pointer declarations
3294 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3295 # foo bar; where foo is some local typedef or #define
3296 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3297 # known declaration macros
3298 $sline =~ /^\+\s+$declaration_macros/ ||
3299 # start of struct or union or enum
3300 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3301 # start or end of block or continuation of declaration
3302 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3303 # bitfield continuation
3304 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3305 # other possible extensions of declaration lines
3306 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3307 # indentation of previous and current line are the same
3308 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3309 if (WARN("LINE_SPACING",
3310 "Missing a blank line after declarations\n" . $hereprev) &&
3312 fix_insert_line($fixlinenr, "\+");
3316 # check for spaces at the beginning of a line.
3318 # 1) within comments
3319 # 2) indented preprocessor commands
3321 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3322 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3323 if (WARN("LEADING_SPACE",
3324 "please, no spaces at the start of a line\n" . $herevet) &&
3326 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3330 # check we are in a valid C source file if not then ignore this hunk
3331 next if ($realfile !~ /\.(h|c)$/);
3333 # check for unusual line ending [ or (
3334 if ($line =~ /^\+.*([\[\(])\s*$/) {
3335 CHK("OPEN_ENDED_LINE",
3336 "Lines should not end with a '$1'\n" . $herecurr);
3339 # check if this appears to be the start function declaration, save the name
3340 if ($sline =~ /^\+\{\s*$/ &&
3341 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3342 $context_function = $1;
3345 # check if this appears to be the end of function declaration
3346 if ($sline =~ /^\+\}\s*$/) {
3347 undef $context_function;
3350 # check indentation of any line with a bare else
3351 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3352 # if the previous line is a break or return and is indented 1 tab more...
3353 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3354 my $tabs = length($1) + 1;
3355 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3356 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3357 defined $lines[$linenr] &&
3358 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3359 WARN("UNNECESSARY_ELSE",
3360 "else is not generally useful after a break or return\n" . $hereprev);
3364 # check indentation of a line with a break;
3365 # if the previous line is a goto or return and is indented the same # of tabs
3366 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3368 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3369 WARN("UNNECESSARY_BREAK",
3370 "break is not useful after a goto or return\n" . $hereprev);
3374 # check for RCS/CVS revision markers
3375 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3377 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3380 # check for old HOTPLUG __dev<foo> section markings
3381 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3382 WARN("HOTPLUG_SECTION",
3383 "Using $1 is unnecessary\n" . $herecurr);
3386 # Check for potential 'bare' types
3387 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3389 #print "LINE<$line>\n";
3390 if ($linenr > $suppress_statement &&
3391 $realcnt && $sline =~ /.\s*\S/) {
3392 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3393 ctx_statement_block($linenr, $realcnt, 0);
3394 $stat =~ s/\n./\n /g;
3395 $cond =~ s/\n./\n /g;
3397 #print "linenr<$linenr> <$stat>\n";
3398 # If this statement has no statement boundaries within
3399 # it there is no point in retrying a statement scan
3400 # until we hit end of it.
3401 my $frag = $stat; $frag =~ s/;+\s*$//;
3402 if ($frag !~ /(?:{|;)/) {
3403 #print "skip<$line_nr_next>\n";
3404 $suppress_statement = $line_nr_next;
3407 # Find the real next line.
3408 $realline_next = $line_nr_next;
3409 if (defined $realline_next &&
3410 (!defined $lines[$realline_next - 1] ||
3411 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3418 # Ignore goto labels.
3419 if ($s =~ /$Ident:\*$/s) {
3421 # Ignore functions being called
3422 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3424 } elsif ($s =~ /^.\s*else\b/s) {
3426 # declarations always start with types
3427 } 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) {
3430 possible($type, "A:" . $s);
3432 # definitions in global scope can only start with types
3433 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3434 possible($1, "B:" . $s);
3437 # any (foo ... *) is a pointer cast, and foo is a type
3438 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3439 possible($1, "C:" . $s);
3442 # Check for any sort of function declaration.
3443 # int foo(something bar, other baz);
3444 # void (*store_gdt)(x86_descr_ptr *);
3445 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3446 my ($name_len) = length($1);
3449 substr($ctx, 0, $name_len + 1, '');
3450 $ctx =~ s/\)[^\)]*$//;
3452 for my $arg (split(/\s*,\s*/, $ctx)) {
3453 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3455 possible($1, "D:" . $s);
3463 # Checks which may be anchored in the context.
3466 # Check for switch () and associated case and default
3467 # statements should be at the same indent.
3468 if ($line=~/\bswitch\s*\(.*\)/) {
3471 my @ctx = ctx_block_outer($linenr, $realcnt);
3473 for my $ctx (@ctx) {
3474 my ($clen, $cindent) = line_stats($ctx);
3475 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3476 $indent != $cindent) {
3477 $err .= "$sep$ctx\n";
3484 ERROR("SWITCH_CASE_INDENT_LEVEL",
3485 "switch and case should be at the same indent\n$hereline$err");
3489 # if/while/etc brace do not go on next line, unless defining a do while loop,
3490 # or if that brace on the next line is for something else
3491 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3492 my $pre_ctx = "$1$2";
3494 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3496 if ($line =~ /^\+\t{6,}/) {
3497 WARN("DEEP_INDENTATION",
3498 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3501 my $ctx_cnt = $realcnt - $#ctx - 1;
3502 my $ctx = join("\n", @ctx);
3504 my $ctx_ln = $linenr;
3505 my $ctx_skip = $realcnt;
3507 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3508 defined $lines[$ctx_ln - 1] &&
3509 $lines[$ctx_ln - 1] =~ /^-/)) {
3510 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3511 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3515 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3516 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3518 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3520 "that open brace { should be on the previous line\n" .
3521 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3523 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3524 $ctx =~ /\)\s*\;\s*$/ &&
3525 defined $lines[$ctx_ln - 1])
3527 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3528 if ($nindent > $indent) {
3529 WARN("TRAILING_SEMICOLON",
3530 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3531 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3536 # Check relative indent for conditionals and blocks.
3537 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3538 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3539 ctx_statement_block($linenr, $realcnt, 0)
3540 if (!defined $stat);
3541 my ($s, $c) = ($stat, $cond);
3543 substr($s, 0, length($c), '');
3545 # remove inline comments
3549 # Find out how long the conditional actually is.
3550 my @newlines = ($c =~ /\n/gs);
3551 my $cond_lines = 1 + $#newlines;
3553 # Make sure we remove the line prefixes as we have
3554 # none on the first line, and are going to readd them
3557 while ($s =~ /\n\s+\\\n/) {
3558 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3561 # We want to check the first line inside the block
3562 # starting at the end of the conditional, so remove:
3563 # 1) any blank line termination
3564 # 2) any opening brace { on end of the line
3566 my $continuation = 0;
3568 $s =~ s/^.*\bdo\b//;
3570 if ($s =~ s/^\s*\\//) {
3573 if ($s =~ s/^\s*?\n//) {
3578 # Also ignore a loop construct at the end of a
3579 # preprocessor statement.
3580 if (($prevline =~ /^.\s*#\s*define\s/ ||
3581 $prevline =~ /\\\s*$/) && $continuation == 0) {
3587 while ($cond_ptr != $cond_lines) {
3588 $cond_ptr = $cond_lines;
3590 # If we see an #else/#elif then the code
3592 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3597 # 1) blank lines, they should be at 0,
3598 # 2) preprocessor lines, and
3600 if ($continuation ||
3602 $s =~ /^\s*#\s*?/ ||
3603 $s =~ /^\s*$Ident\s*:/) {
3604 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3605 if ($s =~ s/^.*?\n//) {
3611 my (undef, $sindent) = line_stats("+" . $s);
3612 my $stat_real = raw_line($linenr, $cond_lines);
3614 # Check if either of these lines are modified, else
3615 # this is not this patch's fault.
3616 if (!defined($stat_real) ||
3617 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3620 if (defined($stat_real) && $cond_lines > 1) {
3621 $stat_real = "[...]\n$stat_real";
3624 #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";
3626 if ($check && $s ne '' &&
3627 (($sindent % 8) != 0 ||
3628 ($sindent < $indent) ||
3629 ($sindent == $indent &&
3630 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3631 ($sindent > $indent + 8))) {
3632 WARN("SUSPECT_CODE_INDENT",
3633 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3637 # Track the 'values' across context and added lines.
3638 my $opline = $line; $opline =~ s/^./ /;
3639 my ($curr_values, $curr_vars) =
3640 annotate_values($opline . "\n", $prev_values);
3641 $curr_values = $prev_values . $curr_values;
3643 my $outline = $opline; $outline =~ s/\t/ /g;
3644 print "$linenr > .$outline\n";
3645 print "$linenr > $curr_values\n";
3646 print "$linenr > $curr_vars\n";
3648 $prev_values = substr($curr_values, -1);
3650 #ignore lines not being added
3651 next if ($line =~ /^[^\+]/);
3653 # check for dereferences that span multiple lines
3654 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3655 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3656 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3658 $line =~ /^.\s*($Lval)/;
3661 WARN("MULTILINE_DEREFERENCE",
3662 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3665 # check for declarations of signed or unsigned without int
3666 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3669 $var = "" if (!defined $var);
3670 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3674 $pointer = "" if (!defined $pointer);
3676 if (WARN("UNSPECIFIED_INT",
3677 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3679 my $decl = trim($sign) . " int ";
3680 my $comp_pointer = $pointer;
3681 $comp_pointer =~ s/\s//g;
3682 $decl .= $comp_pointer;
3683 $decl = rtrim($decl) if ($var eq "");
3684 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3689 # TEST: allow direct testing of the type matcher.
3691 if ($line =~ /^.\s*$Declare\s*$/) {
3693 "TEST: is type\n" . $herecurr);
3694 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3695 ERROR("TEST_NOT_TYPE",
3696 "TEST: is not type ($1 is)\n". $herecurr);
3700 # TEST: allow direct testing of the attribute matcher.
3702 if ($line =~ /^.\s*$Modifier\s*$/) {
3704 "TEST: is attr\n" . $herecurr);
3705 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3706 ERROR("TEST_NOT_ATTR",
3707 "TEST: is not attr ($1 is)\n". $herecurr);
3712 # check for initialisation to aggregates open brace on the next line
3713 if ($line =~ /^.\s*{/ &&
3714 $prevline =~ /(?:^|[^=])=\s*$/) {
3715 if (ERROR("OPEN_BRACE",
3716 "that open brace { should be on the previous line\n" . $hereprev) &&
3717 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3718 fix_delete_line($fixlinenr - 1, $prevrawline);
3719 fix_delete_line($fixlinenr, $rawline);
3720 my $fixedline = $prevrawline;
3721 $fixedline =~ s/\s*=\s*$/ = {/;
3722 fix_insert_line($fixlinenr, $fixedline);
3724 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3725 fix_insert_line($fixlinenr, $fixedline);
3730 # Checks which are anchored on the added line.
3733 # check for malformed paths in #include statements (uses RAW line)
3734 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3736 if ($path =~ m{//}) {
3737 ERROR("MALFORMED_INCLUDE",
3738 "malformed #include filename\n" . $herecurr);
3740 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3741 ERROR("UAPI_INCLUDE",
3742 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3746 # no C99 // comments
3747 if ($line =~ m{//}) {
3748 if (ERROR("C99_COMMENTS",
3749 "do not use C99 // comments\n" . $herecurr) &&
3751 my $line = $fixed[$fixlinenr];
3752 if ($line =~ /\/\/(.*)$/) {
3753 my $comment = trim($1);
3754 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3758 # Remove C99 comments.
3760 $opline =~ s@//.*@@;
3762 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3763 # the whole statement.
3764 #print "APW <$lines[$realline_next - 1]>\n";
3765 if (defined $realline_next &&
3766 exists $lines[$realline_next - 1] &&
3767 !defined $suppress_export{$realline_next} &&
3768 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3769 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3770 # Handle definitions which produce identifiers with
3773 # EXPORT_SYMBOL(something_foo);
3775 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3776 $name =~ /^${Ident}_$2/) {
3777 #print "FOO C name<$name>\n";
3778 $suppress_export{$realline_next} = 1;
3780 } elsif ($stat !~ /(?:
3782 ^.DEFINE_$Ident\(\Q$name\E\)|
3783 ^.DECLARE_$Ident\(\Q$name\E\)|
3784 ^.LIST_HEAD\(\Q$name\E\)|
3785 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3786 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3788 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3789 $suppress_export{$realline_next} = 2;
3791 $suppress_export{$realline_next} = 1;
3794 if (!defined $suppress_export{$linenr} &&
3795 $prevline =~ /^.\s*$/ &&
3796 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3797 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3798 #print "FOO B <$lines[$linenr - 1]>\n";
3799 $suppress_export{$linenr} = 2;
3801 if (defined $suppress_export{$linenr} &&
3802 $suppress_export{$linenr} == 2) {
3803 WARN("EXPORT_SYMBOL",
3804 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3807 # check for global initialisers.
3808 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3809 if (ERROR("GLOBAL_INITIALISERS",
3810 "do not initialise globals to $1\n" . $herecurr) &&
3812 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3815 # check for static initialisers.
3816 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3817 if (ERROR("INITIALISED_STATIC",
3818 "do not initialise statics to $1\n" .
3821 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3825 # check for misordered declarations of char/short/int/long with signed/unsigned
3826 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3828 WARN("MISORDERED_TYPE",
3829 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3832 # check for unnecessary <signed> int declarations of short/long/long long
3833 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3834 my $type = trim($1);
3835 next if ($type !~ /\bint\b/);
3836 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3837 my $new_type = $type;
3838 $new_type =~ s/\b\s*int\s*\b/ /;
3839 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3840 $new_type =~ s/^const\s+//;
3841 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3842 $new_type = "const $new_type" if ($type =~ /^const\b/);
3843 $new_type =~ s/\s+/ /g;
3844 $new_type = trim($new_type);
3845 if (WARN("UNNECESSARY_INT",
3846 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3848 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3852 # check for static const char * arrays.
3853 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3854 WARN("STATIC_CONST_CHAR_ARRAY",
3855 "static const char * array should probably be static const char * const\n" .
3859 # check for static char foo[] = "bar" declarations.
3860 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3861 WARN("STATIC_CONST_CHAR_ARRAY",
3862 "static char array declaration should probably be static const char\n" .
3866 # check for const <foo> const where <foo> is not a pointer or array type
3867 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3869 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3871 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3872 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3874 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3878 # check for non-global char *foo[] = {"bar", ...} declarations.
3879 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3880 WARN("STATIC_CONST_CHAR_ARRAY",
3881 "char * array declaration might be better as static const\n" .
3885 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3886 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3888 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3890 if (WARN("ARRAY_SIZE",
3891 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3893 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3898 # check for function declarations without arguments like "int foo()"
3899 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3900 if (ERROR("FUNCTION_WITHOUT_ARGS",
3901 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3903 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3907 # check for new typedefs, only function parameters and sparse annotations
3909 if ($line =~ /\btypedef\s/ &&
3910 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3911 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3912 $line !~ /\b$typeTypedefs\b/ &&
3913 $line !~ /\b__bitwise\b/) {
3914 WARN("NEW_TYPEDEFS",
3915 "do not add new typedefs\n" . $herecurr);
3918 # * goes on variable not on type
3920 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3922 my ($ident, $from, $to) = ($1, $2, $2);
3924 # Should start with a space.
3925 $to =~ s/^(\S)/ $1/;
3926 # Should not end with a space.
3928 # '*'s should not have spaces between.
3929 while ($to =~ s/\*\s+\*/\*\*/) {
3932 ## print "1: from<$from> to<$to> ident<$ident>\n";
3934 if (ERROR("POINTER_LOCATION",
3935 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3937 my $sub_from = $ident;
3938 my $sub_to = $ident;
3939 $sub_to =~ s/\Q$from\E/$to/;
3940 $fixed[$fixlinenr] =~
3941 s@\Q$sub_from\E@$sub_to@;
3945 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3947 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3949 # Should start with a space.
3950 $to =~ s/^(\S)/ $1/;
3951 # Should not end with a space.
3953 # '*'s should not have spaces between.
3954 while ($to =~ s/\*\s+\*/\*\*/) {
3956 # Modifiers should have spaces.
3957 $to =~ s/(\b$Modifier$)/$1 /;
3959 ## print "2: from<$from> to<$to> ident<$ident>\n";
3960 if ($from ne $to && $ident !~ /^$Modifier$/) {
3961 if (ERROR("POINTER_LOCATION",
3962 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3965 my $sub_from = $match;
3966 my $sub_to = $match;
3967 $sub_to =~ s/\Q$from\E/$to/;
3968 $fixed[$fixlinenr] =~
3969 s@\Q$sub_from\E@$sub_to@;
3974 # avoid BUG() or BUG_ON()
3975 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3976 my $msg_level = \&WARN;
3977 $msg_level = \&CHK if ($file);
3978 &{$msg_level}("AVOID_BUG",
3979 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3982 # avoid LINUX_VERSION_CODE
3983 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3984 WARN("LINUX_VERSION_CODE",
3985 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3988 # check for uses of printk_ratelimit
3989 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3990 WARN("PRINTK_RATELIMITED",
3991 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3994 # printk should use KERN_* levels
3995 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
3996 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3997 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4000 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4002 my $level = lc($orig);
4003 $level = "warn" if ($level eq "warning");
4004 my $level2 = $level;
4005 $level2 = "dbg" if ($level eq "debug");
4006 WARN("PREFER_PR_LEVEL",
4007 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4010 if ($line =~ /\bpr_warning\s*\(/) {
4011 if (WARN("PREFER_PR_LEVEL",
4012 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4014 $fixed[$fixlinenr] =~
4015 s/\bpr_warning\b/pr_warn/;
4019 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4021 my $level = lc($orig);
4022 $level = "warn" if ($level eq "warning");
4023 $level = "dbg" if ($level eq "debug");
4024 WARN("PREFER_DEV_LEVEL",
4025 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4028 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4029 # number of false positives, but assembly files are not checked, so at
4030 # least the arch entry code will not trigger this warning.
4031 if ($line =~ /\bENOSYS\b/) {
4033 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4036 # function brace can't be on same line, except for #defines of do while,
4037 # or if closed on same line
4038 if ($perl_version_ok &&
4039 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4040 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4042 if (ERROR("OPEN_BRACE",
4043 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4045 fix_delete_line($fixlinenr, $rawline);
4046 my $fixed_line = $rawline;
4047 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4050 fix_insert_line($fixlinenr, ltrim($line1));
4051 fix_insert_line($fixlinenr, "\+{");
4052 if ($line2 !~ /^\s*$/) {
4053 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4058 # open braces for enum, union and struct go on the same line.
4059 if ($line =~ /^.\s*{/ &&
4060 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4061 if (ERROR("OPEN_BRACE",
4062 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4063 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4064 fix_delete_line($fixlinenr - 1, $prevrawline);
4065 fix_delete_line($fixlinenr, $rawline);
4066 my $fixedline = rtrim($prevrawline) . " {";
4067 fix_insert_line($fixlinenr, $fixedline);
4068 $fixedline = $rawline;
4069 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4070 if ($fixedline !~ /^\+\s*$/) {
4071 fix_insert_line($fixlinenr, $fixedline);
4076 # missing space after union, struct or enum definition
4077 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4079 "missing space after $1 definition\n" . $herecurr) &&
4081 $fixed[$fixlinenr] =~
4082 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4086 # Function pointer declarations
4087 # check spacing between type, funcptr, and args
4088 # canonical declaration is "type (*funcptr)(args...)"
4089 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4091 my $pre_pointer_space = $2;
4092 my $post_pointer_space = $3;
4094 my $post_funcname_space = $5;
4095 my $pre_args_space = $6;
4097 # the $Declare variable will capture all spaces after the type
4098 # so check it for a missing trailing missing space but pointer return types
4099 # don't need a space so don't warn for those.
4100 my $post_declare_space = "";
4101 if ($declare =~ /(\s+)$/) {
4102 $post_declare_space = $1;
4103 $declare = rtrim($declare);
4105 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4107 "missing space after return type\n" . $herecurr);
4108 $post_declare_space = " ";
4111 # unnecessary space "type (*funcptr)(args...)"
4112 # This test is not currently implemented because these declarations are
4114 # int foo(int bar, ...)
4115 # and this is form shouldn't/doesn't generate a checkpatch warning.
4117 # elsif ($declare =~ /\s{2,}$/) {
4119 # "Multiple spaces after return type\n" . $herecurr);
4122 # unnecessary space "type ( *funcptr)(args...)"
4123 if (defined $pre_pointer_space &&
4124 $pre_pointer_space =~ /^\s/) {
4126 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4129 # unnecessary space "type (* funcptr)(args...)"
4130 if (defined $post_pointer_space &&
4131 $post_pointer_space =~ /^\s/) {
4133 "Unnecessary space before function pointer name\n" . $herecurr);
4136 # unnecessary space "type (*funcptr )(args...)"
4137 if (defined $post_funcname_space &&
4138 $post_funcname_space =~ /^\s/) {
4140 "Unnecessary space after function pointer name\n" . $herecurr);
4143 # unnecessary space "type (*funcptr) (args...)"
4144 if (defined $pre_args_space &&
4145 $pre_args_space =~ /^\s/) {
4147 "Unnecessary space before function pointer arguments\n" . $herecurr);
4150 if (show_type("SPACING") && $fix) {
4151 $fixed[$fixlinenr] =~
4152 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4156 # check for spacing round square brackets; allowed:
4157 # 1. with a type on the left -- int [] a;
4158 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4159 # 3. inside a curly brace -- = { [0...10] = 5 }
4160 while ($line =~ /(.*?\s)\[/g) {
4161 my ($where, $prefix) = ($-[1], $1);
4162 if ($prefix !~ /$Type\s+$/ &&
4163 ($where != 0 || $prefix !~ /^.\s+$/) &&
4164 $prefix !~ /[{,:]\s+$/) {
4165 if (ERROR("BRACKET_SPACE",
4166 "space prohibited before open square bracket '['\n" . $herecurr) &&
4168 $fixed[$fixlinenr] =~
4169 s/^(\+.*?)\s+\[/$1\[/;
4174 # check for spaces between functions and their parentheses.
4175 while ($line =~ /($Ident)\s+\(/g) {
4177 my $ctx_before = substr($line, 0, $-[1]);
4178 my $ctx = "$ctx_before$name";
4180 # Ignore those directives where spaces _are_ permitted.
4182 if|for|while|switch|return|case|
4183 volatile|__volatile__|
4184 __attribute__|format|__extension__|
4187 # cpp #define statements have non-optional spaces, ie
4188 # if there is a space between the name and the open
4189 # parenthesis it is simply not a parameter group.
4190 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4192 # cpp #elif statement condition may start with a (
4193 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4195 # If this whole things ends with a type its most
4196 # likely a typedef for a function.
4197 } elsif ($ctx =~ /$Type$/) {
4201 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4203 $fixed[$fixlinenr] =~
4204 s/\b$name\s+\(/$name\(/;
4209 # Check operator spacing.
4210 if (!($line=~/\#\s*include/)) {
4211 my $fixed_line = "";
4215 <<=|>>=|<=|>=|==|!=|
4216 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4217 =>|->|<<|>>|<|>|=|!|~|
4218 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4221 my @elements = split(/($ops|;)/, $opline);
4223 ## print("element count: <" . $#elements . ">\n");
4224 ## foreach my $el (@elements) {
4225 ## print("el: <$el>\n");
4228 my @fix_elements = ();
4231 foreach my $el (@elements) {
4232 push(@fix_elements, substr($rawline, $off, length($el)));
4233 $off += length($el);
4238 my $blank = copy_spacing($opline);
4239 my $last_after = -1;
4241 for (my $n = 0; $n < $#elements; $n += 2) {
4243 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4245 ## print("n: <$n> good: <$good>\n");
4247 $off += length($elements[$n]);
4249 # Pick up the preceding and succeeding characters.
4250 my $ca = substr($opline, 0, $off);
4252 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4253 $cc = substr($opline, $off + length($elements[$n + 1]));
4255 my $cb = "$ca$;$cc";
4258 $a = 'V' if ($elements[$n] ne '');
4259 $a = 'W' if ($elements[$n] =~ /\s$/);
4260 $a = 'C' if ($elements[$n] =~ /$;$/);
4261 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4262 $a = 'O' if ($elements[$n] eq '');
4263 $a = 'E' if ($ca =~ /^\s*$/);
4265 my $op = $elements[$n + 1];
4268 if (defined $elements[$n + 2]) {
4269 $c = 'V' if ($elements[$n + 2] ne '');
4270 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4271 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4272 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4273 $c = 'O' if ($elements[$n + 2] eq '');
4274 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4279 my $ctx = "${a}x${c}";
4281 my $at = "(ctx:$ctx)";
4283 my $ptr = substr($blank, 0, $off) . "^";
4284 my $hereptr = "$hereline$ptr\n";
4286 # Pull out the value of this operator.
4287 my $op_type = substr($curr_values, $off + 1, 1);
4289 # Get the full operator variant.
4290 my $opv = $op . substr($curr_vars, $off, 1);
4292 # Ignore operators passed as parameters.
4293 if ($op_type ne 'V' &&
4294 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4297 # } elsif ($op =~ /^$;+$/) {
4299 # ; should have either the end of line or a space or \ after it
4300 } elsif ($op eq ';') {
4301 if ($ctx !~ /.x[WEBC]/ &&
4302 $cc !~ /^\\/ && $cc !~ /^;/) {
4303 if (ERROR("SPACING",
4304 "space required after that '$op' $at\n" . $hereptr)) {
4305 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4311 } elsif ($op eq '//') {
4313 # : when part of a bitfield
4314 } elsif ($opv eq ':B') {
4315 # skip the bitfield test for now
4319 } elsif ($op eq '->') {
4320 if ($ctx =~ /Wx.|.xW/) {
4321 if (ERROR("SPACING",
4322 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4323 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4324 if (defined $fix_elements[$n + 2]) {
4325 $fix_elements[$n + 2] =~ s/^\s+//;
4331 # , must not have a space before and must have a space on the right.
4332 } elsif ($op eq ',') {
4333 my $rtrim_before = 0;
4334 my $space_after = 0;
4335 if ($ctx =~ /Wx./) {
4336 if (ERROR("SPACING",
4337 "space prohibited before that '$op' $at\n" . $hereptr)) {
4342 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4343 if (ERROR("SPACING",
4344 "space required after that '$op' $at\n" . $hereptr)) {
4350 if ($rtrim_before || $space_after) {
4351 if ($rtrim_before) {
4352 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4354 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4361 # '*' as part of a type definition -- reported already.
4362 } elsif ($opv eq '*_') {
4363 #warn "'*' is part of type\n";
4365 # unary operators should have a space before and
4366 # none after. May be left adjacent to another
4367 # unary operator, or a cast
4368 } elsif ($op eq '!' || $op eq '~' ||
4369 $opv eq '*U' || $opv eq '-U' ||
4370 $opv eq '&U' || $opv eq '&&U') {
4371 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4372 if (ERROR("SPACING",
4373 "space required before that '$op' $at\n" . $hereptr)) {
4374 if ($n != $last_after + 2) {
4375 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4380 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4381 # A unary '*' may be const
4383 } elsif ($ctx =~ /.xW/) {
4384 if (ERROR("SPACING",
4385 "space prohibited after that '$op' $at\n" . $hereptr)) {
4386 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4387 if (defined $fix_elements[$n + 2]) {
4388 $fix_elements[$n + 2] =~ s/^\s+//;
4394 # unary ++ and unary -- are allowed no space on one side.
4395 } elsif ($op eq '++' or $op eq '--') {
4396 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4397 if (ERROR("SPACING",
4398 "space required one side of that '$op' $at\n" . $hereptr)) {
4399 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4403 if ($ctx =~ /Wx[BE]/ ||
4404 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4405 if (ERROR("SPACING",
4406 "space prohibited before that '$op' $at\n" . $hereptr)) {
4407 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4411 if ($ctx =~ /ExW/) {
4412 if (ERROR("SPACING",
4413 "space prohibited after that '$op' $at\n" . $hereptr)) {
4414 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4415 if (defined $fix_elements[$n + 2]) {
4416 $fix_elements[$n + 2] =~ s/^\s+//;
4422 # << and >> may either have or not have spaces both sides
4423 } elsif ($op eq '<<' or $op eq '>>' or
4424 $op eq '&' or $op eq '^' or $op eq '|' or
4425 $op eq '+' or $op eq '-' or
4426 $op eq '*' or $op eq '/' or
4430 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4432 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4433 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4434 $fix_elements[$n + 2] =~ s/^\s+//;
4437 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4439 "space preferred before that '$op' $at\n" . $hereptr)) {
4440 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4444 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4445 if (ERROR("SPACING",
4446 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4447 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4448 if (defined $fix_elements[$n + 2]) {
4449 $fix_elements[$n + 2] =~ s/^\s+//;
4455 # A colon needs no spaces before when it is
4456 # terminating a case value or a label.
4457 } elsif ($opv eq ':C' || $opv eq ':L') {
4458 if ($ctx =~ /Wx./) {
4459 if (ERROR("SPACING",
4460 "space prohibited before that '$op' $at\n" . $hereptr)) {
4461 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4466 # All the others need spaces both sides.
4467 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4470 # Ignore email addresses <foo@bar>
4472 $cc =~ /^\S+\@\S+>/) ||
4474 $ca =~ /<\S+\@\S+$/))
4479 # for asm volatile statements
4480 # ignore a colon with another
4481 # colon immediately before or after
4483 ($ca =~ /:$/ || $cc =~ /^:/)) {
4487 # messages are ERROR, but ?: are CHK
4489 my $msg_level = \&ERROR;
4490 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4492 if (&{$msg_level}("SPACING",
4493 "spaces required around that '$op' $at\n" . $hereptr)) {
4494 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4495 if (defined $fix_elements[$n + 2]) {
4496 $fix_elements[$n + 2] =~ s/^\s+//;
4502 $off += length($elements[$n + 1]);
4504 ## print("n: <$n> GOOD: <$good>\n");
4506 $fixed_line = $fixed_line . $good;
4509 if (($#elements % 2) == 0) {
4510 $fixed_line = $fixed_line . $fix_elements[$#elements];
4513 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4514 $fixed[$fixlinenr] = $fixed_line;
4520 # check for whitespace before a non-naked semicolon
4521 if ($line =~ /^\+.*\S\s+;\s*$/) {
4523 "space prohibited before semicolon\n" . $herecurr) &&
4525 1 while $fixed[$fixlinenr] =~
4526 s/^(\+.*\S)\s+;/$1;/;
4530 # check for multiple assignments
4531 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4532 CHK("MULTIPLE_ASSIGNMENTS",
4533 "multiple assignments should be avoided\n" . $herecurr);
4536 ## # check for multiple declarations, allowing for a function declaration
4538 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4539 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4541 ## # Remove any bracketed sections to ensure we do not
4542 ## # falsly report the parameters of functions.
4544 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4546 ## if ($ln =~ /,/) {
4547 ## WARN("MULTIPLE_DECLARATION",
4548 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4552 #need space before brace following if, while, etc
4553 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4554 $line =~ /\b(?:else|do)\{/) {
4555 if (ERROR("SPACING",
4556 "space required before the open brace '{'\n" . $herecurr) &&
4558 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4562 ## # check for blank lines before declarations
4563 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4564 ## $prevrawline =~ /^.\s*$/) {
4566 ## "No blank lines before declarations\n" . $hereprev);
4570 # closing brace should have a space following it when it has anything
4572 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4573 if (ERROR("SPACING",
4574 "space required after that close brace '}'\n" . $herecurr) &&
4576 $fixed[$fixlinenr] =~
4577 s/}((?!(?:,|;|\)))\S)/} $1/;
4581 # check spacing on square brackets
4582 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4583 if (ERROR("SPACING",
4584 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4586 $fixed[$fixlinenr] =~
4590 if ($line =~ /\s\]/) {
4591 if (ERROR("SPACING",
4592 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4594 $fixed[$fixlinenr] =~
4599 # check spacing on parentheses
4600 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4601 $line !~ /for\s*\(\s+;/) {
4602 if (ERROR("SPACING",
4603 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4605 $fixed[$fixlinenr] =~
4609 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4610 $line !~ /for\s*\(.*;\s+\)/ &&
4611 $line !~ /:\s+\)/) {
4612 if (ERROR("SPACING",
4613 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4615 $fixed[$fixlinenr] =~
4620 # check unnecessary parentheses around addressof/dereference single $Lvals
4621 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4623 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4625 if (CHK("UNNECESSARY_PARENTHESES",
4626 "Unnecessary parentheses around $var\n" . $herecurr) &&
4628 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4632 # check for unnecessary parentheses around function pointer uses
4633 # ie: (foo->bar)(); should be foo->bar();
4634 # but not "if (foo->bar) (" to avoid some false positives
4635 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4637 if (CHK("UNNECESSARY_PARENTHESES",
4638 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4640 my $var2 = deparenthesize($var);
4642 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4646 # check for unnecessary parentheses around comparisons in if uses
4647 # when !drivers/staging or command-line uses --strict
4648 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4649 $perl_version_ok && defined($stat) &&
4650 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4652 my $test = substr($2, 1, -1);
4654 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4656 # avoid parentheses around potential macro args
4657 next if ($match =~ /^\s*\w+\s*$/);
4658 if (!defined($herectx)) {
4659 $herectx = $here . "\n";
4660 my $cnt = statement_rawlines($if_stat);
4661 for (my $n = 0; $n < $cnt; $n++) {
4662 my $rl = raw_line($linenr, $n);
4663 $herectx .= $rl . "\n";
4664 last if $rl =~ /^[ \+].*\{/;
4667 CHK("UNNECESSARY_PARENTHESES",
4668 "Unnecessary parentheses around '$match'\n" . $herectx);
4672 #goto labels aren't indented, allow a single space however
4673 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4674 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4675 if (WARN("INDENTED_LABEL",
4676 "labels should not be indented\n" . $herecurr) &&
4678 $fixed[$fixlinenr] =~
4683 # return is not a function
4684 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4686 if ($perl_version_ok &&
4687 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4689 $value = deparenthesize($value);
4690 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4691 ERROR("RETURN_PARENTHESES",
4692 "return is not a function, parentheses are not required\n" . $herecurr);
4694 } elsif ($spacing !~ /\s+/) {
4696 "space required before the open parenthesis '('\n" . $herecurr);
4700 # unnecessary return in a void function
4701 # at end-of-function, with the previous line a single leading tab, then return;
4702 # and the line before that not a goto label target like "out:"
4703 if ($sline =~ /^[ \+]}\s*$/ &&
4704 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4706 $lines[$linenr - 3] =~ /^[ +]/ &&
4707 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4709 "void function return statements are not generally useful\n" . $hereprev);
4712 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4713 if ($perl_version_ok &&
4714 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4715 my $openparens = $1;
4716 my $count = $openparens =~ tr@\(@\(@;
4718 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4719 my $comp = $4; #Not $1 because of $LvalOrFunc
4720 $msg = " - maybe == should be = ?" if ($comp eq "==");
4721 WARN("UNNECESSARY_PARENTHESES",
4722 "Unnecessary parentheses$msg\n" . $herecurr);
4726 # comparisons with a constant or upper case identifier on the left
4727 # avoid cases like "foo + BAR < baz"
4728 # only fix matches surrounded by parentheses to avoid incorrect
4729 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4730 if ($perl_version_ok &&
4731 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4736 my $newcomp = $comp;
4737 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4738 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4739 WARN("CONSTANT_COMPARISON",
4740 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4744 } elsif ($comp eq "<=") {
4746 } elsif ($comp eq ">") {
4748 } elsif ($comp eq ">=") {
4751 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4755 # Return of what appears to be an errno should normally be negative
4756 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4758 if ($name ne 'EOF' && $name ne 'ERROR') {
4759 WARN("USE_NEGATIVE_ERRNO",
4760 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4764 # Need a space before open parenthesis after if, while etc
4765 if ($line =~ /\b(if|while|for|switch)\(/) {
4766 if (ERROR("SPACING",
4767 "space required before the open parenthesis '('\n" . $herecurr) &&
4769 $fixed[$fixlinenr] =~
4770 s/\b(if|while|for|switch)\(/$1 \(/;
4774 # Check for illegal assignment in if conditional -- and check for trailing
4775 # statements after the conditional.
4776 if ($line =~ /do\s*(?!{)/) {
4777 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4778 ctx_statement_block($linenr, $realcnt, 0)
4779 if (!defined $stat);
4780 my ($stat_next) = ctx_statement_block($line_nr_next,
4781 $remain_next, $off_next);
4782 $stat_next =~ s/\n./\n /g;
4783 ##print "stat<$stat> stat_next<$stat_next>\n";
4785 if ($stat_next =~ /^\s*while\b/) {
4786 # If the statement carries leading newlines,
4787 # then count those as offsets.
4789 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4791 statement_rawlines($whitespace) - 1;
4793 $suppress_whiletrailers{$line_nr_next +
4797 if (!defined $suppress_whiletrailers{$linenr} &&
4798 defined($stat) && defined($cond) &&
4799 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4800 my ($s, $c) = ($stat, $cond);
4802 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4803 ERROR("ASSIGN_IN_IF",
4804 "do not use assignment in if condition\n" . $herecurr);
4807 # Find out what is on the end of the line after the
4809 substr($s, 0, length($c), '');
4811 $s =~ s/$;//g; # Remove any comments
4812 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4813 $c !~ /}\s*while\s*/)
4815 # Find out how long the conditional actually is.
4816 my @newlines = ($c =~ /\n/gs);
4817 my $cond_lines = 1 + $#newlines;
4820 $stat_real = raw_line($linenr, $cond_lines)
4821 . "\n" if ($cond_lines);
4822 if (defined($stat_real) && $cond_lines > 1) {
4823 $stat_real = "[...]\n$stat_real";
4826 ERROR("TRAILING_STATEMENTS",
4827 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4831 # Check for bitwise tests written as boolean
4843 WARN("HEXADECIMAL_BOOLEAN_TEST",
4844 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4847 # if and else should not have general statements after it
4848 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4850 $s =~ s/$;//g; # Remove any comments
4851 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4852 ERROR("TRAILING_STATEMENTS",
4853 "trailing statements should be on next line\n" . $herecurr);
4856 # if should not continue a brace
4857 if ($line =~ /}\s*if\b/) {
4858 ERROR("TRAILING_STATEMENTS",
4859 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4862 # case and default should not have general statements after them
4863 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4865 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4869 ERROR("TRAILING_STATEMENTS",
4870 "trailing statements should be on next line\n" . $herecurr);
4873 # Check for }<nl>else {, these must be at the same
4874 # indent level to be relevant to each other.
4875 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4876 $previndent == $indent) {
4877 if (ERROR("ELSE_AFTER_BRACE",
4878 "else should follow close brace '}'\n" . $hereprev) &&
4879 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4880 fix_delete_line($fixlinenr - 1, $prevrawline);
4881 fix_delete_line($fixlinenr, $rawline);
4882 my $fixedline = $prevrawline;
4883 $fixedline =~ s/}\s*$//;
4884 if ($fixedline !~ /^\+\s*$/) {
4885 fix_insert_line($fixlinenr, $fixedline);
4887 $fixedline = $rawline;
4888 $fixedline =~ s/^(.\s*)else/$1} else/;
4889 fix_insert_line($fixlinenr, $fixedline);
4893 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4894 $previndent == $indent) {
4895 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4897 # Find out what is on the end of the line after the
4899 substr($s, 0, length($c), '');
4902 if ($s =~ /^\s*;/) {
4903 if (ERROR("WHILE_AFTER_BRACE",
4904 "while should follow close brace '}'\n" . $hereprev) &&
4905 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4906 fix_delete_line($fixlinenr - 1, $prevrawline);
4907 fix_delete_line($fixlinenr, $rawline);
4908 my $fixedline = $prevrawline;
4909 my $trailing = $rawline;
4910 $trailing =~ s/^\+//;
4911 $trailing = trim($trailing);
4912 $fixedline =~ s/}\s*$/} $trailing/;
4913 fix_insert_line($fixlinenr, $fixedline);
4918 #Specific variable tests
4919 while ($line =~ m{($Constant|$Lval)}g) {
4922 #gcc binary extension
4923 if ($var =~ /^$Binary$/) {
4924 if (WARN("GCC_BINARY_CONSTANT",
4925 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4927 my $hexval = sprintf("0x%x", oct($var));
4928 $fixed[$fixlinenr] =~
4929 s/\b$var\b/$hexval/;
4934 if ($var !~ /^$Constant$/ &&
4935 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4936 #Ignore Page<foo> variants
4937 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4938 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4939 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4940 #Ignore some three character SI units explicitly, like MiB and KHz
4941 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4942 while ($var =~ m{($Ident)}g) {
4944 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4946 seed_camelcase_includes();
4947 if (!$file && !$camelcase_file_seeded) {
4948 seed_camelcase_file($realfile);
4949 $camelcase_file_seeded = 1;
4952 if (!defined $camelcase{$word}) {
4953 $camelcase{$word} = 1;
4955 "Avoid CamelCase: <$word>\n" . $herecurr);
4961 #no spaces allowed after \ in define
4962 if ($line =~ /\#\s*define.*\\\s+$/) {
4963 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4964 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4966 $fixed[$fixlinenr] =~ s/\s+$//;
4970 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4971 # itself <asm/foo.h> (uses RAW line)
4972 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4974 my $checkfile = "include/linux/$file";
4975 if (-f "$root/$checkfile" &&
4976 $realfile ne $checkfile &&
4977 $1 !~ /$allowed_asm_includes/)
4979 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4980 if ($asminclude > 0) {
4981 if ($realfile =~ m{^arch/}) {
4982 CHK("ARCH_INCLUDE_LINUX",
4983 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4985 WARN("INCLUDE_LINUX",
4986 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4992 # multi-statement macros should be enclosed in a do while loop, grab the
4993 # first statement and ensure its the whole macro if its not enclosed
4994 # in a known good container
4995 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4996 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4999 my ($off, $dstat, $dcond, $rest);
5001 my $has_flow_statement = 0;
5002 my $has_arg_concat = 0;
5003 ($dstat, $dcond, $ln, $cnt, $off) =
5004 ctx_statement_block($linenr, $realcnt, 0);
5006 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5007 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5009 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5010 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5012 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5013 my $define_args = $1;
5014 my $define_stmt = $dstat;
5017 if (defined $define_args && $define_args ne "") {
5018 $define_args = substr($define_args, 1, length($define_args) - 2);
5019 $define_args =~ s/\s*//g;
5020 $define_args =~ s/\\\+?//g;
5021 @def_args = split(",", $define_args);
5025 $dstat =~ s/\\\n.//g;
5026 $dstat =~ s/^\s*//s;
5027 $dstat =~ s/\s*$//s;
5029 # Flatten any parentheses and braces
5030 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5031 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5032 $dstat =~ s/.\[[^\[\]]*\]/1/)
5036 # Flatten any obvious string concatentation.
5037 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5038 $dstat =~ s/$Ident\s*($String)/$1/)
5042 # Make asm volatile uses seem like a generic function
5043 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5045 my $exceptions = qr{
5058 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5061 my $stmt_cnt = statement_rawlines($ctx);
5062 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5065 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5066 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5067 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5068 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5069 $dstat !~ /$exceptions/ &&
5070 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5071 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5072 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5073 $dstat !~ /^for\s*$Constant$/ && # for (...)
5074 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5075 $dstat !~ /^do\s*{/ && # do {...
5076 $dstat !~ /^\(\{/ && # ({...
5077 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5079 if ($dstat =~ /^\s*if\b/) {
5080 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5081 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5082 } elsif ($dstat =~ /;/) {
5083 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5084 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5086 ERROR("COMPLEX_MACRO",
5087 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5092 # Make $define_stmt single line, comment-free, etc
5093 my @stmt_array = split('\n', $define_stmt);
5096 foreach my $l (@stmt_array) {
5101 } elsif ($l =~ /^[\+ ]/) {
5102 $define_stmt .= substr($l, 1);
5105 $define_stmt =~ s/$;//g;
5106 $define_stmt =~ s/\s+/ /g;
5107 $define_stmt = trim($define_stmt);
5109 # check if any macro arguments are reused (ignore '...' and 'type')
5110 foreach my $arg (@def_args) {
5111 next if ($arg =~ /\.\.\./);
5112 next if ($arg =~ /^type$/i);
5113 my $tmp_stmt = $define_stmt;
5114 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5115 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5116 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5117 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5119 CHK("MACRO_ARG_REUSE",
5120 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5122 # check if any macro arguments may have other precedence issues
5123 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5124 ((defined($1) && $1 ne ',') ||
5125 (defined($2) && $2 ne ','))) {
5126 CHK("MACRO_ARG_PRECEDENCE",
5127 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5131 # check for macros with flow control, but without ## concatenation
5132 # ## concatenation is commonly a macro that defines a function so ignore those
5133 if ($has_flow_statement && !$has_arg_concat) {
5134 my $cnt = statement_rawlines($ctx);
5135 my $herectx = get_stat_here($linenr, $cnt, $here);
5137 WARN("MACRO_WITH_FLOW_CONTROL",
5138 "Macros with flow control statements should be avoided\n" . "$herectx");
5141 # check for line continuations outside of #defines, preprocessor #, and asm
5144 if ($prevline !~ /^..*\\$/ &&
5145 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5146 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5147 $line =~ /^\+.*\\$/) {
5148 WARN("LINE_CONTINUATIONS",
5149 "Avoid unnecessary line continuations\n" . $herecurr);
5153 # do {} while (0) macro tests:
5154 # single-statement macros do not need to be enclosed in do while (0) loop,
5155 # macro should not end with a semicolon
5156 if ($perl_version_ok &&
5157 $realfile !~ m@/vmlinux.lds.h$@ &&
5158 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5161 my ($off, $dstat, $dcond, $rest);
5163 ($dstat, $dcond, $ln, $cnt, $off) =
5164 ctx_statement_block($linenr, $realcnt, 0);
5167 $dstat =~ s/\\\n.//g;
5170 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5175 my $cnt = statement_rawlines($ctx);
5176 my $herectx = get_stat_here($linenr, $cnt, $here);
5178 if (($stmts =~ tr/;/;/) == 1 &&
5179 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5180 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5181 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5183 if (defined $semis && $semis ne "") {
5184 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5185 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5187 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5189 my $cnt = statement_rawlines($ctx);
5190 my $herectx = get_stat_here($linenr, $cnt, $here);
5192 WARN("TRAILING_SEMICOLON",
5193 "macros should not use a trailing semicolon\n" . "$herectx");
5197 # check for redundant bracing round if etc
5198 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5199 my ($level, $endln, @chunks) =
5200 ctx_statement_full($linenr, $realcnt, 1);
5201 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5202 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5203 if ($#chunks > 0 && $level == 0) {
5207 my $herectx = $here . "\n";
5208 my $ln = $linenr - 1;
5209 for my $chunk (@chunks) {
5210 my ($cond, $block) = @{$chunk};
5212 # If the condition carries leading newlines, then count those as offsets.
5213 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5214 my $offset = statement_rawlines($whitespace) - 1;
5216 $allowed[$allow] = 0;
5217 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5219 # We have looked at and allowed this specific line.
5220 $suppress_ifbraces{$ln + $offset} = 1;
5222 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5223 $ln += statement_rawlines($block) - 1;
5225 substr($block, 0, length($cond), '');
5227 $seen++ if ($block =~ /^\s*{/);
5229 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5230 if (statement_lines($cond) > 1) {
5231 #print "APW: ALLOWED: cond<$cond>\n";
5232 $allowed[$allow] = 1;
5234 if ($block =~/\b(?:if|for|while)\b/) {
5235 #print "APW: ALLOWED: block<$block>\n";
5236 $allowed[$allow] = 1;
5238 if (statement_block_size($block) > 1) {
5239 #print "APW: ALLOWED: lines block<$block>\n";
5240 $allowed[$allow] = 1;
5245 my $sum_allowed = 0;
5246 foreach (@allowed) {
5249 if ($sum_allowed == 0) {
5251 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5252 } elsif ($sum_allowed != $allow &&
5255 "braces {} should be used on all arms of this statement\n" . $herectx);
5260 if (!defined $suppress_ifbraces{$linenr - 1} &&
5261 $line =~ /\b(if|while|for|else)\b/) {
5264 # Check the pre-context.
5265 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5266 #print "APW: ALLOWED: pre<$1>\n";
5270 my ($level, $endln, @chunks) =
5271 ctx_statement_full($linenr, $realcnt, $-[0]);
5273 # Check the condition.
5274 my ($cond, $block) = @{$chunks[0]};
5275 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5276 if (defined $cond) {
5277 substr($block, 0, length($cond), '');
5279 if (statement_lines($cond) > 1) {
5280 #print "APW: ALLOWED: cond<$cond>\n";
5283 if ($block =~/\b(?:if|for|while)\b/) {
5284 #print "APW: ALLOWED: block<$block>\n";
5287 if (statement_block_size($block) > 1) {
5288 #print "APW: ALLOWED: lines block<$block>\n";
5291 # Check the post-context.
5292 if (defined $chunks[1]) {
5293 my ($cond, $block) = @{$chunks[1]};
5294 if (defined $cond) {
5295 substr($block, 0, length($cond), '');
5297 if ($block =~ /^\s*\{/) {
5298 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5302 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5303 my $cnt = statement_rawlines($block);
5304 my $herectx = get_stat_here($linenr, $cnt, $here);
5307 "braces {} are not necessary for single statement blocks\n" . $herectx);
5311 # check for single line unbalanced braces
5312 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5313 $sline =~ /^.\s*else\s*\{\s*$/) {
5314 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5317 # check for unnecessary blank lines around braces
5318 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5320 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5321 $fix && $prevrawline =~ /^\+/) {
5322 fix_delete_line($fixlinenr - 1, $prevrawline);
5325 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5327 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5329 fix_delete_line($fixlinenr, $rawline);
5333 # no volatiles please
5334 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5335 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5337 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5340 # Check for user-visible strings broken across lines, which breaks the ability
5341 # to grep for the string. Make exceptions when the previous string ends in a
5342 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5343 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5344 if ($line =~ /^\+\s*$String/ &&
5345 $prevline =~ /"\s*$/ &&
5346 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5347 if (WARN("SPLIT_STRING",
5348 "quoted string split across lines\n" . $hereprev) &&
5350 $prevrawline =~ /^\+.*"\s*$/ &&
5351 $last_coalesced_string_linenr != $linenr - 1) {
5352 my $extracted_string = get_quoted_string($line, $rawline);
5353 my $comma_close = "";
5354 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5358 fix_delete_line($fixlinenr - 1, $prevrawline);
5359 fix_delete_line($fixlinenr, $rawline);
5360 my $fixedline = $prevrawline;
5361 $fixedline =~ s/"\s*$//;
5362 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5363 fix_insert_line($fixlinenr - 1, $fixedline);
5364 $fixedline = $rawline;
5365 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5366 if ($fixedline !~ /\+\s*$/) {
5367 fix_insert_line($fixlinenr, $fixedline);
5369 $last_coalesced_string_linenr = $linenr;
5373 # check for missing a space in a string concatenation
5374 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5375 WARN('MISSING_SPACE',
5376 "break quoted strings at a space character\n" . $hereprev);
5379 # check for an embedded function name in a string when the function is known
5380 # This does not work very well for -f --file checking as it depends on patch
5381 # context providing the function name or a single line form for in-file
5382 # function declarations
5383 if ($line =~ /^\+.*$String/ &&
5384 defined($context_function) &&
5385 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5386 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5387 WARN("EMBEDDED_FUNCTION_NAME",
5388 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5391 # check for spaces before a quoted newline
5392 if ($rawline =~ /^.*\".*\s\\n/) {
5393 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5394 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5396 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5401 # concatenated string without spaces between elements
5402 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5403 if (CHK("CONCATENATED_STRING",
5404 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5406 while ($line =~ /($String)/g) {
5407 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5408 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5409 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5414 # uncoalesced string fragments
5415 if ($line =~ /$String\s*"/) {
5416 if (WARN("STRING_FRAGMENTS",
5417 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5419 while ($line =~ /($String)(?=\s*")/g) {
5420 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5421 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5426 # check for non-standard and hex prefixed decimal printf formats
5427 my $show_L = 1; #don't show the same defect twice
5429 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5430 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5431 $string =~ s/%%/__/g;
5433 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5435 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5439 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5441 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5444 # check for 0x<decimal>
5445 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5446 ERROR("PRINTF_0XDECIMAL",
5447 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5451 # check for line continuations in quoted strings with odd counts of "
5452 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5453 WARN("LINE_CONTINUATIONS",
5454 "Avoid line continuations in quoted strings\n" . $herecurr);
5458 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5460 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5464 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5466 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5469 # check for needless "if (<foo>) fn(<foo>)" uses
5470 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5471 my $tested = quotemeta($1);
5472 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5473 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5475 if (WARN('NEEDLESS_IF',
5476 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5479 my $leading_tabs = "";
5480 my $new_leading_tabs = "";
5481 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5486 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5487 $new_leading_tabs = $1;
5488 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5495 fix_delete_line($fixlinenr - 1, $prevrawline);
5496 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5502 # check for unnecessary "Out of Memory" messages
5503 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5504 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5505 (defined $1 || defined $3) &&
5508 my $testline = $lines[$linenr - 3];
5510 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5511 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5513 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)/) {
5515 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5519 # check for logging functions with KERN_<LEVEL>
5520 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5521 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5523 if (WARN("UNNECESSARY_KERN_LEVEL",
5524 "Possible unnecessary $level\n" . $herecurr) &&
5526 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5530 # check for logging continuations
5531 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5532 WARN("LOGGING_CONTINUATION",
5533 "Avoid logging continuation uses where feasible\n" . $herecurr);
5536 # check for mask then right shift without a parentheses
5537 if ($perl_version_ok &&
5538 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5539 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5540 WARN("MASK_THEN_SHIFT",
5541 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5544 # check for pointer comparisons to NULL
5545 if ($perl_version_ok) {
5546 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5549 $equal = "" if ($4 eq "!=");
5550 if (CHK("COMPARISON_TO_NULL",
5551 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5553 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5558 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5559 if ($line =~ /(\b$InitAttribute\b)/) {
5561 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5564 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5565 ERROR("MISPLACED_INIT",
5566 "$attr should be placed after $var\n" . $herecurr)) ||
5567 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5568 WARN("MISPLACED_INIT",
5569 "$attr should be placed after $var\n" . $herecurr))) &&
5571 $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;
5576 # check for $InitAttributeData (ie: __initdata) with const
5577 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5579 $attr =~ /($InitAttributePrefix)(.*)/;
5580 my $attr_prefix = $1;
5582 if (ERROR("INIT_ATTRIBUTE",
5583 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5585 $fixed[$fixlinenr] =~
5586 s/$InitAttributeData/${attr_prefix}initconst/;
5590 # check for $InitAttributeConst (ie: __initconst) without const
5591 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5593 if (ERROR("INIT_ATTRIBUTE",
5594 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5596 my $lead = $fixed[$fixlinenr] =~
5597 /(^\+\s*(?:static\s+))/;
5599 $lead = "$lead " if ($lead !~ /^\+$/);
5600 $lead = "${lead}const ";
5601 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5605 # check for __read_mostly with const non-pointer (should just be const)
5606 if ($line =~ /\b__read_mostly\b/ &&
5607 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5608 if (ERROR("CONST_READ_MOSTLY",
5609 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5611 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5615 # don't use __constant_<foo> functions outside of include/uapi/
5616 if ($realfile !~ m@^include/uapi/@ &&
5617 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5618 my $constant_func = $1;
5619 my $func = $constant_func;
5620 $func =~ s/^__constant_//;
5621 if (WARN("CONSTANT_CONVERSION",
5622 "$constant_func should be $func\n" . $herecurr) &&
5624 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5628 # prefer usleep_range over udelay
5629 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5631 # ignore udelay's < 10, however
5632 if (! ($delay < 10) ) {
5634 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5636 if ($delay > 2000) {
5638 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5642 # warn about unexpectedly long msleep's
5643 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5646 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5650 # check for comparisons of jiffies
5651 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5652 WARN("JIFFIES_COMPARISON",
5653 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5656 # check for comparisons of get_jiffies_64()
5657 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5658 WARN("JIFFIES_COMPARISON",
5659 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5662 # warn about #ifdefs in C files
5663 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5664 # print "#ifdef in C files should be avoided\n";
5665 # print "$herecurr";
5669 # warn about spacing in #ifdefs
5670 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5671 if (ERROR("SPACING",
5672 "exactly one space required after that #$1\n" . $herecurr) &&
5674 $fixed[$fixlinenr] =~
5675 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5680 # check for spinlock_t definitions without a comment.
5681 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5682 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5684 if (!ctx_has_comment($first_line, $linenr)) {
5685 CHK("UNCOMMENTED_DEFINITION",
5686 "$1 definition without comment\n" . $herecurr);
5689 # check for memory barriers without a comment.
5695 read_barrier_depends
5697 my $barrier_stems = qr{
5705 my $all_barriers = qr{
5707 smp_(?:$barrier_stems)|
5708 virt_(?:$barrier_stems)
5711 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5712 if (!ctx_has_comment($first_line, $linenr)) {
5713 WARN("MEMORY_BARRIER",
5714 "memory barrier without comment\n" . $herecurr);
5718 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5720 if ($realfile !~ m@^include/asm-generic/@ &&
5721 $realfile !~ m@/barrier\.h$@ &&
5722 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5723 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5724 WARN("MEMORY_BARRIER",
5725 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5728 # check for waitqueue_active without a comment.
5729 if ($line =~ /\bwaitqueue_active\s*\(/) {
5730 if (!ctx_has_comment($first_line, $linenr)) {
5731 WARN("WAITQUEUE_ACTIVE",
5732 "waitqueue_active without comment\n" . $herecurr);
5736 # check for smp_read_barrier_depends and read_barrier_depends
5737 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5738 WARN("READ_BARRIER_DEPENDS",
5739 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5742 # check of hardware specific defines
5743 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5745 "architecture specific defines should be avoided\n" . $herecurr);
5748 # check that the storage class is not after a type
5749 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5750 WARN("STORAGE_CLASS",
5751 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5753 # Check that the storage class is at the beginning of a declaration
5754 if ($line =~ /\b$Storage\b/ &&
5755 $line !~ /^.\s*$Storage/ &&
5756 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5757 $1 !~ /[\,\)]\s*$/) {
5758 WARN("STORAGE_CLASS",
5759 "storage class should be at the beginning of the declaration\n" . $herecurr);
5762 # check the location of the inline attribute, that it is between
5763 # storage class and type.
5764 if ($line =~ /\b$Type\s+$Inline\b/ ||
5765 $line =~ /\b$Inline\s+$Storage\b/) {
5766 ERROR("INLINE_LOCATION",
5767 "inline keyword should sit between storage class and type\n" . $herecurr);
5770 # Check for __inline__ and __inline, prefer inline
5771 if ($realfile !~ m@\binclude/uapi/@ &&
5772 $line =~ /\b(__inline__|__inline)\b/) {
5774 "plain inline is preferred over $1\n" . $herecurr) &&
5776 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5781 # Check for __attribute__ packed, prefer __packed
5782 if ($realfile !~ m@\binclude/uapi/@ &&
5783 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5784 WARN("PREFER_PACKED",
5785 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5788 # Check for __attribute__ aligned, prefer __aligned
5789 if ($realfile !~ m@\binclude/uapi/@ &&
5790 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5791 WARN("PREFER_ALIGNED",
5792 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5795 # Check for __attribute__ format(printf, prefer __printf
5796 if ($realfile !~ m@\binclude/uapi/@ &&
5797 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5798 if (WARN("PREFER_PRINTF",
5799 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5801 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5806 # Check for __attribute__ format(scanf, prefer __scanf
5807 if ($realfile !~ m@\binclude/uapi/@ &&
5808 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5809 if (WARN("PREFER_SCANF",
5810 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5812 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5816 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5817 if ($perl_version_ok &&
5818 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5819 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5820 $line =~ /\b__weak\b/)) {
5821 ERROR("WEAK_DECLARATION",
5822 "Using weak declarations can have unintended link defects\n" . $herecurr);
5825 # check for c99 types like uint8_t used outside of uapi/ and tools/
5826 if ($realfile !~ m@\binclude/uapi/@ &&
5827 $realfile !~ m@\btools/@ &&
5828 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5830 if ($type =~ /\b($typeC99Typedefs)\b/) {
5832 my $kernel_type = 'u';
5833 $kernel_type = 's' if ($type =~ /^_*[si]/);
5836 if (CHK("PREFER_KERNEL_TYPES",
5837 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5839 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5844 # check for cast of C90 native int or longer types constants
5845 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5848 if (WARN("TYPECAST_INT_CONSTANT",
5849 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5852 my $newconst = $const;
5853 $newconst =~ s/${Int_type}$//;
5854 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5855 if ($cast =~ /\blong\s+long\b/) {
5857 } elsif ($cast =~ /\blong\b/) {
5860 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5864 # check for sizeof(&)
5865 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5866 WARN("SIZEOF_ADDRESS",
5867 "sizeof(& should be avoided\n" . $herecurr);
5870 # check for sizeof without parenthesis
5871 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5872 if (WARN("SIZEOF_PARENTHESIS",
5873 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5875 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5879 # check for struct spinlock declarations
5880 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5881 WARN("USE_SPINLOCK_T",
5882 "struct spinlock should be spinlock_t\n" . $herecurr);
5885 # check for seq_printf uses that could be seq_puts
5886 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5887 my $fmt = get_quoted_string($line, $rawline);
5890 if (WARN("PREFER_SEQ_PUTS",
5891 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5893 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5898 # check for vsprintf extension %p<foo> misuses
5899 if ($perl_version_ok &&
5901 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5902 $1 !~ /^_*volatile_*$/) {
5905 my $lc = $stat =~ tr@\n@@;
5906 $lc = $lc + $linenr;
5907 for (my $count = $linenr; $count <= $lc; $count++) {
5910 my $bad_specifier = "";
5911 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5914 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5917 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5918 $bad_specifier = $specifier;
5921 if ($extension eq "x" && !defined($stat_real)) {
5922 if (!defined($stat_real)) {
5923 $stat_real = get_stat_real($linenr, $lc);
5925 WARN("VSPRINTF_SPECIFIER_PX",
5926 "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");
5929 if ($bad_specifier ne "") {
5930 my $stat_real = get_stat_real($linenr, $lc);
5931 my $ext_type = "Invalid";
5933 if ($bad_specifier =~ /p[Ff]/) {
5934 $ext_type = "Deprecated";
5935 $use = " - use %pS instead";
5936 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5939 WARN("VSPRINTF_POINTER_EXTENSION",
5940 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5945 # Check for misused memsets
5946 if ($perl_version_ok &&
5948 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5954 if ($ms_size =~ /^(0x|)0$/i) {
5956 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5957 } elsif ($ms_size =~ /^(0x|)1$/i) {
5959 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5963 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5964 # if ($perl_version_ok &&
5966 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5967 # if (WARN("PREFER_ETHER_ADDR_COPY",
5968 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5970 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5974 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5975 # if ($perl_version_ok &&
5977 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5978 # WARN("PREFER_ETHER_ADDR_EQUAL",
5979 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5982 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5983 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5984 # if ($perl_version_ok &&
5986 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5990 # if ($ms_val =~ /^(?:0x|)0+$/i) {
5991 # if (WARN("PREFER_ETH_ZERO_ADDR",
5992 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5994 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5996 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5997 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
5998 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6000 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6005 # typecasts on min/max could be min_t/max_t
6006 if ($perl_version_ok &&
6008 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6009 if (defined $2 || defined $7) {
6011 my $cast1 = deparenthesize($2);
6013 my $cast2 = deparenthesize($7);
6017 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6018 $cast = "$cast1 or $cast2";
6019 } elsif ($cast1 ne "") {
6025 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6029 # check usleep_range arguments
6030 if ($perl_version_ok &&
6032 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6036 WARN("USLEEP_RANGE",
6037 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6038 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6040 WARN("USLEEP_RANGE",
6041 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6045 # check for naked sscanf
6046 if ($perl_version_ok &&
6048 $line =~ /\bsscanf\b/ &&
6049 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6050 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6051 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6052 my $lc = $stat =~ tr@\n@@;
6053 $lc = $lc + $linenr;
6054 my $stat_real = get_stat_real($linenr, $lc);
6055 WARN("NAKED_SSCANF",
6056 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6059 # check for simple sscanf that should be kstrto<foo>
6060 if ($perl_version_ok &&
6062 $line =~ /\bsscanf\b/) {
6063 my $lc = $stat =~ tr@\n@@;
6064 $lc = $lc + $linenr;
6065 my $stat_real = get_stat_real($linenr, $lc);
6066 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6068 my $count = $format =~ tr@%@%@;
6070 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6071 WARN("SSCANF_TO_KSTRTO",
6072 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6077 # check for new externs in .h files.
6078 if ($realfile =~ /\.h$/ &&
6079 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6080 if (CHK("AVOID_EXTERNS",
6081 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6083 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6087 # check for new externs in .c files.
6088 if ($realfile =~ /\.c$/ && defined $stat &&
6089 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6091 my $function_name = $1;
6092 my $paren_space = $2;
6095 if (defined $cond) {
6096 substr($s, 0, length($cond), '');
6098 if ($s =~ /^\s*;/ &&
6099 $function_name ne 'uninitialized_var')
6101 WARN("AVOID_EXTERNS",
6102 "externs should be avoided in .c files\n" . $herecurr);
6105 if ($paren_space =~ /\n/) {
6106 WARN("FUNCTION_ARGUMENTS",
6107 "arguments for function declarations should follow identifier\n" . $herecurr);
6110 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6111 $stat =~ /^.\s*extern\s+/)
6113 WARN("AVOID_EXTERNS",
6114 "externs should be avoided in .c files\n" . $herecurr);
6117 # check for function declarations that have arguments without identifier names
6118 if (defined $stat &&
6119 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6121 my $args = trim($1);
6122 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6124 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6125 WARN("FUNCTION_ARGUMENTS",
6126 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6131 # check for function definitions
6132 if ($perl_version_ok &&
6134 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6135 $context_function = $1;
6137 # check for multiline function definition with misplaced open brace
6139 my $cnt = statement_rawlines($stat);
6140 my $herectx = $here . "\n";
6141 for (my $n = 0; $n < $cnt; $n++) {
6142 my $rl = raw_line($linenr, $n);
6143 $herectx .= $rl . "\n";
6144 $ok = 1 if ($rl =~ /^[ \+]\{/);
6145 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6146 last if $rl =~ /^[ \+].*\{/;
6150 "open brace '{' following function definitions go on the next line\n" . $herectx);
6154 # checks for new __setup's
6155 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6158 if (!grep(/$name/, @setup_docs)) {
6159 CHK("UNDOCUMENTED_SETUP",
6160 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6164 # check for pointless casting of kmalloc return
6165 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6166 WARN("UNNECESSARY_CASTS",
6167 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6171 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6172 if ($perl_version_ok &&
6173 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6174 CHK("ALLOC_SIZEOF_STRUCT",
6175 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6178 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6179 if ($perl_version_ok &&
6181 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6185 my $newfunc = "kmalloc_array";
6186 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6189 if ($a1 =~ /^sizeof\s*\S/) {
6193 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6194 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6195 my $cnt = statement_rawlines($stat);
6196 my $herectx = get_stat_here($linenr, $cnt, $here);
6198 if (WARN("ALLOC_WITH_MULTIPLY",
6199 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6202 $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;
6207 # check for krealloc arg reuse
6208 if ($perl_version_ok &&
6209 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6211 WARN("KREALLOC_ARG_REUSE",
6212 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6215 # check for alloc argument mismatch
6216 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6217 WARN("ALLOC_ARRAY_ARGS",
6218 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6221 # check for multiple semicolons
6222 if ($line =~ /;\s*;\s*$/) {
6223 if (WARN("ONE_SEMICOLON",
6224 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6226 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6230 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6231 if ($realfile !~ m@^include/uapi/@ &&
6232 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6234 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6235 if (CHK("BIT_MACRO",
6236 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6238 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6242 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6243 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6245 if (WARN("PREFER_IS_ENABLED",
6246 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6248 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6252 # check for case / default statements not preceded by break/fallthrough/switch
6253 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6255 my $has_statement = 0;
6257 my $prevline = $linenr;
6258 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6260 my $rline = $rawlines[$prevline - 1];
6261 my $fline = $lines[$prevline - 1];
6262 last if ($fline =~ /^\@\@/);
6263 next if ($fline =~ /^\-/);
6264 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6265 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6266 next if ($fline =~ /^.[\s$;]*$/);
6269 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6271 if (!$has_break && $has_statement) {
6272 WARN("MISSING_BREAK",
6273 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6277 # check for switch/default statements without a break;
6278 if ($perl_version_ok &&
6280 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6281 my $cnt = statement_rawlines($stat);
6282 my $herectx = get_stat_here($linenr, $cnt, $here);
6284 WARN("DEFAULT_NO_BREAK",
6285 "switch default: should use break\n" . $herectx);
6288 # check for gcc specific __FUNCTION__
6289 if ($line =~ /\b__FUNCTION__\b/) {
6290 if (WARN("USE_FUNC",
6291 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6293 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6297 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6298 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6300 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6303 # check for use of yield()
6304 if ($line =~ /\byield\s*\(\s*\)/) {
6306 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6309 # check for comparisons against true and false
6310 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6318 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6320 my $type = lc($otype);
6321 if ($type =~ /^(?:true|false)$/) {
6322 if (("$test" eq "==" && "$type" eq "true") ||
6323 ("$test" eq "!=" && "$type" eq "false")) {
6327 CHK("BOOL_COMPARISON",
6328 "Using comparison to $otype is error prone\n" . $herecurr);
6330 ## maybe suggesting a correct construct would better
6331 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6336 # check for bool bitfields
6337 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6338 WARN("BOOL_BITFIELD",
6339 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6342 # check for bool use in .h files
6343 if ($realfile =~ /\.h$/ &&
6344 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6346 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6349 # check for semaphores initialized locked
6350 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6351 WARN("CONSIDER_COMPLETION",
6352 "consider using a completion\n" . $herecurr);
6355 # recommend kstrto* over simple_strto* and strict_strto*
6356 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6357 WARN("CONSIDER_KSTRTO",
6358 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6361 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6362 if ($line =~ /^.\s*__initcall\s*\(/) {
6363 WARN("USE_DEVICE_INITCALL",
6364 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6367 # check for various structs that are normally const (ops, kgdb, device_tree)
6368 # and avoid what seem like struct definitions 'struct foo {'
6369 if ($line !~ /\bconst\b/ &&
6370 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6371 WARN("CONST_STRUCT",
6372 "struct $1 should normally be const\n" . $herecurr);
6375 # use of NR_CPUS is usually wrong
6376 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6377 if ($line =~ /\bNR_CPUS\b/ &&
6378 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6379 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6380 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6381 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6382 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6385 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6388 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6389 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6390 ERROR("DEFINE_ARCH_HAS",
6391 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6394 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6395 if ($perl_version_ok &&
6396 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6397 WARN("LIKELY_MISUSE",
6398 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6401 # whine mightly about in_atomic
6402 if ($line =~ /\bin_atomic\s*\(/) {
6403 if ($realfile =~ m@^drivers/@) {
6405 "do not use in_atomic in drivers\n" . $herecurr);
6406 } elsif ($realfile !~ m@^kernel/@) {
6408 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6412 # check for mutex_trylock_recursive usage
6413 if ($line =~ /mutex_trylock_recursive/) {
6415 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6418 # check for lockdep_set_novalidate_class
6419 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6420 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6421 if ($realfile !~ m@^kernel/lockdep@ &&
6422 $realfile !~ m@^include/linux/lockdep@ &&
6423 $realfile !~ m@^drivers/base/core@) {
6425 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6429 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6430 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6431 WARN("EXPORTED_WORLD_WRITABLE",
6432 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6435 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6436 # and whether or not function naming is typical and if
6437 # DEVICE_ATTR permissions uses are unusual too
6438 if ($perl_version_ok &&
6440 $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*\)/) {
6445 my $octal_perms = perms_to_octal($perms);
6446 if ($show =~ /^${var}_show$/ &&
6447 $store =~ /^${var}_store$/ &&
6448 $octal_perms eq "0644") {
6449 if (WARN("DEVICE_ATTR_RW",
6450 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6452 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6454 } elsif ($show =~ /^${var}_show$/ &&
6455 $store =~ /^NULL$/ &&
6456 $octal_perms eq "0444") {
6457 if (WARN("DEVICE_ATTR_RO",
6458 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6460 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6462 } elsif ($show =~ /^NULL$/ &&
6463 $store =~ /^${var}_store$/ &&
6464 $octal_perms eq "0200") {
6465 if (WARN("DEVICE_ATTR_WO",
6466 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6468 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6470 } elsif ($octal_perms eq "0644" ||
6471 $octal_perms eq "0444" ||
6472 $octal_perms eq "0200") {
6473 my $newshow = "$show";
6474 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6475 my $newstore = $store;
6476 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6478 if ($show ne $newshow) {
6479 $rename .= " '$show' to '$newshow'";
6481 if ($store ne $newstore) {
6482 $rename .= " '$store' to '$newstore'";
6484 WARN("DEVICE_ATTR_FUNCTIONS",
6485 "Consider renaming function(s)$rename\n" . $herecurr);
6487 WARN("DEVICE_ATTR_PERMS",
6488 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6492 # Mode permission misuses where it seems decimal should be octal
6493 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6494 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6495 # specific definition of not visible in sysfs.
6496 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6497 # use the default permissions
6498 if ($perl_version_ok &&
6500 $line =~ /$mode_perms_search/) {
6501 foreach my $entry (@mode_permission_funcs) {
6502 my $func = $entry->[0];
6503 my $arg_pos = $entry->[1];
6505 my $lc = $stat =~ tr@\n@@;
6506 $lc = $lc + $linenr;
6507 my $stat_real = get_stat_real($linenr, $lc);
6512 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6514 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6515 if ($stat =~ /$test/) {
6517 $val = $6 if ($skip_args ne "");
6518 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6519 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6520 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6521 ERROR("NON_OCTAL_PERMISSIONS",
6522 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6524 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6525 ERROR("EXPORTED_WORLD_WRITABLE",
6526 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6532 # check for uses of S_<PERMS> that could be octal for readability
6533 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6535 my $octal = perms_to_octal($oval);
6536 if (WARN("SYMBOLIC_PERMS",
6537 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6539 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6543 # validate content of MODULE_LICENSE against list from include/linux/module.h
6544 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6545 my $extracted_string = get_quoted_string($line, $rawline);
6546 my $valid_licenses = qr{
6549 GPL\ and\ additional\ rights|
6555 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6556 WARN("MODULE_LICENSE",
6557 "unknown module license " . $extracted_string . "\n" . $herecurr);
6562 # If we have no input at all, then there is nothing to report on
6563 # so just keep quiet.
6564 if ($#rawlines == -1) {
6568 # In mailback mode only produce a report in the negative, for
6569 # things that appear to be patches.
6570 if ($mailback && ($clean == 1 || !$is_patch)) {
6574 # This is not a patch, and we are are in 'no-patch' mode so
6576 if (!$chk_patch && !$is_patch) {
6580 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6581 ERROR("NOT_UNIFIED_DIFF",
6582 "Does not appear to be a unified-diff format patch\n");
6584 if ($is_patch && $has_commit_log && $chk_signoff) {
6585 if ($signoff == 0) {
6586 ERROR("MISSING_SIGN_OFF",
6587 "Missing Signed-off-by: line(s)\n");
6588 } elsif (!$authorsignoff) {
6589 WARN("NO_AUTHOR_SIGN_OFF",
6590 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6594 print report_dump();
6595 if ($summary && !($clean == 1 && $quiet == 1)) {
6596 print "$filename " if ($summary_file);
6597 print "total: $cnt_error errors, $cnt_warn warnings, " .
6598 (($check)? "$cnt_chk checks, " : "") .
6599 "$cnt_lines lines checked\n";
6603 # If there were any defects found and not already fixing them
6604 if (!$clean and !$fix) {
6607 NOTE: For some of the reported defects, checkpatch may be able to
6608 mechanically convert to the typical style using --fix or --fix-inplace.
6611 # If there were whitespace errors which cleanpatch can fix
6612 # then suggest that.
6613 if ($rpt_cleaners) {
6617 NOTE: Whitespace errors detected.
6618 You may wish to use scripts/cleanpatch or scripts/cleanfile
6623 if ($clean == 0 && $fix &&
6624 ("@rawlines" ne "@fixed" ||
6625 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6626 my $newfile = $filename;
6627 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6631 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6633 open($f, '>', $newfile)
6634 or die "$P: Can't open $newfile for write\n";
6635 foreach my $fixed_line (@fixed) {
6638 if ($linecount > 3) {
6639 $fixed_line =~ s/^\+//;
6640 print $f $fixed_line . "\n";
6643 print $f $fixed_line . "\n";
6651 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6653 Do _NOT_ trust the results written to this file.
6654 Do _NOT_ submit these changes without inspecting them for correctness.
6656 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6657 No warranties, expressed or implied...
6665 print "$vname has no obvious style problems and is ready for submission.\n";
6667 print "$vname has style problems, please review.\n";