2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
16 use Getopt::Long qw(:config no_auto_abbrev);
40 my $configuration_file = ".checkpatch.conf";
41 my $max_line_length = 80;
42 my $ignore_perl_version = 0;
43 my $minimum_perl_version = 5.10.0;
49 Usage: $P [OPTION]... [FILE]...
54 --no-tree run without a kernel tree
55 --no-signoff do not check for 'Signed-off-by' line
56 --patch treat FILE as patchfile (default)
57 --emacs emacs compile window format
58 --terse one line per report
59 -f, --file treat FILE as regular source file
60 --subjective, --strict enable more subjective tests
61 --types TYPE(,TYPE2...) show only these comma separated message types
62 --ignore TYPE(,TYPE2...) ignore various comma separated message types
63 --max-line-length=n set the maximum line length, if exceeded, warn
64 --show-types show the message "types" in the output
65 --root=PATH PATH to the kernel tree root
66 --no-summary suppress the per-file summary
67 --mailback only produce a report in case of warnings/errors
68 --summary-file include the filename in summary
69 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
70 'values', 'possible', 'type', and 'attr' (default
72 --test-only=WORD report only warnings/errors containing WORD
74 --fix EXPERIMENTAL - may create horrible results
75 If correctable single-line errors exist, create
76 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
77 with potential errors corrected to the preferred
79 --ignore-perl-version override checking of perl version. expect
81 -h, --help, --version display this help and exit
83 When FILE is - read standard input.
89 my $conf = which_conf($configuration_file);
92 open(my $conffile, '<', "$conf")
93 or warn "$P: Can't find a readable $configuration_file file $!\n";
98 $line =~ s/\s*\n?$//g;
102 next if ($line =~ m/^\s*#/);
103 next if ($line =~ m/^\s*$/);
105 my @words = split(" ", $line);
106 foreach my $word (@words) {
107 last if ($word =~ m/^#/);
108 push (@conf_args, $word);
112 unshift(@ARGV, @conf_args) if @conf_args;
116 'q|quiet+' => \$quiet,
118 'signoff!' => \$chk_signoff,
119 'patch!' => \$chk_patch,
123 'subjective!' => \$check,
124 'strict!' => \$check,
125 'ignore=s' => \@ignore,
127 'show-types!' => \$show_types,
128 'max-line-length=i' => \$max_line_length,
130 'summary!' => \$summary,
131 'mailback!' => \$mailback,
132 'summary-file!' => \$summary_file,
134 'ignore-perl-version!' => \$ignore_perl_version,
135 'debug=s' => \%debug,
136 'test-only=s' => \$tst_only,
145 if ($^V && $^V lt $minimum_perl_version) {
146 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
147 if (!$ignore_perl_version) {
153 print "$P: no input files\n";
157 sub hash_save_array_words {
158 my ($hashRef, $arrayRef) = @_;
160 my @array = split(/,/, join(',', @$arrayRef));
161 foreach my $word (@array) {
162 $word =~ s/\s*\n?$//g;
165 $word =~ tr/[a-z]/[A-Z]/;
167 next if ($word =~ m/^\s*#/);
168 next if ($word =~ m/^\s*$/);
174 sub hash_show_words {
175 my ($hashRef, $prefix) = @_;
177 if ($quiet == 0 && keys $hashRef) {
178 print "NOTE: $prefix message types:";
179 foreach my $word (sort keys $hashRef) {
186 hash_save_array_words(\%ignore_type, \@ignore);
187 hash_save_array_words(\%use_type, \@use);
190 my $dbg_possible = 0;
193 for my $key (keys %debug) {
195 eval "\${dbg_$key} = '$debug{$key}';";
199 my $rpt_cleaners = 0;
208 if (!top_of_kernel_tree($root)) {
209 die "$P: $root: --root does not point at a valid tree\n";
212 if (top_of_kernel_tree('.')) {
214 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
215 top_of_kernel_tree($1)) {
220 if (!defined $root) {
221 print "Must be run from the top-level dir. of a kernel tree\n";
226 my $emitted_corrupt = 0;
229 [A-Za-z_][A-Za-z\d_]*
230 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
232 our $Storage = qr{extern|static|asmlinkage};
245 # Notes to $Attribute:
246 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
265 __(?:mem|cpu|dev|)(?:initdata|initconst|init\b)|
266 ____cacheline_aligned|
267 ____cacheline_aligned_in_smp|
268 ____cacheline_internodealigned_in_smp|
272 our $Inline = qr{inline|__always_inline|noinline};
273 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
274 our $Lval = qr{$Ident(?:$Member)*};
276 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
277 our $Binary = qr{(?i)0b[01]+$Int_type?};
278 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
279 our $Int = qr{[0-9]+$Int_type?};
280 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
281 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
282 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
283 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
284 our $Constant = qr{$Float|$Binary|$Hex|$Int};
285 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
286 our $Compare = qr{<=|>=|==|!=|<|>};
287 our $Arithmetic = qr{\+|-|\*|\/|%};
291 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
298 our $NON_ASCII_UTF8 = qr{
299 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
300 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
301 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
302 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
303 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
304 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
305 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
309 [\x09\x0A\x0D\x20-\x7E] # ASCII
313 our $typeTypedefs = qr{(?x:
314 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
318 our $logFunctions = qr{(?x:
319 printk(?:_ratelimited|_once|)|
320 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
321 WARN(?:_RATELIMIT|_ONCE|)|
326 our $signature_tags = qr{(?xi:
339 qr{(?:unsigned\s+)?char},
340 qr{(?:unsigned\s+)?short},
341 qr{(?:unsigned\s+)?int},
342 qr{(?:unsigned\s+)?long},
343 qr{(?:unsigned\s+)?long\s+int},
344 qr{(?:unsigned\s+)?long\s+long},
345 qr{(?:unsigned\s+)?long\s+long\s+int},
354 qr{${Ident}_handler},
355 qr{${Ident}_handler_fn},
357 our @modifierList = (
361 our $allowed_asm_includes = qr{(?x:
365 # memory.h: ARM has a custom one
368 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
369 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
370 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
372 (?:$Modifier\s+|const\s+)*
374 (?:typeof|__typeof__)\s*\([^\)]*\)|
378 (?:\s+$Modifier|\s+const)*
382 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*|\[\])+|(?:\s*\[\s*\])+)?
383 (?:\s+$Inline|\s+$Modifier)*
385 $Declare = qr{(?:$Storage\s+)?$Type};
389 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
391 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
392 # requires at least perl version v5.10.0
393 # Any use must be runtime checked with $^V
395 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
396 our $LvalOrFunc = qr{($Lval)\s*($balanced_parens{0,1})\s*};
397 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
401 return "" if (!defined($string));
402 $string =~ s@^\s*\(\s*@@g;
403 $string =~ s@\s*\)\s*$@@g;
404 $string =~ s@\s+@ @g;
408 sub seed_camelcase_file {
411 return if (!(-f $file));
415 open(my $include_file, '<', "$file")
416 or warn "$P: Can't read '$file' $!\n";
417 my $text = <$include_file>;
418 close($include_file);
420 my @lines = split('\n', $text);
422 foreach my $line (@lines) {
423 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
424 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
427 elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*\(/) {
433 my $camelcase_seeded = 0;
434 sub seed_camelcase_includes {
435 return if ($camelcase_seeded);
438 my $camelcase_cache = "";
439 my @include_files = ();
441 $camelcase_seeded = 1;
444 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
445 chomp $git_last_include_commit;
446 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
448 my $last_mod_date = 0;
449 $files = `find $root/include -name "*.h"`;
450 @include_files = split('\n', $files);
451 foreach my $file (@include_files) {
452 my $date = POSIX::strftime("%Y%m%d%H%M",
453 localtime((stat $file)[9]));
454 $last_mod_date = $date if ($last_mod_date < $date);
456 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
459 if ($camelcase_cache ne "" && -f $camelcase_cache) {
460 open(my $camelcase_file, '<', "$camelcase_cache")
461 or warn "$P: Can't read '$camelcase_cache' $!\n";
462 while (<$camelcase_file>) {
466 close($camelcase_file);
472 $files = `git ls-files "include/*.h"`;
473 @include_files = split('\n', $files);
476 foreach my $file (@include_files) {
477 seed_camelcase_file($file);
480 if ($camelcase_cache ne "") {
481 unlink glob ".checkpatch-camelcase.*";
482 open(my $camelcase_file, '>', "$camelcase_cache")
483 or warn "$P: Can't write '$camelcase_cache' $!\n";
484 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
485 print $camelcase_file ("$_\n");
487 close($camelcase_file);
491 $chk_signoff = 0 if ($file);
497 for my $filename (@ARGV) {
500 open($FILE, '-|', "diff -u /dev/null $filename") ||
501 die "$P: $filename: diff failed - $!\n";
502 } elsif ($filename eq '-') {
503 open($FILE, '<&STDIN');
505 open($FILE, '<', "$filename") ||
506 die "$P: $filename: open failed - $!\n";
508 if ($filename eq '-') {
509 $vname = 'Your patch';
518 if (!process($filename)) {
528 sub top_of_kernel_tree {
532 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
533 "README", "Documentation", "arch", "include", "drivers",
534 "fs", "init", "ipc", "kernel", "lib", "scripts",
537 foreach my $check (@tree_check) {
538 if (! -e $root . '/' . $check) {
546 my ($formatted_email) = @_;
552 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
555 $comment = $3 if defined $3;
556 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
558 $comment = $2 if defined $2;
559 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
561 $comment = $2 if defined $2;
562 $formatted_email =~ s/$address.*$//;
563 $name = $formatted_email;
565 $name =~ s/^\"|\"$//g;
566 # If there's a name left after stripping spaces and
567 # leading quotes, and the address doesn't have both
568 # leading and trailing angle brackets, the address
570 # "joe smith joe@smith.com" bad
571 # "joe smith <joe@smith.com" bad
572 if ($name ne "" && $address !~ /^<[^>]+>$/) {
580 $name =~ s/^\"|\"$//g;
581 $address = trim($address);
582 $address =~ s/^\<|\>$//g;
584 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
585 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
589 return ($name, $address, $comment);
593 my ($name, $address) = @_;
598 $name =~ s/^\"|\"$//g;
599 $address = trim($address);
601 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
602 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
607 $formatted_email = "$address";
609 $formatted_email = "$name <$address>";
612 return $formatted_email;
618 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
619 if (-e "$path/$conf") {
620 return "$path/$conf";
632 for my $c (split(//, $str)) {
636 for (; ($n % 8) != 0; $n++) {
648 (my $res = shift) =~ tr/\t/ /c;
655 # Drop the diff line leader and expand tabs
657 $line = expand_tabs($line);
659 # Pick the indent from the front of the line.
660 my ($white) = ($line =~ /^(\s*)/);
662 return (length($line), length($white));
665 my $sanitise_quote = '';
667 sub sanitise_line_reset {
668 my ($in_comment) = @_;
671 $sanitise_quote = '*/';
673 $sanitise_quote = '';
686 # Always copy over the diff marker.
687 $res = substr($line, 0, 1);
689 for ($off = 1; $off < length($line); $off++) {
690 $c = substr($line, $off, 1);
692 # Comments we are wacking completly including the begin
693 # and end, all to $;.
694 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
695 $sanitise_quote = '*/';
697 substr($res, $off, 2, "$;$;");
701 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
702 $sanitise_quote = '';
703 substr($res, $off, 2, "$;$;");
707 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
708 $sanitise_quote = '//';
710 substr($res, $off, 2, $sanitise_quote);
715 # A \ in a string means ignore the next character.
716 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
718 substr($res, $off, 2, 'XX');
723 if ($c eq "'" || $c eq '"') {
724 if ($sanitise_quote eq '') {
725 $sanitise_quote = $c;
727 substr($res, $off, 1, $c);
729 } elsif ($sanitise_quote eq $c) {
730 $sanitise_quote = '';
734 #print "c<$c> SQ<$sanitise_quote>\n";
735 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
736 substr($res, $off, 1, $;);
737 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
738 substr($res, $off, 1, $;);
739 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
740 substr($res, $off, 1, 'X');
742 substr($res, $off, 1, $c);
746 if ($sanitise_quote eq '//') {
747 $sanitise_quote = '';
750 # The pathname on a #include may be surrounded by '<' and '>'.
751 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
752 my $clean = 'X' x length($1);
753 $res =~ s@\<.*\>@<$clean>@;
755 # The whole of a #error is a string.
756 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
757 my $clean = 'X' x length($1);
758 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
764 sub get_quoted_string {
765 my ($line, $rawline) = @_;
767 return "" if ($line !~ m/(\"[X]+\")/g);
768 return substr($rawline, $-[0], $+[0] - $-[0]);
771 sub ctx_statement_block {
772 my ($linenr, $remain, $off) = @_;
773 my $line = $linenr - 1;
790 @stack = (['', 0]) if ($#stack == -1);
792 #warn "CSB: blk<$blk> remain<$remain>\n";
793 # If we are about to drop off the end, pull in more
796 for (; $remain > 0; $line++) {
797 last if (!defined $lines[$line]);
798 next if ($lines[$line] =~ /^-/);
801 $blk .= $lines[$line] . "\n";
806 # Bail if there is no further context.
807 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
811 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
817 $c = substr($blk, $off, 1);
818 $remainder = substr($blk, $off);
820 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
822 # Handle nested #if/#else.
823 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
824 push(@stack, [ $type, $level ]);
825 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
826 ($type, $level) = @{$stack[$#stack - 1]};
827 } elsif ($remainder =~ /^#\s*endif\b/) {
828 ($type, $level) = @{pop(@stack)};
831 # Statement ends at the ';' or a close '}' at the
833 if ($level == 0 && $c eq ';') {
837 # An else is really a conditional as long as its not else if
838 if ($level == 0 && $coff_set == 0 &&
839 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
840 $remainder =~ /^(else)(?:\s|{)/ &&
841 $remainder !~ /^else\s+if\b/) {
842 $coff = $off + length($1) - 1;
844 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
845 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
848 if (($type eq '' || $type eq '(') && $c eq '(') {
852 if ($type eq '(' && $c eq ')') {
854 $type = ($level != 0)? '(' : '';
856 if ($level == 0 && $coff < $soff) {
859 #warn "CSB: mark coff<$coff>\n";
862 if (($type eq '' || $type eq '{') && $c eq '{') {
866 if ($type eq '{' && $c eq '}') {
868 $type = ($level != 0)? '{' : '';
871 if (substr($blk, $off + 1, 1) eq ';') {
877 # Preprocessor commands end at the newline unless escaped.
878 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
886 # We are truly at the end, so shuffle to the next line.
893 my $statement = substr($blk, $soff, $off - $soff + 1);
894 my $condition = substr($blk, $soff, $coff - $soff + 1);
896 #warn "STATEMENT<$statement>\n";
897 #warn "CONDITION<$condition>\n";
899 #print "coff<$coff> soff<$off> loff<$loff>\n";
901 return ($statement, $condition,
902 $line, $remain + 1, $off - $loff + 1, $level);
905 sub statement_lines {
908 # Strip the diff line prefixes and rip blank lines at start and end.
909 $stmt =~ s/(^|\n)./$1/g;
913 my @stmt_lines = ($stmt =~ /\n/g);
915 return $#stmt_lines + 2;
918 sub statement_rawlines {
921 my @stmt_lines = ($stmt =~ /\n/g);
923 return $#stmt_lines + 2;
926 sub statement_block_size {
929 $stmt =~ s/(^|\n)./$1/g;
935 my @stmt_lines = ($stmt =~ /\n/g);
936 my @stmt_statements = ($stmt =~ /;/g);
938 my $stmt_lines = $#stmt_lines + 2;
939 my $stmt_statements = $#stmt_statements + 1;
941 if ($stmt_lines > $stmt_statements) {
944 return $stmt_statements;
948 sub ctx_statement_full {
949 my ($linenr, $remain, $off) = @_;
950 my ($statement, $condition, $level);
954 # Grab the first conditional/block pair.
955 ($statement, $condition, $linenr, $remain, $off, $level) =
956 ctx_statement_block($linenr, $remain, $off);
957 #print "F: c<$condition> s<$statement> remain<$remain>\n";
958 push(@chunks, [ $condition, $statement ]);
959 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
960 return ($level, $linenr, @chunks);
963 # Pull in the following conditional/block pairs and see if they
964 # could continue the statement.
966 ($statement, $condition, $linenr, $remain, $off, $level) =
967 ctx_statement_block($linenr, $remain, $off);
968 #print "C: c<$condition> s<$statement> remain<$remain>\n";
969 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
971 push(@chunks, [ $condition, $statement ]);
974 return ($level, $linenr, @chunks);
978 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
980 my $start = $linenr - 1;
987 my @stack = ($level);
988 for ($line = $start; $remain > 0; $line++) {
989 next if ($rawlines[$line] =~ /^-/);
992 $blk .= $rawlines[$line];
994 # Handle nested #if/#else.
995 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
996 push(@stack, $level);
997 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
998 $level = $stack[$#stack - 1];
999 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1000 $level = pop(@stack);
1003 foreach my $c (split(//, $lines[$line])) {
1004 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1010 if ($c eq $close && $level > 0) {
1012 last if ($level == 0);
1013 } elsif ($c eq $open) {
1018 if (!$outer || $level <= 1) {
1019 push(@res, $rawlines[$line]);
1022 last if ($level == 0);
1025 return ($level, @res);
1027 sub ctx_block_outer {
1028 my ($linenr, $remain) = @_;
1030 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1034 my ($linenr, $remain) = @_;
1036 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1040 my ($linenr, $remain, $off) = @_;
1042 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1045 sub ctx_block_level {
1046 my ($linenr, $remain) = @_;
1048 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1050 sub ctx_statement_level {
1051 my ($linenr, $remain, $off) = @_;
1053 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1056 sub ctx_locate_comment {
1057 my ($first_line, $end_line) = @_;
1059 # Catch a comment on the end of the line itself.
1060 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1061 return $current_comment if (defined $current_comment);
1063 # Look through the context and try and figure out if there is a
1066 $current_comment = '';
1067 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1068 my $line = $rawlines[$linenr - 1];
1070 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1073 if ($line =~ m@/\*@) {
1076 if (!$in_comment && $current_comment ne '') {
1077 $current_comment = '';
1079 $current_comment .= $line . "\n" if ($in_comment);
1080 if ($line =~ m@\*/@) {
1085 chomp($current_comment);
1086 return($current_comment);
1088 sub ctx_has_comment {
1089 my ($first_line, $end_line) = @_;
1090 my $cmt = ctx_locate_comment($first_line, $end_line);
1092 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1093 ##print "CMMT: $cmt\n";
1095 return ($cmt ne '');
1099 my ($linenr, $cnt) = @_;
1101 my $offset = $linenr - 1;
1106 $line = $rawlines[$offset++];
1107 next if (defined($line) && $line =~ /^-/);
1119 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1122 $coded = sprintf("^%c", unpack('C', $2) + 64);
1131 my $av_preprocessor = 0;
1136 sub annotate_reset {
1137 $av_preprocessor = 0;
1139 @av_paren_type = ('E');
1140 $av_pend_colon = 'O';
1143 sub annotate_values {
1144 my ($stream, $type) = @_;
1147 my $var = '_' x length($stream);
1150 print "$stream\n" if ($dbg_values > 1);
1152 while (length($cur)) {
1153 @av_paren_type = ('E') if ($#av_paren_type < 0);
1154 print " <" . join('', @av_paren_type) .
1155 "> <$type> <$av_pending>" if ($dbg_values > 1);
1156 if ($cur =~ /^(\s+)/o) {
1157 print "WS($1)\n" if ($dbg_values > 1);
1158 if ($1 =~ /\n/ && $av_preprocessor) {
1159 $type = pop(@av_paren_type);
1160 $av_preprocessor = 0;
1163 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1164 print "CAST($1)\n" if ($dbg_values > 1);
1165 push(@av_paren_type, $type);
1168 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1169 print "DECLARE($1)\n" if ($dbg_values > 1);
1172 } elsif ($cur =~ /^($Modifier)\s*/) {
1173 print "MODIFIER($1)\n" if ($dbg_values > 1);
1176 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1177 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1178 $av_preprocessor = 1;
1179 push(@av_paren_type, $type);
1185 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1186 print "UNDEF($1)\n" if ($dbg_values > 1);
1187 $av_preprocessor = 1;
1188 push(@av_paren_type, $type);
1190 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1191 print "PRE_START($1)\n" if ($dbg_values > 1);
1192 $av_preprocessor = 1;
1194 push(@av_paren_type, $type);
1195 push(@av_paren_type, $type);
1198 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1199 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1200 $av_preprocessor = 1;
1202 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1206 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1207 print "PRE_END($1)\n" if ($dbg_values > 1);
1209 $av_preprocessor = 1;
1211 # Assume all arms of the conditional end as this
1212 # one does, and continue as if the #endif was not here.
1213 pop(@av_paren_type);
1214 push(@av_paren_type, $type);
1217 } elsif ($cur =~ /^(\\\n)/o) {
1218 print "PRECONT($1)\n" if ($dbg_values > 1);
1220 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1221 print "ATTR($1)\n" if ($dbg_values > 1);
1222 $av_pending = $type;
1225 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1226 print "SIZEOF($1)\n" if ($dbg_values > 1);
1232 } elsif ($cur =~ /^(if|while|for)\b/o) {
1233 print "COND($1)\n" if ($dbg_values > 1);
1237 } elsif ($cur =~/^(case)/o) {
1238 print "CASE($1)\n" if ($dbg_values > 1);
1239 $av_pend_colon = 'C';
1242 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1243 print "KEYWORD($1)\n" if ($dbg_values > 1);
1246 } elsif ($cur =~ /^(\()/o) {
1247 print "PAREN('$1')\n" if ($dbg_values > 1);
1248 push(@av_paren_type, $av_pending);
1252 } elsif ($cur =~ /^(\))/o) {
1253 my $new_type = pop(@av_paren_type);
1254 if ($new_type ne '_') {
1256 print "PAREN('$1') -> $type\n"
1257 if ($dbg_values > 1);
1259 print "PAREN('$1')\n" if ($dbg_values > 1);
1262 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1263 print "FUNC($1)\n" if ($dbg_values > 1);
1267 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1268 if (defined $2 && $type eq 'C' || $type eq 'T') {
1269 $av_pend_colon = 'B';
1270 } elsif ($type eq 'E') {
1271 $av_pend_colon = 'L';
1273 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1276 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1277 print "IDENT($1)\n" if ($dbg_values > 1);
1280 } elsif ($cur =~ /^($Assignment)/o) {
1281 print "ASSIGN($1)\n" if ($dbg_values > 1);
1284 } elsif ($cur =~/^(;|{|})/) {
1285 print "END($1)\n" if ($dbg_values > 1);
1287 $av_pend_colon = 'O';
1289 } elsif ($cur =~/^(,)/) {
1290 print "COMMA($1)\n" if ($dbg_values > 1);
1293 } elsif ($cur =~ /^(\?)/o) {
1294 print "QUESTION($1)\n" if ($dbg_values > 1);
1297 } elsif ($cur =~ /^(:)/o) {
1298 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1300 substr($var, length($res), 1, $av_pend_colon);
1301 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1306 $av_pend_colon = 'O';
1308 } elsif ($cur =~ /^(\[)/o) {
1309 print "CLOSE($1)\n" if ($dbg_values > 1);
1312 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1315 print "OPV($1)\n" if ($dbg_values > 1);
1322 substr($var, length($res), 1, $variant);
1325 } elsif ($cur =~ /^($Operators)/o) {
1326 print "OP($1)\n" if ($dbg_values > 1);
1327 if ($1 ne '++' && $1 ne '--') {
1331 } elsif ($cur =~ /(^.)/o) {
1332 print "C($1)\n" if ($dbg_values > 1);
1335 $cur = substr($cur, length($1));
1336 $res .= $type x length($1);
1340 return ($res, $var);
1344 my ($possible, $line) = @_;
1345 my $notPermitted = qr{(?:
1362 ^(?:typedef|struct|enum)\b
1364 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1365 if ($possible !~ $notPermitted) {
1366 # Check for modifiers.
1367 $possible =~ s/\s*$Storage\s*//g;
1368 $possible =~ s/\s*$Sparse\s*//g;
1369 if ($possible =~ /^\s*$/) {
1371 } elsif ($possible =~ /\s/) {
1372 $possible =~ s/\s*$Type\s*//g;
1373 for my $modifier (split(' ', $possible)) {
1374 if ($modifier !~ $notPermitted) {
1375 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1376 push(@modifierList, $modifier);
1381 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1382 push(@typeList, $possible);
1386 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1393 return defined $use_type{$_[0]} if (scalar keys %use_type > 0);
1395 return !defined $ignore_type{$_[0]};
1399 if (!show_type($_[1]) ||
1400 (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1405 $line = "$prefix$_[0]:$_[1]: $_[2]\n";
1407 $line = "$prefix$_[0]: $_[2]\n";
1409 $line = (split('\n', $line))[0] . "\n" if ($terse);
1411 push(our @report, $line);
1420 if (report("ERROR", $_[0], $_[1])) {
1428 if (report("WARNING", $_[0], $_[1])) {
1436 if ($check && report("CHECK", $_[0], $_[1])) {
1444 sub check_absolute_file {
1445 my ($absolute, $herecurr) = @_;
1446 my $file = $absolute;
1448 ##print "absolute<$absolute>\n";
1450 # See if any suffix of this path is a path within the tree.
1451 while ($file =~ s@^[^/]*/@@) {
1452 if (-f "$root/$file") {
1453 ##print "file<$file>\n";
1461 # It is, so see if the prefix is acceptable.
1462 my $prefix = $absolute;
1463 substr($prefix, -length($file)) = '';
1465 ##print "prefix<$prefix>\n";
1466 if ($prefix ne ".../") {
1467 WARN("USE_RELATIVE_PATH",
1468 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1475 $string =~ s/(^\s+|\s+$)//g;
1483 my $source_indent = 8;
1484 my $max_spaces_before_tab = $source_indent - 1;
1485 my $spaces_to_tab = " " x $source_indent;
1487 #convert leading spaces to tabs
1488 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1489 #Remove spaces before a tab
1490 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1495 sub pos_last_openparen {
1500 my $opens = $line =~ tr/\(/\(/;
1501 my $closes = $line =~ tr/\)/\)/;
1503 my $last_openparen = 0;
1505 if (($opens == 0) || ($closes >= $opens)) {
1509 my $len = length($line);
1511 for ($pos = 0; $pos < $len; $pos++) {
1512 my $string = substr($line, $pos);
1513 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1514 $pos += length($1) - 1;
1515 } elsif (substr($line, $pos, 1) eq '(') {
1516 $last_openparen = $pos;
1517 } elsif (index($string, '(') == -1) {
1522 return $last_openparen + 1;
1526 my $filename = shift;
1532 my $stashrawline="";
1543 my $in_header_lines = 1;
1544 my $in_commit_log = 0; #Scanning lines before patch
1546 my $non_utf8_charset = 0;
1554 # Trace the real file/line as we go.
1560 my $comment_edge = 0;
1564 my $prev_values = 'E';
1567 my %suppress_ifbraces;
1568 my %suppress_whiletrailers;
1569 my %suppress_export;
1570 my $suppress_statement = 0;
1572 my %signatures = ();
1574 # Pre-scan the patch sanitizing the lines.
1575 # Pre-scan the patch looking for any __setup documentation.
1577 my @setup_docs = ();
1580 sanitise_line_reset();
1582 foreach my $rawline (@rawlines) {
1586 push(@fixed, $rawline) if ($fix);
1588 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1590 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1595 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1604 # Guestimate if this is a continuing comment. Run
1605 # the context looking for a comment "edge". If this
1606 # edge is a close comment then we must be in a comment
1610 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1611 next if (defined $rawlines[$ln - 1] &&
1612 $rawlines[$ln - 1] =~ /^-/);
1614 #print "RAW<$rawlines[$ln - 1]>\n";
1615 last if (!defined $rawlines[$ln - 1]);
1616 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1617 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1622 if (defined $edge && $edge eq '*/') {
1626 # Guestimate if this is a continuing comment. If this
1627 # is the start of a diff block and this line starts
1628 # ' *' then it is very likely a comment.
1629 if (!defined $edge &&
1630 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1635 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1636 sanitise_line_reset($in_comment);
1638 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1639 # Standardise the strings and chars within the input to
1640 # simplify matching -- only bother with positive lines.
1641 $line = sanitise_line($rawline);
1643 push(@lines, $line);
1646 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1651 #print "==>$rawline\n";
1652 #print "-->$line\n";
1654 if ($setup_docs && $line =~ /^\+/) {
1655 push(@setup_docs, $line);
1663 foreach my $line (@lines) {
1666 my $rawline = $rawlines[$linenr - 1];
1668 #extract the line range in the file after the patch is applied
1669 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1671 $first_line = $linenr + 1;
1681 %suppress_ifbraces = ();
1682 %suppress_whiletrailers = ();
1683 %suppress_export = ();
1684 $suppress_statement = 0;
1687 # track the line number as we move through the hunk, note that
1688 # new versions of GNU diff omit the leading space on completely
1689 # blank context lines so we need to count that too.
1690 } elsif ($line =~ /^( |\+|$)/) {
1692 $realcnt-- if ($realcnt != 0);
1694 # Measure the line length and indent.
1695 ($length, $indent) = line_stats($rawline);
1697 # Track the previous line.
1698 ($prevline, $stashline) = ($stashline, $line);
1699 ($previndent, $stashindent) = ($stashindent, $indent);
1700 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1702 #warn "line<$line>\n";
1704 } elsif ($realcnt == 1) {
1708 my $hunk_line = ($realcnt != 0);
1710 #make up the handle for any error we report on this line
1711 $prefix = "$filename:$realline: " if ($emacs && $file);
1712 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1714 $here = "#$linenr: " if (!$file);
1715 $here = "#$realline: " if ($file);
1717 # extract the filename as it passes
1718 if ($line =~ /^diff --git.*?(\S+)$/) {
1720 $realfile =~ s@^([^/]*)/@@;
1722 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1724 $realfile =~ s@^([^/]*)/@@;
1728 if (!$file && $tree && $p1_prefix ne '' &&
1729 -e "$root/$p1_prefix") {
1730 WARN("PATCH_PREFIX",
1731 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1734 if ($realfile =~ m@^include/asm/@) {
1735 ERROR("MODIFIED_INCLUDE_ASM",
1736 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1741 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1743 my $hereline = "$here\n$rawline\n";
1744 my $herecurr = "$here\n$rawline\n";
1745 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1747 $cnt_lines++ if ($realcnt != 0);
1749 # Check for incorrect file permissions
1750 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1751 my $permhere = $here . "FILE: $realfile\n";
1752 if ($realfile !~ m@scripts/@ &&
1753 $realfile !~ /\.(py|pl|awk|sh)$/) {
1754 ERROR("EXECUTE_PERMISSIONS",
1755 "do not set execute permissions for source files\n" . $permhere);
1759 # Check the patch for a signoff:
1760 if ($line =~ /^\s*signed-off-by:/i) {
1765 # Check signature styles
1766 if (!$in_header_lines &&
1767 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
1768 my $space_before = $1;
1770 my $space_after = $3;
1772 my $ucfirst_sign_off = ucfirst(lc($sign_off));
1774 if ($sign_off !~ /$signature_tags/) {
1775 WARN("BAD_SIGN_OFF",
1776 "Non-standard signature: $sign_off\n" . $herecurr);
1778 if (defined $space_before && $space_before ne "") {
1779 if (WARN("BAD_SIGN_OFF",
1780 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
1782 $fixed[$linenr - 1] =
1783 "$ucfirst_sign_off $email";
1786 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1787 if (WARN("BAD_SIGN_OFF",
1788 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
1790 $fixed[$linenr - 1] =
1791 "$ucfirst_sign_off $email";
1795 if (!defined $space_after || $space_after ne " ") {
1796 if (WARN("BAD_SIGN_OFF",
1797 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
1799 $fixed[$linenr - 1] =
1800 "$ucfirst_sign_off $email";
1804 my ($email_name, $email_address, $comment) = parse_email($email);
1805 my $suggested_email = format_email(($email_name, $email_address));
1806 if ($suggested_email eq "") {
1807 ERROR("BAD_SIGN_OFF",
1808 "Unrecognized email address: '$email'\n" . $herecurr);
1810 my $dequoted = $suggested_email;
1811 $dequoted =~ s/^"//;
1812 $dequoted =~ s/" </ </;
1813 # Don't force email to have quotes
1814 # Allow just an angle bracketed address
1815 if ("$dequoted$comment" ne $email &&
1816 "<$email_address>$comment" ne $email &&
1817 "$suggested_email$comment" ne $email) {
1818 WARN("BAD_SIGN_OFF",
1819 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1823 # Check for duplicate signatures
1824 my $sig_nospace = $line;
1825 $sig_nospace =~ s/\s//g;
1826 $sig_nospace = lc($sig_nospace);
1827 if (defined $signatures{$sig_nospace}) {
1828 WARN("BAD_SIGN_OFF",
1829 "Duplicate signature\n" . $herecurr);
1831 $signatures{$sig_nospace} = 1;
1835 # Check for wrappage within a valid hunk of the file
1836 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1837 ERROR("CORRUPTED_PATCH",
1838 "patch seems to be corrupt (line wrapped?)\n" .
1839 $herecurr) if (!$emitted_corrupt++);
1842 # Check for absolute kernel paths.
1844 while ($line =~ m{(?:^|\s)(/\S*)}g) {
1847 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1848 check_absolute_file($1, $herecurr)) {
1851 check_absolute_file($file, $herecurr);
1856 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1857 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1858 $rawline !~ m/^$UTF8*$/) {
1859 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1861 my $blank = copy_spacing($rawline);
1862 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1863 my $hereptr = "$hereline$ptr\n";
1866 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1869 # Check if it's the start of a commit log
1870 # (not a header line and we haven't seen the patch filename)
1871 if ($in_header_lines && $realfile =~ /^$/ &&
1872 $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1873 $in_header_lines = 0;
1877 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1878 # declined it, i.e defined some charset where it is missing.
1879 if ($in_header_lines &&
1880 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1882 $non_utf8_charset = 1;
1885 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1886 $rawline =~ /$NON_ASCII_UTF8/) {
1887 WARN("UTF8_BEFORE_PATCH",
1888 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
1891 # ignore non-hunk lines and lines being removed
1892 next if (!$hunk_line || $line =~ /^-/);
1894 #trailing whitespace
1895 if ($line =~ /^\+.*\015/) {
1896 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1897 if (ERROR("DOS_LINE_ENDINGS",
1898 "DOS line endings\n" . $herevet) &&
1900 $fixed[$linenr - 1] =~ s/[\s\015]+$//;
1902 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1903 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1904 if (ERROR("TRAILING_WHITESPACE",
1905 "trailing whitespace\n" . $herevet) &&
1907 $fixed[$linenr - 1] =~ s/\s+$//;
1913 # check for Kconfig help text having a real description
1914 # Only applies when adding the entry originally, after that we do not have
1915 # sufficient context to determine whether it is indeed long enough.
1916 if ($realfile =~ /Kconfig/ &&
1917 $line =~ /.\s*config\s+/) {
1920 my $ln = $linenr + 1;
1924 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
1925 $f = $lines[$ln - 1];
1926 $cnt-- if ($lines[$ln - 1] !~ /^-/);
1927 $is_end = $lines[$ln - 1] =~ /^\+/;
1929 next if ($f =~ /^-/);
1931 if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
1933 } elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
1940 next if ($f =~ /^$/);
1941 if ($f =~ /^\s*config\s/) {
1947 WARN("CONFIG_DESCRIPTION",
1948 "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
1949 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
1952 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
1953 if ($realfile =~ /Kconfig/ &&
1954 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
1955 WARN("CONFIG_EXPERIMENTAL",
1956 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
1959 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
1960 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
1963 'EXTRA_AFLAGS' => 'asflags-y',
1964 'EXTRA_CFLAGS' => 'ccflags-y',
1965 'EXTRA_CPPFLAGS' => 'cppflags-y',
1966 'EXTRA_LDFLAGS' => 'ldflags-y',
1969 WARN("DEPRECATED_VARIABLE",
1970 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
1973 # check we are in a valid source file if not then ignore this hunk
1974 next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
1977 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
1978 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
1979 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
1980 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1981 $length > $max_line_length)
1984 "line over $max_line_length characters\n" . $herecurr);
1987 # Check for user-visible strings broken across lines, which breaks the ability
1988 # to grep for the string. Limited to strings used as parameters (those
1989 # following an open parenthesis), which almost completely eliminates false
1990 # positives, as well as warning only once per parameter rather than once per
1991 # line of the string. Make an exception when the previous string ends in a
1992 # newline (multiple lines in one string constant) or \n\t (common in inline
1993 # assembly to indent the instruction on the following line).
1994 if ($line =~ /^\+\s*"/ &&
1995 $prevline =~ /"\s*$/ &&
1996 $prevline =~ /\(/ &&
1997 $prevrawline !~ /\\n(?:\\t)*"\s*$/) {
1998 WARN("SPLIT_STRING",
1999 "quoted string split across lines\n" . $hereprev);
2002 # check for spaces before a quoted newline
2003 if ($rawline =~ /^.*\".*\s\\n/) {
2004 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2005 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2007 $fixed[$linenr - 1] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2012 # check for adding lines without a newline.
2013 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2014 WARN("MISSING_EOF_NEWLINE",
2015 "adding a line without newline at end of file\n" . $herecurr);
2018 # Blackfin: use hi/lo macros
2019 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2020 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2021 my $herevet = "$here\n" . cat_vet($line) . "\n";
2023 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2025 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2026 my $herevet = "$here\n" . cat_vet($line) . "\n";
2028 "use the HI() macro, not (... >> 16)\n" . $herevet);
2032 # check we are in a valid source file C or perl if not then ignore this hunk
2033 next if ($realfile !~ /\.(h|c|pl)$/);
2035 # at the beginning of a line any tabs must come first and anything
2036 # more than 8 must use tabs.
2037 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2038 $rawline =~ /^\+\s* \s*/) {
2039 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2041 if (ERROR("CODE_INDENT",
2042 "code indent should use tabs where possible\n" . $herevet) &&
2044 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2048 # check for space before tabs.
2049 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2050 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2051 if (WARN("SPACE_BEFORE_TAB",
2052 "please, no space before tabs\n" . $herevet) &&
2054 $fixed[$linenr - 1] =~
2055 s/(^\+.*) +\t/$1\t/;
2059 # check for && or || at the start of a line
2060 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2061 CHK("LOGICAL_CONTINUATIONS",
2062 "Logical continuations should be on the previous line\n" . $hereprev);
2065 # check multi-line statement indentation matches previous line
2066 if ($^V && $^V ge 5.10.0 &&
2067 $prevline =~ /^\+(\t*)(if \(|$Ident\().*(\&\&|\|\||,)\s*$/) {
2068 $prevline =~ /^\+(\t*)(.*)$/;
2072 my $pos = pos_last_openparen($rest);
2074 $line =~ /^(\+| )([ \t]*)/;
2077 my $goodtabindent = $oldindent .
2080 my $goodspaceindent = $oldindent . " " x $pos;
2082 if ($newindent ne $goodtabindent &&
2083 $newindent ne $goodspaceindent) {
2085 if (CHK("PARENTHESIS_ALIGNMENT",
2086 "Alignment should match open parenthesis\n" . $hereprev) &&
2087 $fix && $line =~ /^\+/) {
2088 $fixed[$linenr - 1] =~
2089 s/^\+[ \t]*/\+$goodtabindent/;
2095 if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) {
2097 "No space is necessary after a cast\n" . $hereprev) &&
2099 $fixed[$linenr - 1] =~
2100 s/^(\+.*\*[ \t]*\))[ \t]+/$1/;
2104 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2105 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2106 $rawline =~ /^\+[ \t]*\*/) {
2107 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2108 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2111 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2112 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2113 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2114 $rawline =~ /^\+/ && #line is new
2115 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2116 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2117 "networking block comments start with * on subsequent lines\n" . $hereprev);
2120 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2121 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2122 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2123 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2124 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2125 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2126 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2129 # check for spaces at the beginning of a line.
2131 # 1) within comments
2132 # 2) indented preprocessor commands
2134 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2135 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2136 if (WARN("LEADING_SPACE",
2137 "please, no spaces at the start of a line\n" . $herevet) &&
2139 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2143 # check we are in a valid C source file if not then ignore this hunk
2144 next if ($realfile !~ /\.(h|c)$/);
2146 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2147 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2148 WARN("CONFIG_EXPERIMENTAL",
2149 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2152 # check for RCS/CVS revision markers
2153 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2155 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2158 # Blackfin: don't use __builtin_bfin_[cs]sync
2159 if ($line =~ /__builtin_bfin_csync/) {
2160 my $herevet = "$here\n" . cat_vet($line) . "\n";
2162 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2164 if ($line =~ /__builtin_bfin_ssync/) {
2165 my $herevet = "$here\n" . cat_vet($line) . "\n";
2167 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2170 # check for old HOTPLUG __dev<foo> section markings
2171 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2172 WARN("HOTPLUG_SECTION",
2173 "Using $1 is unnecessary\n" . $herecurr);
2176 # Check for potential 'bare' types
2177 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2179 #print "LINE<$line>\n";
2180 if ($linenr >= $suppress_statement &&
2181 $realcnt && $line =~ /.\s*\S/) {
2182 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2183 ctx_statement_block($linenr, $realcnt, 0);
2184 $stat =~ s/\n./\n /g;
2185 $cond =~ s/\n./\n /g;
2187 #print "linenr<$linenr> <$stat>\n";
2188 # If this statement has no statement boundaries within
2189 # it there is no point in retrying a statement scan
2190 # until we hit end of it.
2191 my $frag = $stat; $frag =~ s/;+\s*$//;
2192 if ($frag !~ /(?:{|;)/) {
2193 #print "skip<$line_nr_next>\n";
2194 $suppress_statement = $line_nr_next;
2197 # Find the real next line.
2198 $realline_next = $line_nr_next;
2199 if (defined $realline_next &&
2200 (!defined $lines[$realline_next - 1] ||
2201 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2208 # Ignore goto labels.
2209 if ($s =~ /$Ident:\*$/s) {
2211 # Ignore functions being called
2212 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2214 } elsif ($s =~ /^.\s*else\b/s) {
2216 # declarations always start with types
2217 } 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) {
2220 possible($type, "A:" . $s);
2222 # definitions in global scope can only start with types
2223 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2224 possible($1, "B:" . $s);
2227 # any (foo ... *) is a pointer cast, and foo is a type
2228 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2229 possible($1, "C:" . $s);
2232 # Check for any sort of function declaration.
2233 # int foo(something bar, other baz);
2234 # void (*store_gdt)(x86_descr_ptr *);
2235 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2236 my ($name_len) = length($1);
2239 substr($ctx, 0, $name_len + 1, '');
2240 $ctx =~ s/\)[^\)]*$//;
2242 for my $arg (split(/\s*,\s*/, $ctx)) {
2243 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2245 possible($1, "D:" . $s);
2253 # Checks which may be anchored in the context.
2256 # Check for switch () and associated case and default
2257 # statements should be at the same indent.
2258 if ($line=~/\bswitch\s*\(.*\)/) {
2261 my @ctx = ctx_block_outer($linenr, $realcnt);
2263 for my $ctx (@ctx) {
2264 my ($clen, $cindent) = line_stats($ctx);
2265 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2266 $indent != $cindent) {
2267 $err .= "$sep$ctx\n";
2274 ERROR("SWITCH_CASE_INDENT_LEVEL",
2275 "switch and case should be at the same indent\n$hereline$err");
2279 # if/while/etc brace do not go on next line, unless defining a do while loop,
2280 # or if that brace on the next line is for something else
2281 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2282 my $pre_ctx = "$1$2";
2284 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2286 if ($line =~ /^\+\t{6,}/) {
2287 WARN("DEEP_INDENTATION",
2288 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2291 my $ctx_cnt = $realcnt - $#ctx - 1;
2292 my $ctx = join("\n", @ctx);
2294 my $ctx_ln = $linenr;
2295 my $ctx_skip = $realcnt;
2297 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2298 defined $lines[$ctx_ln - 1] &&
2299 $lines[$ctx_ln - 1] =~ /^-/)) {
2300 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2301 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2305 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2306 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2308 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2310 "that open brace { should be on the previous line\n" .
2311 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2313 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2314 $ctx =~ /\)\s*\;\s*$/ &&
2315 defined $lines[$ctx_ln - 1])
2317 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2318 if ($nindent > $indent) {
2319 WARN("TRAILING_SEMICOLON",
2320 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2321 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2326 # Check relative indent for conditionals and blocks.
2327 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2328 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2329 ctx_statement_block($linenr, $realcnt, 0)
2330 if (!defined $stat);
2331 my ($s, $c) = ($stat, $cond);
2333 substr($s, 0, length($c), '');
2335 # Make sure we remove the line prefixes as we have
2336 # none on the first line, and are going to readd them
2340 # Find out how long the conditional actually is.
2341 my @newlines = ($c =~ /\n/gs);
2342 my $cond_lines = 1 + $#newlines;
2344 # We want to check the first line inside the block
2345 # starting at the end of the conditional, so remove:
2346 # 1) any blank line termination
2347 # 2) any opening brace { on end of the line
2349 my $continuation = 0;
2351 $s =~ s/^.*\bdo\b//;
2353 if ($s =~ s/^\s*\\//) {
2356 if ($s =~ s/^\s*?\n//) {
2361 # Also ignore a loop construct at the end of a
2362 # preprocessor statement.
2363 if (($prevline =~ /^.\s*#\s*define\s/ ||
2364 $prevline =~ /\\\s*$/) && $continuation == 0) {
2370 while ($cond_ptr != $cond_lines) {
2371 $cond_ptr = $cond_lines;
2373 # If we see an #else/#elif then the code
2375 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2380 # 1) blank lines, they should be at 0,
2381 # 2) preprocessor lines, and
2383 if ($continuation ||
2385 $s =~ /^\s*#\s*?/ ||
2386 $s =~ /^\s*$Ident\s*:/) {
2387 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2388 if ($s =~ s/^.*?\n//) {
2394 my (undef, $sindent) = line_stats("+" . $s);
2395 my $stat_real = raw_line($linenr, $cond_lines);
2397 # Check if either of these lines are modified, else
2398 # this is not this patch's fault.
2399 if (!defined($stat_real) ||
2400 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2403 if (defined($stat_real) && $cond_lines > 1) {
2404 $stat_real = "[...]\n$stat_real";
2407 #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";
2409 if ($check && (($sindent % 8) != 0 ||
2410 ($sindent <= $indent && $s ne ''))) {
2411 WARN("SUSPECT_CODE_INDENT",
2412 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2416 # Track the 'values' across context and added lines.
2417 my $opline = $line; $opline =~ s/^./ /;
2418 my ($curr_values, $curr_vars) =
2419 annotate_values($opline . "\n", $prev_values);
2420 $curr_values = $prev_values . $curr_values;
2422 my $outline = $opline; $outline =~ s/\t/ /g;
2423 print "$linenr > .$outline\n";
2424 print "$linenr > $curr_values\n";
2425 print "$linenr > $curr_vars\n";
2427 $prev_values = substr($curr_values, -1);
2429 #ignore lines not being added
2430 next if ($line =~ /^[^\+]/);
2432 # TEST: allow direct testing of the type matcher.
2434 if ($line =~ /^.\s*$Declare\s*$/) {
2436 "TEST: is type\n" . $herecurr);
2437 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2438 ERROR("TEST_NOT_TYPE",
2439 "TEST: is not type ($1 is)\n". $herecurr);
2443 # TEST: allow direct testing of the attribute matcher.
2445 if ($line =~ /^.\s*$Modifier\s*$/) {
2447 "TEST: is attr\n" . $herecurr);
2448 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2449 ERROR("TEST_NOT_ATTR",
2450 "TEST: is not attr ($1 is)\n". $herecurr);
2455 # check for initialisation to aggregates open brace on the next line
2456 if ($line =~ /^.\s*{/ &&
2457 $prevline =~ /(?:^|[^=])=\s*$/) {
2459 "that open brace { should be on the previous line\n" . $hereprev);
2463 # Checks which are anchored on the added line.
2466 # check for malformed paths in #include statements (uses RAW line)
2467 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2469 if ($path =~ m{//}) {
2470 ERROR("MALFORMED_INCLUDE",
2471 "malformed #include filename\n" . $herecurr);
2473 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2474 ERROR("UAPI_INCLUDE",
2475 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2479 # no C99 // comments
2480 if ($line =~ m{//}) {
2481 if (ERROR("C99_COMMENTS",
2482 "do not use C99 // comments\n" . $herecurr) &&
2484 my $line = $fixed[$linenr - 1];
2485 if ($line =~ /\/\/(.*)$/) {
2486 my $comment = trim($1);
2487 $fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@;
2491 # Remove C99 comments.
2493 $opline =~ s@//.*@@;
2495 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2496 # the whole statement.
2497 #print "APW <$lines[$realline_next - 1]>\n";
2498 if (defined $realline_next &&
2499 exists $lines[$realline_next - 1] &&
2500 !defined $suppress_export{$realline_next} &&
2501 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2502 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2503 # Handle definitions which produce identifiers with
2506 # EXPORT_SYMBOL(something_foo);
2508 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2509 $name =~ /^${Ident}_$2/) {
2510 #print "FOO C name<$name>\n";
2511 $suppress_export{$realline_next} = 1;
2513 } elsif ($stat !~ /(?:
2515 ^.DEFINE_$Ident\(\Q$name\E\)|
2516 ^.DECLARE_$Ident\(\Q$name\E\)|
2517 ^.LIST_HEAD\(\Q$name\E\)|
2518 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2519 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2521 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2522 $suppress_export{$realline_next} = 2;
2524 $suppress_export{$realline_next} = 1;
2527 if (!defined $suppress_export{$linenr} &&
2528 $prevline =~ /^.\s*$/ &&
2529 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2530 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2531 #print "FOO B <$lines[$linenr - 1]>\n";
2532 $suppress_export{$linenr} = 2;
2534 if (defined $suppress_export{$linenr} &&
2535 $suppress_export{$linenr} == 2) {
2536 WARN("EXPORT_SYMBOL",
2537 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2540 # check for global initialisers.
2541 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
2542 if (ERROR("GLOBAL_INITIALISERS",
2543 "do not initialise globals to 0 or NULL\n" .
2546 $fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
2549 # check for static initialisers.
2550 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2551 if (ERROR("INITIALISED_STATIC",
2552 "do not initialise statics to 0 or NULL\n" .
2555 $fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
2559 # check for static const char * arrays.
2560 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2561 WARN("STATIC_CONST_CHAR_ARRAY",
2562 "static const char * array should probably be static const char * const\n" .
2566 # check for static char foo[] = "bar" declarations.
2567 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2568 WARN("STATIC_CONST_CHAR_ARRAY",
2569 "static char array declaration should probably be static const char\n" .
2573 # check for declarations of struct pci_device_id
2574 if ($line =~ /\bstruct\s+pci_device_id\s+\w+\s*\[\s*\]\s*\=\s*\{/) {
2575 WARN("DEFINE_PCI_DEVICE_TABLE",
2576 "Use DEFINE_PCI_DEVICE_TABLE for struct pci_device_id\n" . $herecurr);
2579 # check for new typedefs, only function parameters and sparse annotations
2581 if ($line =~ /\btypedef\s/ &&
2582 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2583 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2584 $line !~ /\b$typeTypedefs\b/ &&
2585 $line !~ /\b__bitwise(?:__|)\b/) {
2586 WARN("NEW_TYPEDEFS",
2587 "do not add new typedefs\n" . $herecurr);
2590 # * goes on variable not on type
2592 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2594 my ($ident, $from, $to) = ($1, $2, $2);
2596 # Should start with a space.
2597 $to =~ s/^(\S)/ $1/;
2598 # Should not end with a space.
2600 # '*'s should not have spaces between.
2601 while ($to =~ s/\*\s+\*/\*\*/) {
2604 ## print "1: from<$from> to<$to> ident<$ident>\n";
2606 if (ERROR("POINTER_LOCATION",
2607 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
2609 my $sub_from = $ident;
2610 my $sub_to = $ident;
2611 $sub_to =~ s/\Q$from\E/$to/;
2612 $fixed[$linenr - 1] =~
2613 s@\Q$sub_from\E@$sub_to@;
2617 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2619 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
2621 # Should start with a space.
2622 $to =~ s/^(\S)/ $1/;
2623 # Should not end with a space.
2625 # '*'s should not have spaces between.
2626 while ($to =~ s/\*\s+\*/\*\*/) {
2628 # Modifiers should have spaces.
2629 $to =~ s/(\b$Modifier$)/$1 /;
2631 ## print "2: from<$from> to<$to> ident<$ident>\n";
2632 if ($from ne $to && $ident !~ /^$Modifier$/) {
2633 if (ERROR("POINTER_LOCATION",
2634 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
2637 my $sub_from = $match;
2638 my $sub_to = $match;
2639 $sub_to =~ s/\Q$from\E/$to/;
2640 $fixed[$linenr - 1] =~
2641 s@\Q$sub_from\E@$sub_to@;
2646 # # no BUG() or BUG_ON()
2647 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
2648 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2649 # print "$herecurr";
2653 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2654 WARN("LINUX_VERSION_CODE",
2655 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2658 # check for uses of printk_ratelimit
2659 if ($line =~ /\bprintk_ratelimit\s*\(/) {
2660 WARN("PRINTK_RATELIMITED",
2661 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2664 # printk should use KERN_* levels. Note that follow on printk's on the
2665 # same line do not need a level, so we use the current block context
2666 # to try and find and validate the current printk. In summary the current
2667 # printk includes all preceding printk's which have no newline on the end.
2668 # we assume the first bad printk is the one to report.
2669 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2671 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2672 #print "CHECK<$lines[$ln - 1]\n";
2673 # we have a preceding printk if it ends
2674 # with "\n" ignore it, else it is to blame
2675 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2676 if ($rawlines[$ln - 1] !~ m{\\n"}) {
2683 WARN("PRINTK_WITHOUT_KERN_LEVEL",
2684 "printk() should include KERN_ facility level\n" . $herecurr);
2688 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
2690 my $level = lc($orig);
2691 $level = "warn" if ($level eq "warning");
2692 my $level2 = $level;
2693 $level2 = "dbg" if ($level eq "debug");
2694 WARN("PREFER_PR_LEVEL",
2695 "Prefer netdev_$level2(netdev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
2698 if ($line =~ /\bpr_warning\s*\(/) {
2699 if (WARN("PREFER_PR_LEVEL",
2700 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
2702 $fixed[$linenr - 1] =~
2703 s/\bpr_warning\b/pr_warn/;
2707 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
2709 my $level = lc($orig);
2710 $level = "warn" if ($level eq "warning");
2711 $level = "dbg" if ($level eq "debug");
2712 WARN("PREFER_DEV_LEVEL",
2713 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
2716 # function brace can't be on same line, except for #defines of do while,
2717 # or if closed on same line
2718 if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
2719 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
2721 "open brace '{' following function declarations go on the next line\n" . $herecurr);
2724 # open braces for enum, union and struct go on the same line.
2725 if ($line =~ /^.\s*{/ &&
2726 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2728 "open brace '{' following $1 go on the same line\n" . $hereprev);
2731 # missing space after union, struct or enum definition
2732 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
2734 "missing space after $1 definition\n" . $herecurr) &&
2736 $fixed[$linenr - 1] =~
2737 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
2741 # check for spacing round square brackets; allowed:
2742 # 1. with a type on the left -- int [] a;
2743 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2744 # 3. inside a curly brace -- = { [0...10] = 5 }
2745 while ($line =~ /(.*?\s)\[/g) {
2746 my ($where, $prefix) = ($-[1], $1);
2747 if ($prefix !~ /$Type\s+$/ &&
2748 ($where != 0 || $prefix !~ /^.\s+$/) &&
2749 $prefix !~ /[{,]\s+$/) {
2750 if (ERROR("BRACKET_SPACE",
2751 "space prohibited before open square bracket '['\n" . $herecurr) &&
2753 $fixed[$linenr - 1] =~
2754 s/^(\+.*?)\s+\[/$1\[/;
2759 # check for spaces between functions and their parentheses.
2760 while ($line =~ /($Ident)\s+\(/g) {
2762 my $ctx_before = substr($line, 0, $-[1]);
2763 my $ctx = "$ctx_before$name";
2765 # Ignore those directives where spaces _are_ permitted.
2767 if|for|while|switch|return|case|
2768 volatile|__volatile__|
2769 __attribute__|format|__extension__|
2772 # cpp #define statements have non-optional spaces, ie
2773 # if there is a space between the name and the open
2774 # parenthesis it is simply not a parameter group.
2775 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2777 # cpp #elif statement condition may start with a (
2778 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2780 # If this whole things ends with a type its most
2781 # likely a typedef for a function.
2782 } elsif ($ctx =~ /$Type$/) {
2786 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
2788 $fixed[$linenr - 1] =~
2789 s/\b$name\s+\(/$name\(/;
2794 # Check operator spacing.
2795 if (!($line=~/\#\s*include/)) {
2796 my $fixed_line = "";
2800 <<=|>>=|<=|>=|==|!=|
2801 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2802 =>|->|<<|>>|<|>|=|!|~|
2803 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2806 my @elements = split(/($ops|;)/, $opline);
2808 ## print("element count: <" . $#elements . ">\n");
2809 ## foreach my $el (@elements) {
2810 ## print("el: <$el>\n");
2813 my @fix_elements = ();
2816 foreach my $el (@elements) {
2817 push(@fix_elements, substr($rawline, $off, length($el)));
2818 $off += length($el);
2823 my $blank = copy_spacing($opline);
2825 for (my $n = 0; $n < $#elements; $n += 2) {
2827 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
2829 ## print("n: <$n> good: <$good>\n");
2831 $off += length($elements[$n]);
2833 # Pick up the preceding and succeeding characters.
2834 my $ca = substr($opline, 0, $off);
2836 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2837 $cc = substr($opline, $off + length($elements[$n + 1]));
2839 my $cb = "$ca$;$cc";
2842 $a = 'V' if ($elements[$n] ne '');
2843 $a = 'W' if ($elements[$n] =~ /\s$/);
2844 $a = 'C' if ($elements[$n] =~ /$;$/);
2845 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2846 $a = 'O' if ($elements[$n] eq '');
2847 $a = 'E' if ($ca =~ /^\s*$/);
2849 my $op = $elements[$n + 1];
2852 if (defined $elements[$n + 2]) {
2853 $c = 'V' if ($elements[$n + 2] ne '');
2854 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2855 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2856 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2857 $c = 'O' if ($elements[$n + 2] eq '');
2858 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2863 my $ctx = "${a}x${c}";
2865 my $at = "(ctx:$ctx)";
2867 my $ptr = substr($blank, 0, $off) . "^";
2868 my $hereptr = "$hereline$ptr\n";
2870 # Pull out the value of this operator.
2871 my $op_type = substr($curr_values, $off + 1, 1);
2873 # Get the full operator variant.
2874 my $opv = $op . substr($curr_vars, $off, 1);
2876 # Ignore operators passed as parameters.
2877 if ($op_type ne 'V' &&
2878 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2881 # } elsif ($op =~ /^$;+$/) {
2883 # ; should have either the end of line or a space or \ after it
2884 } elsif ($op eq ';') {
2885 if ($ctx !~ /.x[WEBC]/ &&
2886 $cc !~ /^\\/ && $cc !~ /^;/) {
2887 if (ERROR("SPACING",
2888 "space required after that '$op' $at\n" . $hereptr)) {
2889 $good = trim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
2895 } elsif ($op eq '//') {
2899 # : when part of a bitfield
2900 } elsif ($op eq '->' || $opv eq ':B') {
2901 if ($ctx =~ /Wx.|.xW/) {
2902 if (ERROR("SPACING",
2903 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
2904 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2906 if (defined $fix_elements[$n + 2]) {
2907 $fix_elements[$n + 2] =~ s/^\s+//;
2912 # , must have a space on the right.
2913 } elsif ($op eq ',') {
2914 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
2915 if (ERROR("SPACING",
2916 "space required after that '$op' $at\n" . $hereptr)) {
2917 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]) . " ";
2922 # '*' as part of a type definition -- reported already.
2923 } elsif ($opv eq '*_') {
2924 #warn "'*' is part of type\n";
2926 # unary operators should have a space before and
2927 # none after. May be left adjacent to another
2928 # unary operator, or a cast
2929 } elsif ($op eq '!' || $op eq '~' ||
2930 $opv eq '*U' || $opv eq '-U' ||
2931 $opv eq '&U' || $opv eq '&&U') {
2932 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2933 if (ERROR("SPACING",
2934 "space required before that '$op' $at\n" . $hereptr)) {
2935 $good = trim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
2939 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2940 # A unary '*' may be const
2942 } elsif ($ctx =~ /.xW/) {
2943 if (ERROR("SPACING",
2944 "space prohibited after that '$op' $at\n" . $hereptr)) {
2945 $fixed_line =~ s/\s+$//;
2946 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2948 if (defined $fix_elements[$n + 2]) {
2949 $fix_elements[$n + 2] =~ s/^\s+//;
2954 # unary ++ and unary -- are allowed no space on one side.
2955 } elsif ($op eq '++' or $op eq '--') {
2956 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2957 if (ERROR("SPACING",
2958 "space required one side of that '$op' $at\n" . $hereptr)) {
2959 $fixed_line =~ s/\s+$//;
2960 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]) . " ";
2964 if ($ctx =~ /Wx[BE]/ ||
2965 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2966 if (ERROR("SPACING",
2967 "space prohibited before that '$op' $at\n" . $hereptr)) {
2968 $fixed_line =~ s/\s+$//;
2969 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2973 if ($ctx =~ /ExW/) {
2974 if (ERROR("SPACING",
2975 "space prohibited after that '$op' $at\n" . $hereptr)) {
2976 $fixed_line =~ s/\s+$//;
2977 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2979 if (defined $fix_elements[$n + 2]) {
2980 $fix_elements[$n + 2] =~ s/^\s+//;
2985 # << and >> may either have or not have spaces both sides
2986 } elsif ($op eq '<<' or $op eq '>>' or
2987 $op eq '&' or $op eq '^' or $op eq '|' or
2988 $op eq '+' or $op eq '-' or
2989 $op eq '*' or $op eq '/' or
2992 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
2993 if (ERROR("SPACING",
2994 "need consistent spacing around '$op' $at\n" . $hereptr)) {
2995 $fixed_line =~ s/\s+$//;
2996 $good = trim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3001 # A colon needs no spaces before when it is
3002 # terminating a case value or a label.
3003 } elsif ($opv eq ':C' || $opv eq ':L') {
3004 if ($ctx =~ /Wx./) {
3005 if (ERROR("SPACING",
3006 "space prohibited before that '$op' $at\n" . $hereptr)) {
3007 $good = trim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3012 # All the others need spaces both sides.
3013 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3016 # Ignore email addresses <foo@bar>
3018 $cc =~ /^\S+\@\S+>/) ||
3020 $ca =~ /<\S+\@\S+$/))
3026 if (($opv eq ':O' && $ca =~ /\?$/) ||
3027 ($op eq '?' && $cc =~ /^:/)) {
3032 if (ERROR("SPACING",
3033 "spaces required around that '$op' $at\n" . $hereptr)) {
3034 $good = trim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3035 $good = $fix_elements[$n] . " " . trim($fix_elements[$n + 1]) . " ";
3040 $off += length($elements[$n + 1]);
3042 ## print("n: <$n> GOOD: <$good>\n");
3044 $fixed_line = $fixed_line . $good;
3047 if (($#elements % 2) == 0) {
3048 $fixed_line = $fixed_line . $fix_elements[$#elements];
3051 if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) {
3052 $fixed[$linenr - 1] = $fixed_line;
3058 # check for whitespace before a non-naked semicolon
3059 if ($line =~ /^\+.*\S\s+;/) {
3061 "space prohibited before semicolon\n" . $herecurr) &&
3063 1 while $fixed[$linenr - 1] =~
3064 s/^(\+.*\S)\s+;/$1;/;
3068 # check for multiple assignments
3069 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3070 CHK("MULTIPLE_ASSIGNMENTS",
3071 "multiple assignments should be avoided\n" . $herecurr);
3074 ## # check for multiple declarations, allowing for a function declaration
3076 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3077 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3079 ## # Remove any bracketed sections to ensure we do not
3080 ## # falsly report the parameters of functions.
3082 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3084 ## if ($ln =~ /,/) {
3085 ## WARN("MULTIPLE_DECLARATION",
3086 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3090 #need space before brace following if, while, etc
3091 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3093 if (ERROR("SPACING",
3094 "space required before the open brace '{'\n" . $herecurr) &&
3096 $fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/;
3100 ## # check for blank lines before declarations
3101 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3102 ## $prevrawline =~ /^.\s*$/) {
3104 ## "No blank lines before declarations\n" . $hereprev);
3108 # closing brace should have a space following it when it has anything
3110 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3111 if (ERROR("SPACING",
3112 "space required after that close brace '}'\n" . $herecurr) &&
3114 $fixed[$linenr - 1] =~
3115 s/}((?!(?:,|;|\)))\S)/} $1/;
3119 # check spacing on square brackets
3120 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3121 if (ERROR("SPACING",
3122 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3124 $fixed[$linenr - 1] =~
3128 if ($line =~ /\s\]/) {
3129 if (ERROR("SPACING",
3130 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3132 $fixed[$linenr - 1] =~
3137 # check spacing on parentheses
3138 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3139 $line !~ /for\s*\(\s+;/) {
3140 if (ERROR("SPACING",
3141 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3143 $fixed[$linenr - 1] =~
3147 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3148 $line !~ /for\s*\(.*;\s+\)/ &&
3149 $line !~ /:\s+\)/) {
3150 if (ERROR("SPACING",
3151 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3153 $fixed[$linenr - 1] =~
3158 #goto labels aren't indented, allow a single space however
3159 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3160 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3161 if (WARN("INDENTED_LABEL",
3162 "labels should not be indented\n" . $herecurr) &&
3164 $fixed[$linenr - 1] =~
3169 # Return is not a function.
3170 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
3174 # Flatten any parentheses
3175 $value =~ s/\(/ \(/g;
3176 $value =~ s/\)/\) /g;
3177 while ($value =~ s/\[[^\[\]]*\]/1/ ||
3178 $value !~ /(?:$Ident|-?$Constant)\s*
3180 (?:$Ident|-?$Constant)/x &&
3181 $value =~ s/\([^\(\)]*\)/1/) {
3183 #print "value<$value>\n";
3184 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
3185 ERROR("RETURN_PARENTHESES",
3186 "return is not a function, parentheses are not required\n" . $herecurr);
3188 } elsif ($spacing !~ /\s+/) {
3190 "space required before the open parenthesis '('\n" . $herecurr);
3193 # Return of what appears to be an errno should normally be -'ve
3194 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3196 if ($name ne 'EOF' && $name ne 'ERROR') {
3197 WARN("USE_NEGATIVE_ERRNO",
3198 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3202 # Need a space before open parenthesis after if, while etc
3203 if ($line =~ /\b(if|while|for|switch)\(/) {
3204 if (ERROR("SPACING",
3205 "space required before the open parenthesis '('\n" . $herecurr) &&
3207 $fixed[$linenr - 1] =~
3208 s/\b(if|while|for|switch)\(/$1 \(/;
3212 # Check for illegal assignment in if conditional -- and check for trailing
3213 # statements after the conditional.
3214 if ($line =~ /do\s*(?!{)/) {
3215 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3216 ctx_statement_block($linenr, $realcnt, 0)
3217 if (!defined $stat);
3218 my ($stat_next) = ctx_statement_block($line_nr_next,
3219 $remain_next, $off_next);
3220 $stat_next =~ s/\n./\n /g;
3221 ##print "stat<$stat> stat_next<$stat_next>\n";
3223 if ($stat_next =~ /^\s*while\b/) {
3224 # If the statement carries leading newlines,
3225 # then count those as offsets.
3227 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3229 statement_rawlines($whitespace) - 1;
3231 $suppress_whiletrailers{$line_nr_next +
3235 if (!defined $suppress_whiletrailers{$linenr} &&
3236 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3237 my ($s, $c) = ($stat, $cond);
3239 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3240 ERROR("ASSIGN_IN_IF",
3241 "do not use assignment in if condition\n" . $herecurr);
3244 # Find out what is on the end of the line after the
3246 substr($s, 0, length($c), '');
3248 $s =~ s/$;//g; # Remove any comments
3249 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3250 $c !~ /}\s*while\s*/)
3252 # Find out how long the conditional actually is.
3253 my @newlines = ($c =~ /\n/gs);
3254 my $cond_lines = 1 + $#newlines;
3257 $stat_real = raw_line($linenr, $cond_lines)
3258 . "\n" if ($cond_lines);
3259 if (defined($stat_real) && $cond_lines > 1) {
3260 $stat_real = "[...]\n$stat_real";
3263 ERROR("TRAILING_STATEMENTS",
3264 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3268 # Check for bitwise tests written as boolean
3280 WARN("HEXADECIMAL_BOOLEAN_TEST",
3281 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3284 # if and else should not have general statements after it
3285 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3287 $s =~ s/$;//g; # Remove any comments
3288 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3289 ERROR("TRAILING_STATEMENTS",
3290 "trailing statements should be on next line\n" . $herecurr);
3293 # if should not continue a brace
3294 if ($line =~ /}\s*if\b/) {
3295 ERROR("TRAILING_STATEMENTS",
3296 "trailing statements should be on next line\n" .
3299 # case and default should not have general statements after them
3300 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
3302 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
3306 ERROR("TRAILING_STATEMENTS",
3307 "trailing statements should be on next line\n" . $herecurr);
3310 # Check for }<nl>else {, these must be at the same
3311 # indent level to be relevant to each other.
3312 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
3313 $previndent == $indent) {
3314 ERROR("ELSE_AFTER_BRACE",
3315 "else should follow close brace '}'\n" . $hereprev);
3318 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
3319 $previndent == $indent) {
3320 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
3322 # Find out what is on the end of the line after the
3324 substr($s, 0, length($c), '');
3327 if ($s =~ /^\s*;/) {
3328 ERROR("WHILE_AFTER_BRACE",
3329 "while should follow close brace '}'\n" . $hereprev);
3333 #Specific variable tests
3334 while ($line =~ m{($Constant|$Lval)}g) {
3337 #gcc binary extension
3338 if ($var =~ /^$Binary$/) {
3339 if (WARN("GCC_BINARY_CONSTANT",
3340 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
3342 my $hexval = sprintf("0x%x", oct($var));
3343 $fixed[$linenr - 1] =~
3344 s/\b$var\b/$hexval/;
3349 if ($var !~ /^$Constant$/ &&
3350 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
3351 #Ignore Page<foo> variants
3352 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
3353 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
3354 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) {
3355 while ($var =~ m{($Ident)}g) {
3357 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
3358 seed_camelcase_includes() if ($check);
3359 if (!defined $camelcase{$word}) {
3360 $camelcase{$word} = 1;
3362 "Avoid CamelCase: <$word>\n" . $herecurr);
3368 #no spaces allowed after \ in define
3369 if ($line =~ /\#\s*define.*\\\s+$/) {
3370 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
3371 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
3373 $fixed[$linenr - 1] =~ s/\s+$//;
3377 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
3378 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
3380 my $checkfile = "include/linux/$file";
3381 if (-f "$root/$checkfile" &&
3382 $realfile ne $checkfile &&
3383 $1 !~ /$allowed_asm_includes/)
3385 if ($realfile =~ m{^arch/}) {
3386 CHK("ARCH_INCLUDE_LINUX",
3387 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3389 WARN("INCLUDE_LINUX",
3390 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3395 # multi-statement macros should be enclosed in a do while loop, grab the
3396 # first statement and ensure its the whole macro if its not enclosed
3397 # in a known good container
3398 if ($realfile !~ m@/vmlinux.lds.h$@ &&
3399 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
3402 my ($off, $dstat, $dcond, $rest);
3404 ($dstat, $dcond, $ln, $cnt, $off) =
3405 ctx_statement_block($linenr, $realcnt, 0);
3407 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
3408 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
3410 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
3412 $dstat =~ s/\\\n.//g;
3413 $dstat =~ s/^\s*//s;
3414 $dstat =~ s/\s*$//s;
3416 # Flatten any parentheses and braces
3417 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
3418 $dstat =~ s/\{[^\{\}]*\}/1/ ||
3419 $dstat =~ s/\[[^\[\]]*\]/1/)
3423 # Flatten any obvious string concatentation.
3424 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
3425 $dstat =~ s/$Ident\s*("X*")/$1/)
3429 my $exceptions = qr{
3441 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
3443 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
3444 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
3445 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
3446 $dstat !~ /^'X'$/ && # character constants
3447 $dstat !~ /$exceptions/ &&
3448 $dstat !~ /^\.$Ident\s*=/ && # .foo =
3449 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
3450 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
3451 $dstat !~ /^for\s*$Constant$/ && # for (...)
3452 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
3453 $dstat !~ /^do\s*{/ && # do {...
3454 $dstat !~ /^\({/) # ({...
3457 my $herectx = $here . "\n";
3458 my $cnt = statement_rawlines($ctx);
3460 for (my $n = 0; $n < $cnt; $n++) {
3461 $herectx .= raw_line($linenr, $n) . "\n";
3464 if ($dstat =~ /;/) {
3465 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
3466 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
3468 ERROR("COMPLEX_MACRO",
3469 "Macros with complex values should be enclosed in parenthesis\n" . "$herectx");
3473 # check for line continuations outside of #defines, preprocessor #, and asm
3476 if ($prevline !~ /^..*\\$/ &&
3477 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
3478 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
3479 $line =~ /^\+.*\\$/) {
3480 WARN("LINE_CONTINUATIONS",
3481 "Avoid unnecessary line continuations\n" . $herecurr);
3485 # do {} while (0) macro tests:
3486 # single-statement macros do not need to be enclosed in do while (0) loop,
3487 # macro should not end with a semicolon
3488 if ($^V && $^V ge 5.10.0 &&
3489 $realfile !~ m@/vmlinux.lds.h$@ &&
3490 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
3493 my ($off, $dstat, $dcond, $rest);
3495 ($dstat, $dcond, $ln, $cnt, $off) =
3496 ctx_statement_block($linenr, $realcnt, 0);
3499 $dstat =~ s/\\\n.//g;
3501 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
3506 my $cnt = statement_rawlines($ctx);
3507 my $herectx = $here . "\n";
3509 for (my $n = 0; $n < $cnt; $n++) {
3510 $herectx .= raw_line($linenr, $n) . "\n";
3513 if (($stmts =~ tr/;/;/) == 1 &&
3514 $stmts !~ /^\s*(if|while|for|switch)\b/) {
3515 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
3516 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
3518 if (defined $semis && $semis ne "") {
3519 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
3520 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
3525 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
3526 # all assignments may have only one of the following with an assignment:
3529 # VMLINUX_SYMBOL(...)
3530 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
3531 WARN("MISSING_VMLINUX_SYMBOL",
3532 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
3535 # check for redundant bracing round if etc
3536 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
3537 my ($level, $endln, @chunks) =
3538 ctx_statement_full($linenr, $realcnt, 1);
3539 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
3540 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
3541 if ($#chunks > 0 && $level == 0) {
3545 my $herectx = $here . "\n";
3546 my $ln = $linenr - 1;
3547 for my $chunk (@chunks) {
3548 my ($cond, $block) = @{$chunk};
3550 # If the condition carries leading newlines, then count those as offsets.
3551 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
3552 my $offset = statement_rawlines($whitespace) - 1;
3554 $allowed[$allow] = 0;
3555 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
3557 # We have looked at and allowed this specific line.
3558 $suppress_ifbraces{$ln + $offset} = 1;
3560 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3561 $ln += statement_rawlines($block) - 1;
3563 substr($block, 0, length($cond), '');
3565 $seen++ if ($block =~ /^\s*{/);
3567 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
3568 if (statement_lines($cond) > 1) {
3569 #print "APW: ALLOWED: cond<$cond>\n";
3570 $allowed[$allow] = 1;
3572 if ($block =~/\b(?:if|for|while)\b/) {
3573 #print "APW: ALLOWED: block<$block>\n";
3574 $allowed[$allow] = 1;
3576 if (statement_block_size($block) > 1) {
3577 #print "APW: ALLOWED: lines block<$block>\n";
3578 $allowed[$allow] = 1;
3583 my $sum_allowed = 0;
3584 foreach (@allowed) {
3587 if ($sum_allowed == 0) {
3589 "braces {} are not necessary for any arm of this statement\n" . $herectx);
3590 } elsif ($sum_allowed != $allow &&
3593 "braces {} should be used on all arms of this statement\n" . $herectx);
3598 if (!defined $suppress_ifbraces{$linenr - 1} &&
3599 $line =~ /\b(if|while|for|else)\b/) {
3602 # Check the pre-context.
3603 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3604 #print "APW: ALLOWED: pre<$1>\n";
3608 my ($level, $endln, @chunks) =
3609 ctx_statement_full($linenr, $realcnt, $-[0]);
3611 # Check the condition.
3612 my ($cond, $block) = @{$chunks[0]};
3613 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
3614 if (defined $cond) {
3615 substr($block, 0, length($cond), '');
3617 if (statement_lines($cond) > 1) {
3618 #print "APW: ALLOWED: cond<$cond>\n";
3621 if ($block =~/\b(?:if|for|while)\b/) {
3622 #print "APW: ALLOWED: block<$block>\n";
3625 if (statement_block_size($block) > 1) {
3626 #print "APW: ALLOWED: lines block<$block>\n";
3629 # Check the post-context.
3630 if (defined $chunks[1]) {
3631 my ($cond, $block) = @{$chunks[1]};
3632 if (defined $cond) {
3633 substr($block, 0, length($cond), '');
3635 if ($block =~ /^\s*\{/) {
3636 #print "APW: ALLOWED: chunk-1 block<$block>\n";
3640 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
3641 my $herectx = $here . "\n";
3642 my $cnt = statement_rawlines($block);
3644 for (my $n = 0; $n < $cnt; $n++) {
3645 $herectx .= raw_line($linenr, $n) . "\n";
3649 "braces {} are not necessary for single statement blocks\n" . $herectx);
3653 # check for unnecessary blank lines around braces
3654 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
3656 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
3658 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
3660 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
3663 # no volatiles please
3664 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3665 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
3667 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
3671 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3672 CHK("REDUNDANT_CODE",
3673 "if this code is redundant consider removing it\n" .
3677 # check for needless "if (<foo>) fn(<foo>)" uses
3678 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
3679 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
3680 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
3682 "$1(NULL) is safe this check is probably not required\n" . $hereprev);
3686 # prefer usleep_range over udelay
3687 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
3688 # ignore udelay's < 10, however
3691 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
3695 # warn about unexpectedly long msleep's
3696 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
3699 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
3703 # check for comparisons of jiffies
3704 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
3705 WARN("JIFFIES_COMPARISON",
3706 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
3709 # check for comparisons of get_jiffies_64()
3710 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
3711 WARN("JIFFIES_COMPARISON",
3712 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
3715 # warn about #ifdefs in C files
3716 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3717 # print "#ifdef in C files should be avoided\n";
3718 # print "$herecurr";
3722 # warn about spacing in #ifdefs
3723 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3724 if (ERROR("SPACING",
3725 "exactly one space required after that #$1\n" . $herecurr) &&
3727 $fixed[$linenr - 1] =~
3728 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
3733 # check for spinlock_t definitions without a comment.
3734 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
3735 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
3737 if (!ctx_has_comment($first_line, $linenr)) {
3738 CHK("UNCOMMENTED_DEFINITION",
3739 "$1 definition without comment\n" . $herecurr);
3742 # check for memory barriers without a comment.
3743 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
3744 if (!ctx_has_comment($first_line, $linenr)) {
3745 CHK("MEMORY_BARRIER",
3746 "memory barrier without comment\n" . $herecurr);
3749 # check of hardware specific defines
3750 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
3752 "architecture specific defines should be avoided\n" . $herecurr);
3755 # Check that the storage class is at the beginning of a declaration
3756 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
3757 WARN("STORAGE_CLASS",
3758 "storage class should be at the beginning of the declaration\n" . $herecurr)
3761 # check the location of the inline attribute, that it is between
3762 # storage class and type.
3763 if ($line =~ /\b$Type\s+$Inline\b/ ||
3764 $line =~ /\b$Inline\s+$Storage\b/) {
3765 ERROR("INLINE_LOCATION",
3766 "inline keyword should sit between storage class and type\n" . $herecurr);
3769 # Check for __inline__ and __inline, prefer inline
3770 if ($line =~ /\b(__inline__|__inline)\b/) {
3772 "plain inline is preferred over $1\n" . $herecurr) &&
3774 $fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/;
3779 # Check for __attribute__ packed, prefer __packed
3780 if ($line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
3781 WARN("PREFER_PACKED",
3782 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
3785 # Check for __attribute__ aligned, prefer __aligned
3786 if ($line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
3787 WARN("PREFER_ALIGNED",
3788 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
3791 # Check for __attribute__ format(printf, prefer __printf
3792 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
3793 if (WARN("PREFER_PRINTF",
3794 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
3796 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
3801 # Check for __attribute__ format(scanf, prefer __scanf
3802 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
3803 if (WARN("PREFER_SCANF",
3804 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
3806 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
3810 # check for sizeof(&)
3811 if ($line =~ /\bsizeof\s*\(\s*\&/) {
3812 WARN("SIZEOF_ADDRESS",
3813 "sizeof(& should be avoided\n" . $herecurr);
3816 # check for sizeof without parenthesis
3817 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
3818 if (WARN("SIZEOF_PARENTHESIS",
3819 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
3821 $fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
3825 # check for line continuations in quoted strings with odd counts of "
3826 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
3827 WARN("LINE_CONTINUATIONS",
3828 "Avoid line continuations in quoted strings\n" . $herecurr);
3831 # check for struct spinlock declarations
3832 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
3833 WARN("USE_SPINLOCK_T",
3834 "struct spinlock should be spinlock_t\n" . $herecurr);
3837 # check for seq_printf uses that could be seq_puts
3838 if ($line =~ /\bseq_printf\s*\(/) {
3839 my $fmt = get_quoted_string($line, $rawline);
3840 if ($fmt !~ /[^\\]\%/) {
3841 if (WARN("PREFER_SEQ_PUTS",
3842 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
3844 $fixed[$linenr - 1] =~ s/\bseq_printf\b/seq_puts/;
3849 # Check for misused memsets
3850 if ($^V && $^V ge 5.10.0 &&
3852 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
3858 if ($ms_size =~ /^(0x|)0$/i) {
3860 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
3861 } elsif ($ms_size =~ /^(0x|)1$/i) {
3863 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
3867 # typecasts on min/max could be min_t/max_t
3868 if ($^V && $^V ge 5.10.0 &&
3870 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
3871 if (defined $2 || defined $7) {
3873 my $cast1 = deparenthesize($2);
3875 my $cast2 = deparenthesize($7);
3879 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
3880 $cast = "$cast1 or $cast2";
3881 } elsif ($cast1 ne "") {
3887 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
3891 # check usleep_range arguments
3892 if ($^V && $^V ge 5.10.0 &&
3894 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
3898 WARN("USLEEP_RANGE",
3899 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3900 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
3902 WARN("USLEEP_RANGE",
3903 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3907 # check for new externs in .h files.
3908 if ($realfile =~ /\.h$/ &&
3909 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
3910 if (WARN("AVOID_EXTERNS",
3911 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
3913 $fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
3917 # check for new externs in .c files.
3918 if ($realfile =~ /\.c$/ && defined $stat &&
3919 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
3921 my $function_name = $1;
3922 my $paren_space = $2;
3925 if (defined $cond) {
3926 substr($s, 0, length($cond), '');
3928 if ($s =~ /^\s*;/ &&
3929 $function_name ne 'uninitialized_var')
3931 WARN("AVOID_EXTERNS",
3932 "externs should be avoided in .c files\n" . $herecurr);
3935 if ($paren_space =~ /\n/) {
3936 WARN("FUNCTION_ARGUMENTS",
3937 "arguments for function declarations should follow identifier\n" . $herecurr);
3940 } elsif ($realfile =~ /\.c$/ && defined $stat &&
3941 $stat =~ /^.\s*extern\s+/)
3943 WARN("AVOID_EXTERNS",
3944 "externs should be avoided in .c files\n" . $herecurr);
3947 # checks for new __setup's
3948 if ($rawline =~ /\b__setup\("([^"]*)"/) {
3951 if (!grep(/$name/, @setup_docs)) {
3952 CHK("UNDOCUMENTED_SETUP",
3953 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
3957 # check for pointless casting of kmalloc return
3958 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
3959 WARN("UNNECESSARY_CASTS",
3960 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
3964 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
3965 if ($^V && $^V ge 5.10.0 &&
3966 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
3967 CHK("ALLOC_SIZEOF_STRUCT",
3968 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
3971 # check for krealloc arg reuse
3972 if ($^V && $^V ge 5.10.0 &&
3973 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
3974 WARN("KREALLOC_ARG_REUSE",
3975 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
3978 # check for alloc argument mismatch
3979 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
3980 WARN("ALLOC_ARRAY_ARGS",
3981 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
3984 # check for multiple semicolons
3985 if ($line =~ /;\s*;\s*$/) {
3986 if (WARN("ONE_SEMICOLON",
3987 "Statements terminations use 1 semicolon\n" . $herecurr) &&
3989 $fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g;
3993 # check for switch/default statements without a break;
3994 if ($^V && $^V ge 5.10.0 &&
3996 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
3998 my $herectx = $here . "\n";
3999 my $cnt = statement_rawlines($stat);
4000 for (my $n = 0; $n < $cnt; $n++) {
4001 $herectx .= raw_line($linenr, $n) . "\n";
4003 WARN("DEFAULT_NO_BREAK",
4004 "switch default: should use break\n" . $herectx);
4007 # check for gcc specific __FUNCTION__
4008 if ($line =~ /\b__FUNCTION__\b/) {
4009 if (WARN("USE_FUNC",
4010 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
4012 $fixed[$linenr - 1] =~ s/\b__FUNCTION__\b/__func__/g;
4016 # check for use of yield()
4017 if ($line =~ /\byield\s*\(\s*\)/) {
4019 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
4022 # check for comparisons against true and false
4023 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
4031 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
4033 my $type = lc($otype);
4034 if ($type =~ /^(?:true|false)$/) {
4035 if (("$test" eq "==" && "$type" eq "true") ||
4036 ("$test" eq "!=" && "$type" eq "false")) {
4040 CHK("BOOL_COMPARISON",
4041 "Using comparison to $otype is error prone\n" . $herecurr);
4043 ## maybe suggesting a correct construct would better
4044 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
4049 # check for semaphores initialized locked
4050 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
4051 WARN("CONSIDER_COMPLETION",
4052 "consider using a completion\n" . $herecurr);
4055 # recommend kstrto* over simple_strto* and strict_strto*
4056 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
4057 WARN("CONSIDER_KSTRTO",
4058 "$1 is obsolete, use k$3 instead\n" . $herecurr);
4061 # check for __initcall(), use device_initcall() explicitly please
4062 if ($line =~ /^.\s*__initcall\s*\(/) {
4063 WARN("USE_DEVICE_INITCALL",
4064 "please use device_initcall() instead of __initcall()\n" . $herecurr);
4067 # check for various ops structs, ensure they are const.
4068 my $struct_ops = qr{acpi_dock_ops|
4069 address_space_operations|
4071 block_device_operations|
4076 file_lock_operations|
4086 lock_manager_operations|
4092 pipe_buf_operations|
4093 platform_hibernation_ops|
4094 platform_suspend_ops|
4099 soc_pcmcia_socket_ops|
4105 if ($line !~ /\bconst\b/ &&
4106 $line =~ /\bstruct\s+($struct_ops)\b/) {
4107 WARN("CONST_STRUCT",
4108 "struct $1 should normally be const\n" .
4112 # use of NR_CPUS is usually wrong
4113 # ignore definitions of NR_CPUS and usage to define arrays as likely right
4114 if ($line =~ /\bNR_CPUS\b/ &&
4115 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
4116 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
4117 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
4118 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
4119 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
4122 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
4125 # check for %L{u,d,i} in strings
4127 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4128 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4129 $string =~ s/%%/__/g;
4130 if ($string =~ /(?<!%)%L[udi]/) {
4132 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4137 # whine mightly about in_atomic
4138 if ($line =~ /\bin_atomic\s*\(/) {
4139 if ($realfile =~ m@^drivers/@) {
4141 "do not use in_atomic in drivers\n" . $herecurr);
4142 } elsif ($realfile !~ m@^kernel/@) {
4144 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
4148 # check for lockdep_set_novalidate_class
4149 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
4150 $line =~ /__lockdep_no_validate__\s*\)/ ) {
4151 if ($realfile !~ m@^kernel/lockdep@ &&
4152 $realfile !~ m@^include/linux/lockdep@ &&
4153 $realfile !~ m@^drivers/base/core@) {
4155 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
4159 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
4160 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
4161 WARN("EXPORTED_WORLD_WRITABLE",
4162 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
4166 # If we have no input at all, then there is nothing to report on
4167 # so just keep quiet.
4168 if ($#rawlines == -1) {
4172 # In mailback mode only produce a report in the negative, for
4173 # things that appear to be patches.
4174 if ($mailback && ($clean == 1 || !$is_patch)) {
4178 # This is not a patch, and we are are in 'no-patch' mode so
4180 if (!$chk_patch && !$is_patch) {
4185 ERROR("NOT_UNIFIED_DIFF",
4186 "Does not appear to be a unified-diff format patch\n");
4188 if ($is_patch && $chk_signoff && $signoff == 0) {
4189 ERROR("MISSING_SIGN_OFF",
4190 "Missing Signed-off-by: line(s)\n");
4193 print report_dump();
4194 if ($summary && !($clean == 1 && $quiet == 1)) {
4195 print "$filename " if ($summary_file);
4196 print "total: $cnt_error errors, $cnt_warn warnings, " .
4197 (($check)? "$cnt_chk checks, " : "") .
4198 "$cnt_lines lines checked\n";
4199 print "\n" if ($quiet == 0);
4204 if ($^V lt 5.10.0) {
4205 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
4206 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
4209 # If there were whitespace errors which cleanpatch can fix
4210 # then suggest that.
4211 if ($rpt_cleaners) {
4212 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
4213 print " scripts/cleanfile\n\n";
4218 hash_show_words(\%use_type, "Used");
4219 hash_show_words(\%ignore_type, "Ignored");
4221 if ($clean == 0 && $fix && "@rawlines" ne "@fixed") {
4222 my $newfile = $filename . ".EXPERIMENTAL-checkpatch-fixes";
4226 open($f, '>', $newfile)
4227 or die "$P: Can't open $newfile for write\n";
4228 foreach my $fixed_line (@fixed) {
4231 if ($linecount > 3) {
4232 $fixed_line =~ s/^\+//;
4233 print $f $fixed_line. "\n";
4236 print $f $fixed_line . "\n";
4243 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
4245 Do _NOT_ trust the results written to this file.
4246 Do _NOT_ submit these changes without inspecting them for correctness.
4248 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
4249 No warranties, expressed or implied...
4255 if ($clean == 1 && $quiet == 0) {
4256 print "$vname has no obvious style problems and is ready for submission.\n"
4258 if ($clean == 0 && $quiet == 0) {
4260 $vname has style problems, please review.
4262 If any of these errors are false positives, please report
4263 them to the maintainer, see CHECKPATCH in MAINTAINERS.