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 our $InitAttribute = qr{__(?:mem|cpu|dev|net_|)(?:initdata|initconst|init\b)};
247 # Notes to $Attribute:
248 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
268 ____cacheline_aligned|
269 ____cacheline_aligned_in_smp|
270 ____cacheline_internodealigned_in_smp|
274 our $Inline = qr{inline|__always_inline|noinline};
275 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
276 our $Lval = qr{$Ident(?:$Member)*};
278 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
279 our $Binary = qr{(?i)0b[01]+$Int_type?};
280 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
281 our $Int = qr{[0-9]+$Int_type?};
282 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
283 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
284 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
285 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
286 our $Constant = qr{$Float|$Binary|$Hex|$Int};
287 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
288 our $Compare = qr{<=|>=|==|!=|<|>};
289 our $Arithmetic = qr{\+|-|\*|\/|%};
293 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
297 our $NonptrTypeWithAttr;
301 our $NON_ASCII_UTF8 = qr{
302 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
303 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
304 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
305 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
306 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
307 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
308 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
312 [\x09\x0A\x0D\x20-\x7E] # ASCII
316 our $typeTypedefs = qr{(?x:
317 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
321 our $logFunctions = qr{(?x:
322 printk(?:_ratelimited|_once|)|
323 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
324 WARN(?:_RATELIMIT|_ONCE|)|
329 our $signature_tags = qr{(?xi:
342 qr{(?:unsigned\s+)?char},
343 qr{(?:unsigned\s+)?short},
344 qr{(?:unsigned\s+)?int},
345 qr{(?:unsigned\s+)?long},
346 qr{(?:unsigned\s+)?long\s+int},
347 qr{(?:unsigned\s+)?long\s+long},
348 qr{(?:unsigned\s+)?long\s+long\s+int},
357 qr{${Ident}_handler},
358 qr{${Ident}_handler_fn},
360 our @typeListWithAttr = (
362 qr{struct\s+$InitAttribute\s+$Ident},
363 qr{union\s+$InitAttribute\s+$Ident},
366 our @modifierList = (
370 our $allowed_asm_includes = qr{(?x:
374 # memory.h: ARM has a custom one
377 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
378 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
379 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
380 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
382 (?:$Modifier\s+|const\s+)*
384 (?:typeof|__typeof__)\s*\([^\)]*\)|
388 (?:\s+$Modifier|\s+const)*
390 $NonptrTypeWithAttr = qr{
391 (?:$Modifier\s+|const\s+)*
393 (?:typeof|__typeof__)\s*\([^\)]*\)|
397 (?:\s+$Modifier|\s+const)*
401 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*|\[\])+|(?:\s*\[\s*\])+)?
402 (?:\s+$Inline|\s+$Modifier)*
404 $Declare = qr{(?:$Storage\s+)?$Type};
408 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
410 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
411 # requires at least perl version v5.10.0
412 # Any use must be runtime checked with $^V
414 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
415 our $LvalOrFunc = qr{($Lval)\s*($balanced_parens{0,1})\s*};
416 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
420 return "" if (!defined($string));
421 $string =~ s@^\s*\(\s*@@g;
422 $string =~ s@\s*\)\s*$@@g;
423 $string =~ s@\s+@ @g;
427 sub seed_camelcase_file {
430 return if (!(-f $file));
434 open(my $include_file, '<', "$file")
435 or warn "$P: Can't read '$file' $!\n";
436 my $text = <$include_file>;
437 close($include_file);
439 my @lines = split('\n', $text);
441 foreach my $line (@lines) {
442 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
443 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
446 elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
452 my $camelcase_seeded = 0;
453 sub seed_camelcase_includes {
454 return if ($camelcase_seeded);
457 my $camelcase_cache = "";
458 my @include_files = ();
460 $camelcase_seeded = 1;
463 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
464 chomp $git_last_include_commit;
465 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
467 my $last_mod_date = 0;
468 $files = `find $root/include -name "*.h"`;
469 @include_files = split('\n', $files);
470 foreach my $file (@include_files) {
471 my $date = POSIX::strftime("%Y%m%d%H%M",
472 localtime((stat $file)[9]));
473 $last_mod_date = $date if ($last_mod_date < $date);
475 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
478 if ($camelcase_cache ne "" && -f $camelcase_cache) {
479 open(my $camelcase_file, '<', "$camelcase_cache")
480 or warn "$P: Can't read '$camelcase_cache' $!\n";
481 while (<$camelcase_file>) {
485 close($camelcase_file);
491 $files = `git ls-files "include/*.h"`;
492 @include_files = split('\n', $files);
495 foreach my $file (@include_files) {
496 seed_camelcase_file($file);
499 if ($camelcase_cache ne "") {
500 unlink glob ".checkpatch-camelcase.*";
501 open(my $camelcase_file, '>', "$camelcase_cache")
502 or warn "$P: Can't write '$camelcase_cache' $!\n";
503 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
504 print $camelcase_file ("$_\n");
506 close($camelcase_file);
510 $chk_signoff = 0 if ($file);
516 for my $filename (@ARGV) {
519 open($FILE, '-|', "diff -u /dev/null $filename") ||
520 die "$P: $filename: diff failed - $!\n";
521 } elsif ($filename eq '-') {
522 open($FILE, '<&STDIN');
524 open($FILE, '<', "$filename") ||
525 die "$P: $filename: open failed - $!\n";
527 if ($filename eq '-') {
528 $vname = 'Your patch';
537 if (!process($filename)) {
547 sub top_of_kernel_tree {
551 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
552 "README", "Documentation", "arch", "include", "drivers",
553 "fs", "init", "ipc", "kernel", "lib", "scripts",
556 foreach my $check (@tree_check) {
557 if (! -e $root . '/' . $check) {
565 my ($formatted_email) = @_;
571 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
574 $comment = $3 if defined $3;
575 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
577 $comment = $2 if defined $2;
578 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
580 $comment = $2 if defined $2;
581 $formatted_email =~ s/$address.*$//;
582 $name = $formatted_email;
584 $name =~ s/^\"|\"$//g;
585 # If there's a name left after stripping spaces and
586 # leading quotes, and the address doesn't have both
587 # leading and trailing angle brackets, the address
589 # "joe smith joe@smith.com" bad
590 # "joe smith <joe@smith.com" bad
591 if ($name ne "" && $address !~ /^<[^>]+>$/) {
599 $name =~ s/^\"|\"$//g;
600 $address = trim($address);
601 $address =~ s/^\<|\>$//g;
603 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
604 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
608 return ($name, $address, $comment);
612 my ($name, $address) = @_;
617 $name =~ s/^\"|\"$//g;
618 $address = trim($address);
620 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
621 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
626 $formatted_email = "$address";
628 $formatted_email = "$name <$address>";
631 return $formatted_email;
637 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
638 if (-e "$path/$conf") {
639 return "$path/$conf";
651 for my $c (split(//, $str)) {
655 for (; ($n % 8) != 0; $n++) {
667 (my $res = shift) =~ tr/\t/ /c;
674 # Drop the diff line leader and expand tabs
676 $line = expand_tabs($line);
678 # Pick the indent from the front of the line.
679 my ($white) = ($line =~ /^(\s*)/);
681 return (length($line), length($white));
684 my $sanitise_quote = '';
686 sub sanitise_line_reset {
687 my ($in_comment) = @_;
690 $sanitise_quote = '*/';
692 $sanitise_quote = '';
705 # Always copy over the diff marker.
706 $res = substr($line, 0, 1);
708 for ($off = 1; $off < length($line); $off++) {
709 $c = substr($line, $off, 1);
711 # Comments we are wacking completly including the begin
712 # and end, all to $;.
713 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
714 $sanitise_quote = '*/';
716 substr($res, $off, 2, "$;$;");
720 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
721 $sanitise_quote = '';
722 substr($res, $off, 2, "$;$;");
726 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
727 $sanitise_quote = '//';
729 substr($res, $off, 2, $sanitise_quote);
734 # A \ in a string means ignore the next character.
735 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
737 substr($res, $off, 2, 'XX');
742 if ($c eq "'" || $c eq '"') {
743 if ($sanitise_quote eq '') {
744 $sanitise_quote = $c;
746 substr($res, $off, 1, $c);
748 } elsif ($sanitise_quote eq $c) {
749 $sanitise_quote = '';
753 #print "c<$c> SQ<$sanitise_quote>\n";
754 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
755 substr($res, $off, 1, $;);
756 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
757 substr($res, $off, 1, $;);
758 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
759 substr($res, $off, 1, 'X');
761 substr($res, $off, 1, $c);
765 if ($sanitise_quote eq '//') {
766 $sanitise_quote = '';
769 # The pathname on a #include may be surrounded by '<' and '>'.
770 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
771 my $clean = 'X' x length($1);
772 $res =~ s@\<.*\>@<$clean>@;
774 # The whole of a #error is a string.
775 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
776 my $clean = 'X' x length($1);
777 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
783 sub get_quoted_string {
784 my ($line, $rawline) = @_;
786 return "" if ($line !~ m/(\"[X]+\")/g);
787 return substr($rawline, $-[0], $+[0] - $-[0]);
790 sub ctx_statement_block {
791 my ($linenr, $remain, $off) = @_;
792 my $line = $linenr - 1;
809 @stack = (['', 0]) if ($#stack == -1);
811 #warn "CSB: blk<$blk> remain<$remain>\n";
812 # If we are about to drop off the end, pull in more
815 for (; $remain > 0; $line++) {
816 last if (!defined $lines[$line]);
817 next if ($lines[$line] =~ /^-/);
820 $blk .= $lines[$line] . "\n";
825 # Bail if there is no further context.
826 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
830 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
836 $c = substr($blk, $off, 1);
837 $remainder = substr($blk, $off);
839 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
841 # Handle nested #if/#else.
842 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
843 push(@stack, [ $type, $level ]);
844 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
845 ($type, $level) = @{$stack[$#stack - 1]};
846 } elsif ($remainder =~ /^#\s*endif\b/) {
847 ($type, $level) = @{pop(@stack)};
850 # Statement ends at the ';' or a close '}' at the
852 if ($level == 0 && $c eq ';') {
856 # An else is really a conditional as long as its not else if
857 if ($level == 0 && $coff_set == 0 &&
858 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
859 $remainder =~ /^(else)(?:\s|{)/ &&
860 $remainder !~ /^else\s+if\b/) {
861 $coff = $off + length($1) - 1;
863 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
864 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
867 if (($type eq '' || $type eq '(') && $c eq '(') {
871 if ($type eq '(' && $c eq ')') {
873 $type = ($level != 0)? '(' : '';
875 if ($level == 0 && $coff < $soff) {
878 #warn "CSB: mark coff<$coff>\n";
881 if (($type eq '' || $type eq '{') && $c eq '{') {
885 if ($type eq '{' && $c eq '}') {
887 $type = ($level != 0)? '{' : '';
890 if (substr($blk, $off + 1, 1) eq ';') {
896 # Preprocessor commands end at the newline unless escaped.
897 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
905 # We are truly at the end, so shuffle to the next line.
912 my $statement = substr($blk, $soff, $off - $soff + 1);
913 my $condition = substr($blk, $soff, $coff - $soff + 1);
915 #warn "STATEMENT<$statement>\n";
916 #warn "CONDITION<$condition>\n";
918 #print "coff<$coff> soff<$off> loff<$loff>\n";
920 return ($statement, $condition,
921 $line, $remain + 1, $off - $loff + 1, $level);
924 sub statement_lines {
927 # Strip the diff line prefixes and rip blank lines at start and end.
928 $stmt =~ s/(^|\n)./$1/g;
932 my @stmt_lines = ($stmt =~ /\n/g);
934 return $#stmt_lines + 2;
937 sub statement_rawlines {
940 my @stmt_lines = ($stmt =~ /\n/g);
942 return $#stmt_lines + 2;
945 sub statement_block_size {
948 $stmt =~ s/(^|\n)./$1/g;
954 my @stmt_lines = ($stmt =~ /\n/g);
955 my @stmt_statements = ($stmt =~ /;/g);
957 my $stmt_lines = $#stmt_lines + 2;
958 my $stmt_statements = $#stmt_statements + 1;
960 if ($stmt_lines > $stmt_statements) {
963 return $stmt_statements;
967 sub ctx_statement_full {
968 my ($linenr, $remain, $off) = @_;
969 my ($statement, $condition, $level);
973 # Grab the first conditional/block pair.
974 ($statement, $condition, $linenr, $remain, $off, $level) =
975 ctx_statement_block($linenr, $remain, $off);
976 #print "F: c<$condition> s<$statement> remain<$remain>\n";
977 push(@chunks, [ $condition, $statement ]);
978 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
979 return ($level, $linenr, @chunks);
982 # Pull in the following conditional/block pairs and see if they
983 # could continue the statement.
985 ($statement, $condition, $linenr, $remain, $off, $level) =
986 ctx_statement_block($linenr, $remain, $off);
987 #print "C: c<$condition> s<$statement> remain<$remain>\n";
988 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
990 push(@chunks, [ $condition, $statement ]);
993 return ($level, $linenr, @chunks);
997 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
999 my $start = $linenr - 1;
1006 my @stack = ($level);
1007 for ($line = $start; $remain > 0; $line++) {
1008 next if ($rawlines[$line] =~ /^-/);
1011 $blk .= $rawlines[$line];
1013 # Handle nested #if/#else.
1014 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1015 push(@stack, $level);
1016 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1017 $level = $stack[$#stack - 1];
1018 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1019 $level = pop(@stack);
1022 foreach my $c (split(//, $lines[$line])) {
1023 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1029 if ($c eq $close && $level > 0) {
1031 last if ($level == 0);
1032 } elsif ($c eq $open) {
1037 if (!$outer || $level <= 1) {
1038 push(@res, $rawlines[$line]);
1041 last if ($level == 0);
1044 return ($level, @res);
1046 sub ctx_block_outer {
1047 my ($linenr, $remain) = @_;
1049 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1053 my ($linenr, $remain) = @_;
1055 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1059 my ($linenr, $remain, $off) = @_;
1061 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1064 sub ctx_block_level {
1065 my ($linenr, $remain) = @_;
1067 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1069 sub ctx_statement_level {
1070 my ($linenr, $remain, $off) = @_;
1072 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1075 sub ctx_locate_comment {
1076 my ($first_line, $end_line) = @_;
1078 # Catch a comment on the end of the line itself.
1079 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1080 return $current_comment if (defined $current_comment);
1082 # Look through the context and try and figure out if there is a
1085 $current_comment = '';
1086 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1087 my $line = $rawlines[$linenr - 1];
1089 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1092 if ($line =~ m@/\*@) {
1095 if (!$in_comment && $current_comment ne '') {
1096 $current_comment = '';
1098 $current_comment .= $line . "\n" if ($in_comment);
1099 if ($line =~ m@\*/@) {
1104 chomp($current_comment);
1105 return($current_comment);
1107 sub ctx_has_comment {
1108 my ($first_line, $end_line) = @_;
1109 my $cmt = ctx_locate_comment($first_line, $end_line);
1111 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1112 ##print "CMMT: $cmt\n";
1114 return ($cmt ne '');
1118 my ($linenr, $cnt) = @_;
1120 my $offset = $linenr - 1;
1125 $line = $rawlines[$offset++];
1126 next if (defined($line) && $line =~ /^-/);
1138 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1141 $coded = sprintf("^%c", unpack('C', $2) + 64);
1150 my $av_preprocessor = 0;
1155 sub annotate_reset {
1156 $av_preprocessor = 0;
1158 @av_paren_type = ('E');
1159 $av_pend_colon = 'O';
1162 sub annotate_values {
1163 my ($stream, $type) = @_;
1166 my $var = '_' x length($stream);
1169 print "$stream\n" if ($dbg_values > 1);
1171 while (length($cur)) {
1172 @av_paren_type = ('E') if ($#av_paren_type < 0);
1173 print " <" . join('', @av_paren_type) .
1174 "> <$type> <$av_pending>" if ($dbg_values > 1);
1175 if ($cur =~ /^(\s+)/o) {
1176 print "WS($1)\n" if ($dbg_values > 1);
1177 if ($1 =~ /\n/ && $av_preprocessor) {
1178 $type = pop(@av_paren_type);
1179 $av_preprocessor = 0;
1182 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1183 print "CAST($1)\n" if ($dbg_values > 1);
1184 push(@av_paren_type, $type);
1187 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1188 print "DECLARE($1)\n" if ($dbg_values > 1);
1191 } elsif ($cur =~ /^($Modifier)\s*/) {
1192 print "MODIFIER($1)\n" if ($dbg_values > 1);
1195 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1196 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1197 $av_preprocessor = 1;
1198 push(@av_paren_type, $type);
1204 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1205 print "UNDEF($1)\n" if ($dbg_values > 1);
1206 $av_preprocessor = 1;
1207 push(@av_paren_type, $type);
1209 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1210 print "PRE_START($1)\n" if ($dbg_values > 1);
1211 $av_preprocessor = 1;
1213 push(@av_paren_type, $type);
1214 push(@av_paren_type, $type);
1217 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1218 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1219 $av_preprocessor = 1;
1221 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1225 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1226 print "PRE_END($1)\n" if ($dbg_values > 1);
1228 $av_preprocessor = 1;
1230 # Assume all arms of the conditional end as this
1231 # one does, and continue as if the #endif was not here.
1232 pop(@av_paren_type);
1233 push(@av_paren_type, $type);
1236 } elsif ($cur =~ /^(\\\n)/o) {
1237 print "PRECONT($1)\n" if ($dbg_values > 1);
1239 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1240 print "ATTR($1)\n" if ($dbg_values > 1);
1241 $av_pending = $type;
1244 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1245 print "SIZEOF($1)\n" if ($dbg_values > 1);
1251 } elsif ($cur =~ /^(if|while|for)\b/o) {
1252 print "COND($1)\n" if ($dbg_values > 1);
1256 } elsif ($cur =~/^(case)/o) {
1257 print "CASE($1)\n" if ($dbg_values > 1);
1258 $av_pend_colon = 'C';
1261 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1262 print "KEYWORD($1)\n" if ($dbg_values > 1);
1265 } elsif ($cur =~ /^(\()/o) {
1266 print "PAREN('$1')\n" if ($dbg_values > 1);
1267 push(@av_paren_type, $av_pending);
1271 } elsif ($cur =~ /^(\))/o) {
1272 my $new_type = pop(@av_paren_type);
1273 if ($new_type ne '_') {
1275 print "PAREN('$1') -> $type\n"
1276 if ($dbg_values > 1);
1278 print "PAREN('$1')\n" if ($dbg_values > 1);
1281 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1282 print "FUNC($1)\n" if ($dbg_values > 1);
1286 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1287 if (defined $2 && $type eq 'C' || $type eq 'T') {
1288 $av_pend_colon = 'B';
1289 } elsif ($type eq 'E') {
1290 $av_pend_colon = 'L';
1292 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1295 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1296 print "IDENT($1)\n" if ($dbg_values > 1);
1299 } elsif ($cur =~ /^($Assignment)/o) {
1300 print "ASSIGN($1)\n" if ($dbg_values > 1);
1303 } elsif ($cur =~/^(;|{|})/) {
1304 print "END($1)\n" if ($dbg_values > 1);
1306 $av_pend_colon = 'O';
1308 } elsif ($cur =~/^(,)/) {
1309 print "COMMA($1)\n" if ($dbg_values > 1);
1312 } elsif ($cur =~ /^(\?)/o) {
1313 print "QUESTION($1)\n" if ($dbg_values > 1);
1316 } elsif ($cur =~ /^(:)/o) {
1317 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1319 substr($var, length($res), 1, $av_pend_colon);
1320 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1325 $av_pend_colon = 'O';
1327 } elsif ($cur =~ /^(\[)/o) {
1328 print "CLOSE($1)\n" if ($dbg_values > 1);
1331 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1334 print "OPV($1)\n" if ($dbg_values > 1);
1341 substr($var, length($res), 1, $variant);
1344 } elsif ($cur =~ /^($Operators)/o) {
1345 print "OP($1)\n" if ($dbg_values > 1);
1346 if ($1 ne '++' && $1 ne '--') {
1350 } elsif ($cur =~ /(^.)/o) {
1351 print "C($1)\n" if ($dbg_values > 1);
1354 $cur = substr($cur, length($1));
1355 $res .= $type x length($1);
1359 return ($res, $var);
1363 my ($possible, $line) = @_;
1364 my $notPermitted = qr{(?:
1381 ^(?:typedef|struct|enum)\b
1383 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1384 if ($possible !~ $notPermitted) {
1385 # Check for modifiers.
1386 $possible =~ s/\s*$Storage\s*//g;
1387 $possible =~ s/\s*$Sparse\s*//g;
1388 if ($possible =~ /^\s*$/) {
1390 } elsif ($possible =~ /\s/) {
1391 $possible =~ s/\s*$Type\s*//g;
1392 for my $modifier (split(' ', $possible)) {
1393 if ($modifier !~ $notPermitted) {
1394 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1395 push(@modifierList, $modifier);
1400 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1401 push(@typeList, $possible);
1405 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1412 return defined $use_type{$_[0]} if (scalar keys %use_type > 0);
1414 return !defined $ignore_type{$_[0]};
1418 if (!show_type($_[1]) ||
1419 (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1424 $line = "$prefix$_[0]:$_[1]: $_[2]\n";
1426 $line = "$prefix$_[0]: $_[2]\n";
1428 $line = (split('\n', $line))[0] . "\n" if ($terse);
1430 push(our @report, $line);
1439 if (report("ERROR", $_[0], $_[1])) {
1447 if (report("WARNING", $_[0], $_[1])) {
1455 if ($check && report("CHECK", $_[0], $_[1])) {
1463 sub check_absolute_file {
1464 my ($absolute, $herecurr) = @_;
1465 my $file = $absolute;
1467 ##print "absolute<$absolute>\n";
1469 # See if any suffix of this path is a path within the tree.
1470 while ($file =~ s@^[^/]*/@@) {
1471 if (-f "$root/$file") {
1472 ##print "file<$file>\n";
1480 # It is, so see if the prefix is acceptable.
1481 my $prefix = $absolute;
1482 substr($prefix, -length($file)) = '';
1484 ##print "prefix<$prefix>\n";
1485 if ($prefix ne ".../") {
1486 WARN("USE_RELATIVE_PATH",
1487 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1494 $string =~ s/^\s+|\s+$//g;
1502 $string =~ s/^\s+//;
1510 $string =~ s/\s+$//;
1518 my $source_indent = 8;
1519 my $max_spaces_before_tab = $source_indent - 1;
1520 my $spaces_to_tab = " " x $source_indent;
1522 #convert leading spaces to tabs
1523 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1524 #Remove spaces before a tab
1525 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1530 sub pos_last_openparen {
1535 my $opens = $line =~ tr/\(/\(/;
1536 my $closes = $line =~ tr/\)/\)/;
1538 my $last_openparen = 0;
1540 if (($opens == 0) || ($closes >= $opens)) {
1544 my $len = length($line);
1546 for ($pos = 0; $pos < $len; $pos++) {
1547 my $string = substr($line, $pos);
1548 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1549 $pos += length($1) - 1;
1550 } elsif (substr($line, $pos, 1) eq '(') {
1551 $last_openparen = $pos;
1552 } elsif (index($string, '(') == -1) {
1557 return $last_openparen + 1;
1561 my $filename = shift;
1567 my $stashrawline="";
1578 my $in_header_lines = 1;
1579 my $in_commit_log = 0; #Scanning lines before patch
1581 my $non_utf8_charset = 0;
1589 # Trace the real file/line as we go.
1595 my $comment_edge = 0;
1599 my $prev_values = 'E';
1602 my %suppress_ifbraces;
1603 my %suppress_whiletrailers;
1604 my %suppress_export;
1605 my $suppress_statement = 0;
1607 my %signatures = ();
1609 # Pre-scan the patch sanitizing the lines.
1610 # Pre-scan the patch looking for any __setup documentation.
1612 my @setup_docs = ();
1615 my $camelcase_file_seeded = 0;
1617 sanitise_line_reset();
1619 foreach my $rawline (@rawlines) {
1623 push(@fixed, $rawline) if ($fix);
1625 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1627 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1632 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1641 # Guestimate if this is a continuing comment. Run
1642 # the context looking for a comment "edge". If this
1643 # edge is a close comment then we must be in a comment
1647 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1648 next if (defined $rawlines[$ln - 1] &&
1649 $rawlines[$ln - 1] =~ /^-/);
1651 #print "RAW<$rawlines[$ln - 1]>\n";
1652 last if (!defined $rawlines[$ln - 1]);
1653 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1654 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1659 if (defined $edge && $edge eq '*/') {
1663 # Guestimate if this is a continuing comment. If this
1664 # is the start of a diff block and this line starts
1665 # ' *' then it is very likely a comment.
1666 if (!defined $edge &&
1667 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1672 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1673 sanitise_line_reset($in_comment);
1675 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1676 # Standardise the strings and chars within the input to
1677 # simplify matching -- only bother with positive lines.
1678 $line = sanitise_line($rawline);
1680 push(@lines, $line);
1683 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1688 #print "==>$rawline\n";
1689 #print "-->$line\n";
1691 if ($setup_docs && $line =~ /^\+/) {
1692 push(@setup_docs, $line);
1700 foreach my $line (@lines) {
1702 my $sline = $line; #copy of $line
1703 $sline =~ s/$;/ /g; #with comments as spaces
1705 my $rawline = $rawlines[$linenr - 1];
1707 #extract the line range in the file after the patch is applied
1708 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1710 $first_line = $linenr + 1;
1720 %suppress_ifbraces = ();
1721 %suppress_whiletrailers = ();
1722 %suppress_export = ();
1723 $suppress_statement = 0;
1726 # track the line number as we move through the hunk, note that
1727 # new versions of GNU diff omit the leading space on completely
1728 # blank context lines so we need to count that too.
1729 } elsif ($line =~ /^( |\+|$)/) {
1731 $realcnt-- if ($realcnt != 0);
1733 # Measure the line length and indent.
1734 ($length, $indent) = line_stats($rawline);
1736 # Track the previous line.
1737 ($prevline, $stashline) = ($stashline, $line);
1738 ($previndent, $stashindent) = ($stashindent, $indent);
1739 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1741 #warn "line<$line>\n";
1743 } elsif ($realcnt == 1) {
1747 my $hunk_line = ($realcnt != 0);
1749 #make up the handle for any error we report on this line
1750 $prefix = "$filename:$realline: " if ($emacs && $file);
1751 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1753 $here = "#$linenr: " if (!$file);
1754 $here = "#$realline: " if ($file);
1756 # extract the filename as it passes
1757 if ($line =~ /^diff --git.*?(\S+)$/) {
1759 $realfile =~ s@^([^/]*)/@@;
1761 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1763 $realfile =~ s@^([^/]*)/@@;
1767 if (!$file && $tree && $p1_prefix ne '' &&
1768 -e "$root/$p1_prefix") {
1769 WARN("PATCH_PREFIX",
1770 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1773 if ($realfile =~ m@^include/asm/@) {
1774 ERROR("MODIFIED_INCLUDE_ASM",
1775 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1780 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1782 my $hereline = "$here\n$rawline\n";
1783 my $herecurr = "$here\n$rawline\n";
1784 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1786 $cnt_lines++ if ($realcnt != 0);
1788 # Check for incorrect file permissions
1789 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1790 my $permhere = $here . "FILE: $realfile\n";
1791 if ($realfile !~ m@scripts/@ &&
1792 $realfile !~ /\.(py|pl|awk|sh)$/) {
1793 ERROR("EXECUTE_PERMISSIONS",
1794 "do not set execute permissions for source files\n" . $permhere);
1798 # Check the patch for a signoff:
1799 if ($line =~ /^\s*signed-off-by:/i) {
1804 # Check signature styles
1805 if (!$in_header_lines &&
1806 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
1807 my $space_before = $1;
1809 my $space_after = $3;
1811 my $ucfirst_sign_off = ucfirst(lc($sign_off));
1813 if ($sign_off !~ /$signature_tags/) {
1814 WARN("BAD_SIGN_OFF",
1815 "Non-standard signature: $sign_off\n" . $herecurr);
1817 if (defined $space_before && $space_before ne "") {
1818 if (WARN("BAD_SIGN_OFF",
1819 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
1821 $fixed[$linenr - 1] =
1822 "$ucfirst_sign_off $email";
1825 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1826 if (WARN("BAD_SIGN_OFF",
1827 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
1829 $fixed[$linenr - 1] =
1830 "$ucfirst_sign_off $email";
1834 if (!defined $space_after || $space_after ne " ") {
1835 if (WARN("BAD_SIGN_OFF",
1836 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
1838 $fixed[$linenr - 1] =
1839 "$ucfirst_sign_off $email";
1843 my ($email_name, $email_address, $comment) = parse_email($email);
1844 my $suggested_email = format_email(($email_name, $email_address));
1845 if ($suggested_email eq "") {
1846 ERROR("BAD_SIGN_OFF",
1847 "Unrecognized email address: '$email'\n" . $herecurr);
1849 my $dequoted = $suggested_email;
1850 $dequoted =~ s/^"//;
1851 $dequoted =~ s/" </ </;
1852 # Don't force email to have quotes
1853 # Allow just an angle bracketed address
1854 if ("$dequoted$comment" ne $email &&
1855 "<$email_address>$comment" ne $email &&
1856 "$suggested_email$comment" ne $email) {
1857 WARN("BAD_SIGN_OFF",
1858 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1862 # Check for duplicate signatures
1863 my $sig_nospace = $line;
1864 $sig_nospace =~ s/\s//g;
1865 $sig_nospace = lc($sig_nospace);
1866 if (defined $signatures{$sig_nospace}) {
1867 WARN("BAD_SIGN_OFF",
1868 "Duplicate signature\n" . $herecurr);
1870 $signatures{$sig_nospace} = 1;
1874 # Check for wrappage within a valid hunk of the file
1875 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1876 ERROR("CORRUPTED_PATCH",
1877 "patch seems to be corrupt (line wrapped?)\n" .
1878 $herecurr) if (!$emitted_corrupt++);
1881 # Check for absolute kernel paths.
1883 while ($line =~ m{(?:^|\s)(/\S*)}g) {
1886 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1887 check_absolute_file($1, $herecurr)) {
1890 check_absolute_file($file, $herecurr);
1895 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1896 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1897 $rawline !~ m/^$UTF8*$/) {
1898 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1900 my $blank = copy_spacing($rawline);
1901 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1902 my $hereptr = "$hereline$ptr\n";
1905 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1908 # Check if it's the start of a commit log
1909 # (not a header line and we haven't seen the patch filename)
1910 if ($in_header_lines && $realfile =~ /^$/ &&
1911 $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1912 $in_header_lines = 0;
1916 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1917 # declined it, i.e defined some charset where it is missing.
1918 if ($in_header_lines &&
1919 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1921 $non_utf8_charset = 1;
1924 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1925 $rawline =~ /$NON_ASCII_UTF8/) {
1926 WARN("UTF8_BEFORE_PATCH",
1927 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
1930 # ignore non-hunk lines and lines being removed
1931 next if (!$hunk_line || $line =~ /^-/);
1933 #trailing whitespace
1934 if ($line =~ /^\+.*\015/) {
1935 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1936 if (ERROR("DOS_LINE_ENDINGS",
1937 "DOS line endings\n" . $herevet) &&
1939 $fixed[$linenr - 1] =~ s/[\s\015]+$//;
1941 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1942 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1943 if (ERROR("TRAILING_WHITESPACE",
1944 "trailing whitespace\n" . $herevet) &&
1946 $fixed[$linenr - 1] =~ s/\s+$//;
1952 # check for Kconfig help text having a real description
1953 # Only applies when adding the entry originally, after that we do not have
1954 # sufficient context to determine whether it is indeed long enough.
1955 if ($realfile =~ /Kconfig/ &&
1956 $line =~ /.\s*config\s+/) {
1959 my $ln = $linenr + 1;
1963 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
1964 $f = $lines[$ln - 1];
1965 $cnt-- if ($lines[$ln - 1] !~ /^-/);
1966 $is_end = $lines[$ln - 1] =~ /^\+/;
1968 next if ($f =~ /^-/);
1970 if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
1972 } elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
1979 next if ($f =~ /^$/);
1980 if ($f =~ /^\s*config\s/) {
1986 WARN("CONFIG_DESCRIPTION",
1987 "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
1988 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
1991 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
1992 if ($realfile =~ /Kconfig/ &&
1993 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
1994 WARN("CONFIG_EXPERIMENTAL",
1995 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
1998 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
1999 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2002 'EXTRA_AFLAGS' => 'asflags-y',
2003 'EXTRA_CFLAGS' => 'ccflags-y',
2004 'EXTRA_CPPFLAGS' => 'cppflags-y',
2005 'EXTRA_LDFLAGS' => 'ldflags-y',
2008 WARN("DEPRECATED_VARIABLE",
2009 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2012 # check we are in a valid source file if not then ignore this hunk
2013 next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
2016 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2017 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2018 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2019 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2020 $length > $max_line_length)
2023 "line over $max_line_length characters\n" . $herecurr);
2026 # Check for user-visible strings broken across lines, which breaks the ability
2027 # to grep for the string. Limited to strings used as parameters (those
2028 # following an open parenthesis), which almost completely eliminates false
2029 # positives, as well as warning only once per parameter rather than once per
2030 # line of the string. Make an exception when the previous string ends in a
2031 # newline (multiple lines in one string constant) or \n\t (common in inline
2032 # assembly to indent the instruction on the following line).
2033 if ($line =~ /^\+\s*"/ &&
2034 $prevline =~ /"\s*$/ &&
2035 $prevline =~ /\(/ &&
2036 $prevrawline !~ /\\n(?:\\t)*"\s*$/) {
2037 WARN("SPLIT_STRING",
2038 "quoted string split across lines\n" . $hereprev);
2041 # check for spaces before a quoted newline
2042 if ($rawline =~ /^.*\".*\s\\n/) {
2043 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2044 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2046 $fixed[$linenr - 1] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2051 # check for adding lines without a newline.
2052 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2053 WARN("MISSING_EOF_NEWLINE",
2054 "adding a line without newline at end of file\n" . $herecurr);
2057 # Blackfin: use hi/lo macros
2058 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2059 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2060 my $herevet = "$here\n" . cat_vet($line) . "\n";
2062 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2064 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2065 my $herevet = "$here\n" . cat_vet($line) . "\n";
2067 "use the HI() macro, not (... >> 16)\n" . $herevet);
2071 # check we are in a valid source file C or perl if not then ignore this hunk
2072 next if ($realfile !~ /\.(h|c|pl)$/);
2074 # at the beginning of a line any tabs must come first and anything
2075 # more than 8 must use tabs.
2076 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2077 $rawline =~ /^\+\s* \s*/) {
2078 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2080 if (ERROR("CODE_INDENT",
2081 "code indent should use tabs where possible\n" . $herevet) &&
2083 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2087 # check for space before tabs.
2088 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2089 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2090 if (WARN("SPACE_BEFORE_TAB",
2091 "please, no space before tabs\n" . $herevet) &&
2093 $fixed[$linenr - 1] =~
2094 s/(^\+.*) +\t/$1\t/;
2098 # check for && or || at the start of a line
2099 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2100 CHK("LOGICAL_CONTINUATIONS",
2101 "Logical continuations should be on the previous line\n" . $hereprev);
2104 # check multi-line statement indentation matches previous line
2105 if ($^V && $^V ge 5.10.0 &&
2106 $prevline =~ /^\+(\t*)(if \(|$Ident\().*(\&\&|\|\||,)\s*$/) {
2107 $prevline =~ /^\+(\t*)(.*)$/;
2111 my $pos = pos_last_openparen($rest);
2113 $line =~ /^(\+| )([ \t]*)/;
2116 my $goodtabindent = $oldindent .
2119 my $goodspaceindent = $oldindent . " " x $pos;
2121 if ($newindent ne $goodtabindent &&
2122 $newindent ne $goodspaceindent) {
2124 if (CHK("PARENTHESIS_ALIGNMENT",
2125 "Alignment should match open parenthesis\n" . $hereprev) &&
2126 $fix && $line =~ /^\+/) {
2127 $fixed[$linenr - 1] =~
2128 s/^\+[ \t]*/\+$goodtabindent/;
2134 if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) {
2136 "No space is necessary after a cast\n" . $hereprev) &&
2138 $fixed[$linenr - 1] =~
2139 s/^(\+.*\*[ \t]*\))[ \t]+/$1/;
2143 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2144 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2145 $rawline =~ /^\+[ \t]*\*/) {
2146 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2147 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2150 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2151 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2152 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2153 $rawline =~ /^\+/ && #line is new
2154 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2155 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2156 "networking block comments start with * on subsequent lines\n" . $hereprev);
2159 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2160 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2161 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2162 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2163 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2164 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2165 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2168 # check for spaces at the beginning of a line.
2170 # 1) within comments
2171 # 2) indented preprocessor commands
2173 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2174 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2175 if (WARN("LEADING_SPACE",
2176 "please, no spaces at the start of a line\n" . $herevet) &&
2178 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2182 # check we are in a valid C source file if not then ignore this hunk
2183 next if ($realfile !~ /\.(h|c)$/);
2185 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2186 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2187 WARN("CONFIG_EXPERIMENTAL",
2188 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2191 # check for RCS/CVS revision markers
2192 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2194 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2197 # Blackfin: don't use __builtin_bfin_[cs]sync
2198 if ($line =~ /__builtin_bfin_csync/) {
2199 my $herevet = "$here\n" . cat_vet($line) . "\n";
2201 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2203 if ($line =~ /__builtin_bfin_ssync/) {
2204 my $herevet = "$here\n" . cat_vet($line) . "\n";
2206 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2209 # check for old HOTPLUG __dev<foo> section markings
2210 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2211 WARN("HOTPLUG_SECTION",
2212 "Using $1 is unnecessary\n" . $herecurr);
2215 # Check for potential 'bare' types
2216 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2218 #print "LINE<$line>\n";
2219 if ($linenr >= $suppress_statement &&
2220 $realcnt && $sline =~ /.\s*\S/) {
2221 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2222 ctx_statement_block($linenr, $realcnt, 0);
2223 $stat =~ s/\n./\n /g;
2224 $cond =~ s/\n./\n /g;
2226 #print "linenr<$linenr> <$stat>\n";
2227 # If this statement has no statement boundaries within
2228 # it there is no point in retrying a statement scan
2229 # until we hit end of it.
2230 my $frag = $stat; $frag =~ s/;+\s*$//;
2231 if ($frag !~ /(?:{|;)/) {
2232 #print "skip<$line_nr_next>\n";
2233 $suppress_statement = $line_nr_next;
2236 # Find the real next line.
2237 $realline_next = $line_nr_next;
2238 if (defined $realline_next &&
2239 (!defined $lines[$realline_next - 1] ||
2240 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2247 # Ignore goto labels.
2248 if ($s =~ /$Ident:\*$/s) {
2250 # Ignore functions being called
2251 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2253 } elsif ($s =~ /^.\s*else\b/s) {
2255 # declarations always start with types
2256 } 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) {
2259 possible($type, "A:" . $s);
2261 # definitions in global scope can only start with types
2262 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2263 possible($1, "B:" . $s);
2266 # any (foo ... *) is a pointer cast, and foo is a type
2267 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2268 possible($1, "C:" . $s);
2271 # Check for any sort of function declaration.
2272 # int foo(something bar, other baz);
2273 # void (*store_gdt)(x86_descr_ptr *);
2274 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2275 my ($name_len) = length($1);
2278 substr($ctx, 0, $name_len + 1, '');
2279 $ctx =~ s/\)[^\)]*$//;
2281 for my $arg (split(/\s*,\s*/, $ctx)) {
2282 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2284 possible($1, "D:" . $s);
2292 # Checks which may be anchored in the context.
2295 # Check for switch () and associated case and default
2296 # statements should be at the same indent.
2297 if ($line=~/\bswitch\s*\(.*\)/) {
2300 my @ctx = ctx_block_outer($linenr, $realcnt);
2302 for my $ctx (@ctx) {
2303 my ($clen, $cindent) = line_stats($ctx);
2304 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2305 $indent != $cindent) {
2306 $err .= "$sep$ctx\n";
2313 ERROR("SWITCH_CASE_INDENT_LEVEL",
2314 "switch and case should be at the same indent\n$hereline$err");
2318 # if/while/etc brace do not go on next line, unless defining a do while loop,
2319 # or if that brace on the next line is for something else
2320 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2321 my $pre_ctx = "$1$2";
2323 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2325 if ($line =~ /^\+\t{6,}/) {
2326 WARN("DEEP_INDENTATION",
2327 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2330 my $ctx_cnt = $realcnt - $#ctx - 1;
2331 my $ctx = join("\n", @ctx);
2333 my $ctx_ln = $linenr;
2334 my $ctx_skip = $realcnt;
2336 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2337 defined $lines[$ctx_ln - 1] &&
2338 $lines[$ctx_ln - 1] =~ /^-/)) {
2339 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2340 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2344 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2345 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2347 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2349 "that open brace { should be on the previous line\n" .
2350 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2352 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2353 $ctx =~ /\)\s*\;\s*$/ &&
2354 defined $lines[$ctx_ln - 1])
2356 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2357 if ($nindent > $indent) {
2358 WARN("TRAILING_SEMICOLON",
2359 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2360 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2365 # Check relative indent for conditionals and blocks.
2366 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2367 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2368 ctx_statement_block($linenr, $realcnt, 0)
2369 if (!defined $stat);
2370 my ($s, $c) = ($stat, $cond);
2372 substr($s, 0, length($c), '');
2374 # Make sure we remove the line prefixes as we have
2375 # none on the first line, and are going to readd them
2379 # Find out how long the conditional actually is.
2380 my @newlines = ($c =~ /\n/gs);
2381 my $cond_lines = 1 + $#newlines;
2383 # We want to check the first line inside the block
2384 # starting at the end of the conditional, so remove:
2385 # 1) any blank line termination
2386 # 2) any opening brace { on end of the line
2388 my $continuation = 0;
2390 $s =~ s/^.*\bdo\b//;
2392 if ($s =~ s/^\s*\\//) {
2395 if ($s =~ s/^\s*?\n//) {
2400 # Also ignore a loop construct at the end of a
2401 # preprocessor statement.
2402 if (($prevline =~ /^.\s*#\s*define\s/ ||
2403 $prevline =~ /\\\s*$/) && $continuation == 0) {
2409 while ($cond_ptr != $cond_lines) {
2410 $cond_ptr = $cond_lines;
2412 # If we see an #else/#elif then the code
2414 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2419 # 1) blank lines, they should be at 0,
2420 # 2) preprocessor lines, and
2422 if ($continuation ||
2424 $s =~ /^\s*#\s*?/ ||
2425 $s =~ /^\s*$Ident\s*:/) {
2426 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2427 if ($s =~ s/^.*?\n//) {
2433 my (undef, $sindent) = line_stats("+" . $s);
2434 my $stat_real = raw_line($linenr, $cond_lines);
2436 # Check if either of these lines are modified, else
2437 # this is not this patch's fault.
2438 if (!defined($stat_real) ||
2439 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2442 if (defined($stat_real) && $cond_lines > 1) {
2443 $stat_real = "[...]\n$stat_real";
2446 #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";
2448 if ($check && (($sindent % 8) != 0 ||
2449 ($sindent <= $indent && $s ne ''))) {
2450 WARN("SUSPECT_CODE_INDENT",
2451 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2455 # Track the 'values' across context and added lines.
2456 my $opline = $line; $opline =~ s/^./ /;
2457 my ($curr_values, $curr_vars) =
2458 annotate_values($opline . "\n", $prev_values);
2459 $curr_values = $prev_values . $curr_values;
2461 my $outline = $opline; $outline =~ s/\t/ /g;
2462 print "$linenr > .$outline\n";
2463 print "$linenr > $curr_values\n";
2464 print "$linenr > $curr_vars\n";
2466 $prev_values = substr($curr_values, -1);
2468 #ignore lines not being added
2469 next if ($line =~ /^[^\+]/);
2471 # TEST: allow direct testing of the type matcher.
2473 if ($line =~ /^.\s*$Declare\s*$/) {
2475 "TEST: is type\n" . $herecurr);
2476 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2477 ERROR("TEST_NOT_TYPE",
2478 "TEST: is not type ($1 is)\n". $herecurr);
2482 # TEST: allow direct testing of the attribute matcher.
2484 if ($line =~ /^.\s*$Modifier\s*$/) {
2486 "TEST: is attr\n" . $herecurr);
2487 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2488 ERROR("TEST_NOT_ATTR",
2489 "TEST: is not attr ($1 is)\n". $herecurr);
2494 # check for initialisation to aggregates open brace on the next line
2495 if ($line =~ /^.\s*{/ &&
2496 $prevline =~ /(?:^|[^=])=\s*$/) {
2498 "that open brace { should be on the previous line\n" . $hereprev);
2502 # Checks which are anchored on the added line.
2505 # check for malformed paths in #include statements (uses RAW line)
2506 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2508 if ($path =~ m{//}) {
2509 ERROR("MALFORMED_INCLUDE",
2510 "malformed #include filename\n" . $herecurr);
2512 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2513 ERROR("UAPI_INCLUDE",
2514 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2518 # no C99 // comments
2519 if ($line =~ m{//}) {
2520 if (ERROR("C99_COMMENTS",
2521 "do not use C99 // comments\n" . $herecurr) &&
2523 my $line = $fixed[$linenr - 1];
2524 if ($line =~ /\/\/(.*)$/) {
2525 my $comment = trim($1);
2526 $fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@;
2530 # Remove C99 comments.
2532 $opline =~ s@//.*@@;
2534 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2535 # the whole statement.
2536 #print "APW <$lines[$realline_next - 1]>\n";
2537 if (defined $realline_next &&
2538 exists $lines[$realline_next - 1] &&
2539 !defined $suppress_export{$realline_next} &&
2540 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2541 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2542 # Handle definitions which produce identifiers with
2545 # EXPORT_SYMBOL(something_foo);
2547 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2548 $name =~ /^${Ident}_$2/) {
2549 #print "FOO C name<$name>\n";
2550 $suppress_export{$realline_next} = 1;
2552 } elsif ($stat !~ /(?:
2554 ^.DEFINE_$Ident\(\Q$name\E\)|
2555 ^.DECLARE_$Ident\(\Q$name\E\)|
2556 ^.LIST_HEAD\(\Q$name\E\)|
2557 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2558 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2560 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2561 $suppress_export{$realline_next} = 2;
2563 $suppress_export{$realline_next} = 1;
2566 if (!defined $suppress_export{$linenr} &&
2567 $prevline =~ /^.\s*$/ &&
2568 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2569 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2570 #print "FOO B <$lines[$linenr - 1]>\n";
2571 $suppress_export{$linenr} = 2;
2573 if (defined $suppress_export{$linenr} &&
2574 $suppress_export{$linenr} == 2) {
2575 WARN("EXPORT_SYMBOL",
2576 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2579 # check for global initialisers.
2580 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
2581 if (ERROR("GLOBAL_INITIALISERS",
2582 "do not initialise globals to 0 or NULL\n" .
2585 $fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
2588 # check for static initialisers.
2589 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2590 if (ERROR("INITIALISED_STATIC",
2591 "do not initialise statics to 0 or NULL\n" .
2594 $fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
2598 # check for static const char * arrays.
2599 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2600 WARN("STATIC_CONST_CHAR_ARRAY",
2601 "static const char * array should probably be static const char * const\n" .
2605 # check for static char foo[] = "bar" declarations.
2606 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2607 WARN("STATIC_CONST_CHAR_ARRAY",
2608 "static char array declaration should probably be static const char\n" .
2612 # check for declarations of struct pci_device_id
2613 if ($line =~ /\bstruct\s+pci_device_id\s+\w+\s*\[\s*\]\s*\=\s*\{/) {
2614 WARN("DEFINE_PCI_DEVICE_TABLE",
2615 "Use DEFINE_PCI_DEVICE_TABLE for struct pci_device_id\n" . $herecurr);
2618 # check for new typedefs, only function parameters and sparse annotations
2620 if ($line =~ /\btypedef\s/ &&
2621 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2622 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2623 $line !~ /\b$typeTypedefs\b/ &&
2624 $line !~ /\b__bitwise(?:__|)\b/) {
2625 WARN("NEW_TYPEDEFS",
2626 "do not add new typedefs\n" . $herecurr);
2629 # * goes on variable not on type
2631 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2633 my ($ident, $from, $to) = ($1, $2, $2);
2635 # Should start with a space.
2636 $to =~ s/^(\S)/ $1/;
2637 # Should not end with a space.
2639 # '*'s should not have spaces between.
2640 while ($to =~ s/\*\s+\*/\*\*/) {
2643 ## print "1: from<$from> to<$to> ident<$ident>\n";
2645 if (ERROR("POINTER_LOCATION",
2646 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
2648 my $sub_from = $ident;
2649 my $sub_to = $ident;
2650 $sub_to =~ s/\Q$from\E/$to/;
2651 $fixed[$linenr - 1] =~
2652 s@\Q$sub_from\E@$sub_to@;
2656 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2658 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
2660 # Should start with a space.
2661 $to =~ s/^(\S)/ $1/;
2662 # Should not end with a space.
2664 # '*'s should not have spaces between.
2665 while ($to =~ s/\*\s+\*/\*\*/) {
2667 # Modifiers should have spaces.
2668 $to =~ s/(\b$Modifier$)/$1 /;
2670 ## print "2: from<$from> to<$to> ident<$ident>\n";
2671 if ($from ne $to && $ident !~ /^$Modifier$/) {
2672 if (ERROR("POINTER_LOCATION",
2673 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
2676 my $sub_from = $match;
2677 my $sub_to = $match;
2678 $sub_to =~ s/\Q$from\E/$to/;
2679 $fixed[$linenr - 1] =~
2680 s@\Q$sub_from\E@$sub_to@;
2685 # # no BUG() or BUG_ON()
2686 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
2687 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2688 # print "$herecurr";
2692 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2693 WARN("LINUX_VERSION_CODE",
2694 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2697 # check for uses of printk_ratelimit
2698 if ($line =~ /\bprintk_ratelimit\s*\(/) {
2699 WARN("PRINTK_RATELIMITED",
2700 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2703 # printk should use KERN_* levels. Note that follow on printk's on the
2704 # same line do not need a level, so we use the current block context
2705 # to try and find and validate the current printk. In summary the current
2706 # printk includes all preceding printk's which have no newline on the end.
2707 # we assume the first bad printk is the one to report.
2708 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2710 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2711 #print "CHECK<$lines[$ln - 1]\n";
2712 # we have a preceding printk if it ends
2713 # with "\n" ignore it, else it is to blame
2714 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2715 if ($rawlines[$ln - 1] !~ m{\\n"}) {
2722 WARN("PRINTK_WITHOUT_KERN_LEVEL",
2723 "printk() should include KERN_ facility level\n" . $herecurr);
2727 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
2729 my $level = lc($orig);
2730 $level = "warn" if ($level eq "warning");
2731 my $level2 = $level;
2732 $level2 = "dbg" if ($level eq "debug");
2733 WARN("PREFER_PR_LEVEL",
2734 "Prefer netdev_$level2(netdev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
2737 if ($line =~ /\bpr_warning\s*\(/) {
2738 if (WARN("PREFER_PR_LEVEL",
2739 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
2741 $fixed[$linenr - 1] =~
2742 s/\bpr_warning\b/pr_warn/;
2746 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
2748 my $level = lc($orig);
2749 $level = "warn" if ($level eq "warning");
2750 $level = "dbg" if ($level eq "debug");
2751 WARN("PREFER_DEV_LEVEL",
2752 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
2755 # function brace can't be on same line, except for #defines of do while,
2756 # or if closed on same line
2757 if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
2758 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
2760 "open brace '{' following function declarations go on the next line\n" . $herecurr);
2763 # open braces for enum, union and struct go on the same line.
2764 if ($line =~ /^.\s*{/ &&
2765 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2767 "open brace '{' following $1 go on the same line\n" . $hereprev);
2770 # missing space after union, struct or enum definition
2771 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
2773 "missing space after $1 definition\n" . $herecurr) &&
2775 $fixed[$linenr - 1] =~
2776 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
2780 # check for spacing round square brackets; allowed:
2781 # 1. with a type on the left -- int [] a;
2782 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2783 # 3. inside a curly brace -- = { [0...10] = 5 }
2784 while ($line =~ /(.*?\s)\[/g) {
2785 my ($where, $prefix) = ($-[1], $1);
2786 if ($prefix !~ /$Type\s+$/ &&
2787 ($where != 0 || $prefix !~ /^.\s+$/) &&
2788 $prefix !~ /[{,]\s+$/) {
2789 if (ERROR("BRACKET_SPACE",
2790 "space prohibited before open square bracket '['\n" . $herecurr) &&
2792 $fixed[$linenr - 1] =~
2793 s/^(\+.*?)\s+\[/$1\[/;
2798 # check for spaces between functions and their parentheses.
2799 while ($line =~ /($Ident)\s+\(/g) {
2801 my $ctx_before = substr($line, 0, $-[1]);
2802 my $ctx = "$ctx_before$name";
2804 # Ignore those directives where spaces _are_ permitted.
2806 if|for|while|switch|return|case|
2807 volatile|__volatile__|
2808 __attribute__|format|__extension__|
2811 # cpp #define statements have non-optional spaces, ie
2812 # if there is a space between the name and the open
2813 # parenthesis it is simply not a parameter group.
2814 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2816 # cpp #elif statement condition may start with a (
2817 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2819 # If this whole things ends with a type its most
2820 # likely a typedef for a function.
2821 } elsif ($ctx =~ /$Type$/) {
2825 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
2827 $fixed[$linenr - 1] =~
2828 s/\b$name\s+\(/$name\(/;
2833 # Check operator spacing.
2834 if (!($line=~/\#\s*include/)) {
2835 my $fixed_line = "";
2839 <<=|>>=|<=|>=|==|!=|
2840 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2841 =>|->|<<|>>|<|>|=|!|~|
2842 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2845 my @elements = split(/($ops|;)/, $opline);
2847 ## print("element count: <" . $#elements . ">\n");
2848 ## foreach my $el (@elements) {
2849 ## print("el: <$el>\n");
2852 my @fix_elements = ();
2855 foreach my $el (@elements) {
2856 push(@fix_elements, substr($rawline, $off, length($el)));
2857 $off += length($el);
2862 my $blank = copy_spacing($opline);
2863 my $last_after = -1;
2865 for (my $n = 0; $n < $#elements; $n += 2) {
2867 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
2869 ## print("n: <$n> good: <$good>\n");
2871 $off += length($elements[$n]);
2873 # Pick up the preceding and succeeding characters.
2874 my $ca = substr($opline, 0, $off);
2876 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2877 $cc = substr($opline, $off + length($elements[$n + 1]));
2879 my $cb = "$ca$;$cc";
2882 $a = 'V' if ($elements[$n] ne '');
2883 $a = 'W' if ($elements[$n] =~ /\s$/);
2884 $a = 'C' if ($elements[$n] =~ /$;$/);
2885 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2886 $a = 'O' if ($elements[$n] eq '');
2887 $a = 'E' if ($ca =~ /^\s*$/);
2889 my $op = $elements[$n + 1];
2892 if (defined $elements[$n + 2]) {
2893 $c = 'V' if ($elements[$n + 2] ne '');
2894 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2895 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2896 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2897 $c = 'O' if ($elements[$n + 2] eq '');
2898 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2903 my $ctx = "${a}x${c}";
2905 my $at = "(ctx:$ctx)";
2907 my $ptr = substr($blank, 0, $off) . "^";
2908 my $hereptr = "$hereline$ptr\n";
2910 # Pull out the value of this operator.
2911 my $op_type = substr($curr_values, $off + 1, 1);
2913 # Get the full operator variant.
2914 my $opv = $op . substr($curr_vars, $off, 1);
2916 # Ignore operators passed as parameters.
2917 if ($op_type ne 'V' &&
2918 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2921 # } elsif ($op =~ /^$;+$/) {
2923 # ; should have either the end of line or a space or \ after it
2924 } elsif ($op eq ';') {
2925 if ($ctx !~ /.x[WEBC]/ &&
2926 $cc !~ /^\\/ && $cc !~ /^;/) {
2927 if (ERROR("SPACING",
2928 "space required after that '$op' $at\n" . $hereptr)) {
2929 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2935 } elsif ($op eq '//') {
2939 # : when part of a bitfield
2940 } elsif ($op eq '->' || $opv eq ':B') {
2941 if ($ctx =~ /Wx.|.xW/) {
2942 if (ERROR("SPACING",
2943 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
2944 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2945 if (defined $fix_elements[$n + 2]) {
2946 $fix_elements[$n + 2] =~ s/^\s+//;
2952 # , must have a space on the right.
2953 } elsif ($op eq ',') {
2954 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
2955 if (ERROR("SPACING",
2956 "space required after that '$op' $at\n" . $hereptr)) {
2957 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2963 # '*' as part of a type definition -- reported already.
2964 } elsif ($opv eq '*_') {
2965 #warn "'*' is part of type\n";
2967 # unary operators should have a space before and
2968 # none after. May be left adjacent to another
2969 # unary operator, or a cast
2970 } elsif ($op eq '!' || $op eq '~' ||
2971 $opv eq '*U' || $opv eq '-U' ||
2972 $opv eq '&U' || $opv eq '&&U') {
2973 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2974 if (ERROR("SPACING",
2975 "space required before that '$op' $at\n" . $hereptr)) {
2976 if ($n != $last_after + 2) {
2977 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
2982 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2983 # A unary '*' may be const
2985 } elsif ($ctx =~ /.xW/) {
2986 if (ERROR("SPACING",
2987 "space prohibited after that '$op' $at\n" . $hereptr)) {
2988 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
2989 if (defined $fix_elements[$n + 2]) {
2990 $fix_elements[$n + 2] =~ s/^\s+//;
2996 # unary ++ and unary -- are allowed no space on one side.
2997 } elsif ($op eq '++' or $op eq '--') {
2998 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2999 if (ERROR("SPACING",
3000 "space required one side of that '$op' $at\n" . $hereptr)) {
3001 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3005 if ($ctx =~ /Wx[BE]/ ||
3006 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3007 if (ERROR("SPACING",
3008 "space prohibited before that '$op' $at\n" . $hereptr)) {
3009 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3013 if ($ctx =~ /ExW/) {
3014 if (ERROR("SPACING",
3015 "space prohibited after that '$op' $at\n" . $hereptr)) {
3016 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3017 if (defined $fix_elements[$n + 2]) {
3018 $fix_elements[$n + 2] =~ s/^\s+//;
3024 # << and >> may either have or not have spaces both sides
3025 } elsif ($op eq '<<' or $op eq '>>' or
3026 $op eq '&' or $op eq '^' or $op eq '|' or
3027 $op eq '+' or $op eq '-' or
3028 $op eq '*' or $op eq '/' or
3031 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3032 if (ERROR("SPACING",
3033 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3034 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3035 if (defined $fix_elements[$n + 2]) {
3036 $fix_elements[$n + 2] =~ s/^\s+//;
3042 # A colon needs no spaces before when it is
3043 # terminating a case value or a label.
3044 } elsif ($opv eq ':C' || $opv eq ':L') {
3045 if ($ctx =~ /Wx./) {
3046 if (ERROR("SPACING",
3047 "space prohibited before that '$op' $at\n" . $hereptr)) {
3048 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3053 # All the others need spaces both sides.
3054 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3057 # Ignore email addresses <foo@bar>
3059 $cc =~ /^\S+\@\S+>/) ||
3061 $ca =~ /<\S+\@\S+$/))
3066 # messages are ERROR, but ?: are CHK
3068 my $msg_type = \&ERROR;
3069 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3071 if (&{$msg_type}("SPACING",
3072 "spaces required around that '$op' $at\n" . $hereptr)) {
3073 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3074 if (defined $fix_elements[$n + 2]) {
3075 $fix_elements[$n + 2] =~ s/^\s+//;
3081 $off += length($elements[$n + 1]);
3083 ## print("n: <$n> GOOD: <$good>\n");
3085 $fixed_line = $fixed_line . $good;
3088 if (($#elements % 2) == 0) {
3089 $fixed_line = $fixed_line . $fix_elements[$#elements];
3092 if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) {
3093 $fixed[$linenr - 1] = $fixed_line;
3099 # check for whitespace before a non-naked semicolon
3100 if ($line =~ /^\+.*\S\s+;/) {
3102 "space prohibited before semicolon\n" . $herecurr) &&
3104 1 while $fixed[$linenr - 1] =~
3105 s/^(\+.*\S)\s+;/$1;/;
3109 # check for multiple assignments
3110 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3111 CHK("MULTIPLE_ASSIGNMENTS",
3112 "multiple assignments should be avoided\n" . $herecurr);
3115 ## # check for multiple declarations, allowing for a function declaration
3117 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3118 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3120 ## # Remove any bracketed sections to ensure we do not
3121 ## # falsly report the parameters of functions.
3123 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3125 ## if ($ln =~ /,/) {
3126 ## WARN("MULTIPLE_DECLARATION",
3127 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3131 #need space before brace following if, while, etc
3132 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3134 if (ERROR("SPACING",
3135 "space required before the open brace '{'\n" . $herecurr) &&
3137 $fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/;
3141 ## # check for blank lines before declarations
3142 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3143 ## $prevrawline =~ /^.\s*$/) {
3145 ## "No blank lines before declarations\n" . $hereprev);
3149 # closing brace should have a space following it when it has anything
3151 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3152 if (ERROR("SPACING",
3153 "space required after that close brace '}'\n" . $herecurr) &&
3155 $fixed[$linenr - 1] =~
3156 s/}((?!(?:,|;|\)))\S)/} $1/;
3160 # check spacing on square brackets
3161 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3162 if (ERROR("SPACING",
3163 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3165 $fixed[$linenr - 1] =~
3169 if ($line =~ /\s\]/) {
3170 if (ERROR("SPACING",
3171 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3173 $fixed[$linenr - 1] =~
3178 # check spacing on parentheses
3179 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3180 $line !~ /for\s*\(\s+;/) {
3181 if (ERROR("SPACING",
3182 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3184 $fixed[$linenr - 1] =~
3188 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3189 $line !~ /for\s*\(.*;\s+\)/ &&
3190 $line !~ /:\s+\)/) {
3191 if (ERROR("SPACING",
3192 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3194 $fixed[$linenr - 1] =~
3199 #goto labels aren't indented, allow a single space however
3200 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3201 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3202 if (WARN("INDENTED_LABEL",
3203 "labels should not be indented\n" . $herecurr) &&
3205 $fixed[$linenr - 1] =~
3210 # Return is not a function.
3211 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
3215 # Flatten any parentheses
3216 $value =~ s/\(/ \(/g;
3217 $value =~ s/\)/\) /g;
3218 while ($value =~ s/\[[^\[\]]*\]/1/ ||
3219 $value !~ /(?:$Ident|-?$Constant)\s*
3221 (?:$Ident|-?$Constant)/x &&
3222 $value =~ s/\([^\(\)]*\)/1/) {
3224 #print "value<$value>\n";
3225 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
3226 ERROR("RETURN_PARENTHESES",
3227 "return is not a function, parentheses are not required\n" . $herecurr);
3229 } elsif ($spacing !~ /\s+/) {
3231 "space required before the open parenthesis '('\n" . $herecurr);
3234 # Return of what appears to be an errno should normally be -'ve
3235 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3237 if ($name ne 'EOF' && $name ne 'ERROR') {
3238 WARN("USE_NEGATIVE_ERRNO",
3239 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3243 # Need a space before open parenthesis after if, while etc
3244 if ($line =~ /\b(if|while|for|switch)\(/) {
3245 if (ERROR("SPACING",
3246 "space required before the open parenthesis '('\n" . $herecurr) &&
3248 $fixed[$linenr - 1] =~
3249 s/\b(if|while|for|switch)\(/$1 \(/;
3253 # Check for illegal assignment in if conditional -- and check for trailing
3254 # statements after the conditional.
3255 if ($line =~ /do\s*(?!{)/) {
3256 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3257 ctx_statement_block($linenr, $realcnt, 0)
3258 if (!defined $stat);
3259 my ($stat_next) = ctx_statement_block($line_nr_next,
3260 $remain_next, $off_next);
3261 $stat_next =~ s/\n./\n /g;
3262 ##print "stat<$stat> stat_next<$stat_next>\n";
3264 if ($stat_next =~ /^\s*while\b/) {
3265 # If the statement carries leading newlines,
3266 # then count those as offsets.
3268 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3270 statement_rawlines($whitespace) - 1;
3272 $suppress_whiletrailers{$line_nr_next +
3276 if (!defined $suppress_whiletrailers{$linenr} &&
3277 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3278 my ($s, $c) = ($stat, $cond);
3280 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3281 ERROR("ASSIGN_IN_IF",
3282 "do not use assignment in if condition\n" . $herecurr);
3285 # Find out what is on the end of the line after the
3287 substr($s, 0, length($c), '');
3289 $s =~ s/$;//g; # Remove any comments
3290 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3291 $c !~ /}\s*while\s*/)
3293 # Find out how long the conditional actually is.
3294 my @newlines = ($c =~ /\n/gs);
3295 my $cond_lines = 1 + $#newlines;
3298 $stat_real = raw_line($linenr, $cond_lines)
3299 . "\n" if ($cond_lines);
3300 if (defined($stat_real) && $cond_lines > 1) {
3301 $stat_real = "[...]\n$stat_real";
3304 ERROR("TRAILING_STATEMENTS",
3305 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3309 # Check for bitwise tests written as boolean
3321 WARN("HEXADECIMAL_BOOLEAN_TEST",
3322 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3325 # if and else should not have general statements after it
3326 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3328 $s =~ s/$;//g; # Remove any comments
3329 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3330 ERROR("TRAILING_STATEMENTS",
3331 "trailing statements should be on next line\n" . $herecurr);
3334 # if should not continue a brace
3335 if ($line =~ /}\s*if\b/) {
3336 ERROR("TRAILING_STATEMENTS",
3337 "trailing statements should be on next line\n" .
3340 # case and default should not have general statements after them
3341 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
3343 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
3347 ERROR("TRAILING_STATEMENTS",
3348 "trailing statements should be on next line\n" . $herecurr);
3351 # Check for }<nl>else {, these must be at the same
3352 # indent level to be relevant to each other.
3353 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
3354 $previndent == $indent) {
3355 ERROR("ELSE_AFTER_BRACE",
3356 "else should follow close brace '}'\n" . $hereprev);
3359 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
3360 $previndent == $indent) {
3361 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
3363 # Find out what is on the end of the line after the
3365 substr($s, 0, length($c), '');
3368 if ($s =~ /^\s*;/) {
3369 ERROR("WHILE_AFTER_BRACE",
3370 "while should follow close brace '}'\n" . $hereprev);
3374 #Specific variable tests
3375 while ($line =~ m{($Constant|$Lval)}g) {
3378 #gcc binary extension
3379 if ($var =~ /^$Binary$/) {
3380 if (WARN("GCC_BINARY_CONSTANT",
3381 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
3383 my $hexval = sprintf("0x%x", oct($var));
3384 $fixed[$linenr - 1] =~
3385 s/\b$var\b/$hexval/;
3390 if ($var !~ /^$Constant$/ &&
3391 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
3392 #Ignore Page<foo> variants
3393 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
3394 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
3395 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) {
3396 while ($var =~ m{($Ident)}g) {
3398 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
3400 seed_camelcase_includes();
3401 if (!$file && !$camelcase_file_seeded) {
3402 seed_camelcase_file($realfile);
3403 $camelcase_file_seeded = 1;
3406 if (!defined $camelcase{$word}) {
3407 $camelcase{$word} = 1;
3409 "Avoid CamelCase: <$word>\n" . $herecurr);
3415 #no spaces allowed after \ in define
3416 if ($line =~ /\#\s*define.*\\\s+$/) {
3417 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
3418 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
3420 $fixed[$linenr - 1] =~ s/\s+$//;
3424 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
3425 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
3427 my $checkfile = "include/linux/$file";
3428 if (-f "$root/$checkfile" &&
3429 $realfile ne $checkfile &&
3430 $1 !~ /$allowed_asm_includes/)
3432 if ($realfile =~ m{^arch/}) {
3433 CHK("ARCH_INCLUDE_LINUX",
3434 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3436 WARN("INCLUDE_LINUX",
3437 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3442 # multi-statement macros should be enclosed in a do while loop, grab the
3443 # first statement and ensure its the whole macro if its not enclosed
3444 # in a known good container
3445 if ($realfile !~ m@/vmlinux.lds.h$@ &&
3446 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
3449 my ($off, $dstat, $dcond, $rest);
3451 ($dstat, $dcond, $ln, $cnt, $off) =
3452 ctx_statement_block($linenr, $realcnt, 0);
3454 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
3455 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
3457 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
3459 $dstat =~ s/\\\n.//g;
3460 $dstat =~ s/^\s*//s;
3461 $dstat =~ s/\s*$//s;
3463 # Flatten any parentheses and braces
3464 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
3465 $dstat =~ s/\{[^\{\}]*\}/1/ ||
3466 $dstat =~ s/\[[^\[\]]*\]/1/)
3470 # Flatten any obvious string concatentation.
3471 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
3472 $dstat =~ s/$Ident\s*("X*")/$1/)
3476 my $exceptions = qr{
3488 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
3490 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
3491 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
3492 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
3493 $dstat !~ /^'X'$/ && # character constants
3494 $dstat !~ /$exceptions/ &&
3495 $dstat !~ /^\.$Ident\s*=/ && # .foo =
3496 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
3497 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
3498 $dstat !~ /^for\s*$Constant$/ && # for (...)
3499 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
3500 $dstat !~ /^do\s*{/ && # do {...
3501 $dstat !~ /^\({/ && # ({...
3502 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
3505 my $herectx = $here . "\n";
3506 my $cnt = statement_rawlines($ctx);
3508 for (my $n = 0; $n < $cnt; $n++) {
3509 $herectx .= raw_line($linenr, $n) . "\n";
3512 if ($dstat =~ /;/) {
3513 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
3514 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
3516 ERROR("COMPLEX_MACRO",
3517 "Macros with complex values should be enclosed in parenthesis\n" . "$herectx");
3521 # check for line continuations outside of #defines, preprocessor #, and asm
3524 if ($prevline !~ /^..*\\$/ &&
3525 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
3526 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
3527 $line =~ /^\+.*\\$/) {
3528 WARN("LINE_CONTINUATIONS",
3529 "Avoid unnecessary line continuations\n" . $herecurr);
3533 # do {} while (0) macro tests:
3534 # single-statement macros do not need to be enclosed in do while (0) loop,
3535 # macro should not end with a semicolon
3536 if ($^V && $^V ge 5.10.0 &&
3537 $realfile !~ m@/vmlinux.lds.h$@ &&
3538 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
3541 my ($off, $dstat, $dcond, $rest);
3543 ($dstat, $dcond, $ln, $cnt, $off) =
3544 ctx_statement_block($linenr, $realcnt, 0);
3547 $dstat =~ s/\\\n.//g;
3549 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
3554 my $cnt = statement_rawlines($ctx);
3555 my $herectx = $here . "\n";
3557 for (my $n = 0; $n < $cnt; $n++) {
3558 $herectx .= raw_line($linenr, $n) . "\n";
3561 if (($stmts =~ tr/;/;/) == 1 &&
3562 $stmts !~ /^\s*(if|while|for|switch)\b/) {
3563 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
3564 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
3566 if (defined $semis && $semis ne "") {
3567 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
3568 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
3573 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
3574 # all assignments may have only one of the following with an assignment:
3577 # VMLINUX_SYMBOL(...)
3578 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
3579 WARN("MISSING_VMLINUX_SYMBOL",
3580 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
3583 # check for redundant bracing round if etc
3584 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
3585 my ($level, $endln, @chunks) =
3586 ctx_statement_full($linenr, $realcnt, 1);
3587 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
3588 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
3589 if ($#chunks > 0 && $level == 0) {
3593 my $herectx = $here . "\n";
3594 my $ln = $linenr - 1;
3595 for my $chunk (@chunks) {
3596 my ($cond, $block) = @{$chunk};
3598 # If the condition carries leading newlines, then count those as offsets.
3599 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
3600 my $offset = statement_rawlines($whitespace) - 1;
3602 $allowed[$allow] = 0;
3603 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
3605 # We have looked at and allowed this specific line.
3606 $suppress_ifbraces{$ln + $offset} = 1;
3608 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3609 $ln += statement_rawlines($block) - 1;
3611 substr($block, 0, length($cond), '');
3613 $seen++ if ($block =~ /^\s*{/);
3615 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
3616 if (statement_lines($cond) > 1) {
3617 #print "APW: ALLOWED: cond<$cond>\n";
3618 $allowed[$allow] = 1;
3620 if ($block =~/\b(?:if|for|while)\b/) {
3621 #print "APW: ALLOWED: block<$block>\n";
3622 $allowed[$allow] = 1;
3624 if (statement_block_size($block) > 1) {
3625 #print "APW: ALLOWED: lines block<$block>\n";
3626 $allowed[$allow] = 1;
3631 my $sum_allowed = 0;
3632 foreach (@allowed) {
3635 if ($sum_allowed == 0) {
3637 "braces {} are not necessary for any arm of this statement\n" . $herectx);
3638 } elsif ($sum_allowed != $allow &&
3641 "braces {} should be used on all arms of this statement\n" . $herectx);
3646 if (!defined $suppress_ifbraces{$linenr - 1} &&
3647 $line =~ /\b(if|while|for|else)\b/) {
3650 # Check the pre-context.
3651 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3652 #print "APW: ALLOWED: pre<$1>\n";
3656 my ($level, $endln, @chunks) =
3657 ctx_statement_full($linenr, $realcnt, $-[0]);
3659 # Check the condition.
3660 my ($cond, $block) = @{$chunks[0]};
3661 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
3662 if (defined $cond) {
3663 substr($block, 0, length($cond), '');
3665 if (statement_lines($cond) > 1) {
3666 #print "APW: ALLOWED: cond<$cond>\n";
3669 if ($block =~/\b(?:if|for|while)\b/) {
3670 #print "APW: ALLOWED: block<$block>\n";
3673 if (statement_block_size($block) > 1) {
3674 #print "APW: ALLOWED: lines block<$block>\n";
3677 # Check the post-context.
3678 if (defined $chunks[1]) {
3679 my ($cond, $block) = @{$chunks[1]};
3680 if (defined $cond) {
3681 substr($block, 0, length($cond), '');
3683 if ($block =~ /^\s*\{/) {
3684 #print "APW: ALLOWED: chunk-1 block<$block>\n";
3688 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
3689 my $herectx = $here . "\n";
3690 my $cnt = statement_rawlines($block);
3692 for (my $n = 0; $n < $cnt; $n++) {
3693 $herectx .= raw_line($linenr, $n) . "\n";
3697 "braces {} are not necessary for single statement blocks\n" . $herectx);
3701 # check for unnecessary blank lines around braces
3702 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
3704 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
3706 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
3708 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
3711 # no volatiles please
3712 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3713 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
3715 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
3719 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3720 CHK("REDUNDANT_CODE",
3721 "if this code is redundant consider removing it\n" .
3725 # check for needless "if (<foo>) fn(<foo>)" uses
3726 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
3727 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
3728 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
3730 "$1(NULL) is safe this check is probably not required\n" . $hereprev);
3734 sub string_find_replace {
3735 my ($string, $find, $replace) = @_;
3737 $string =~ s/$find/$replace/g;
3742 # check for bad placement of section $InitAttribute (e.g.: __initdata)
3743 if ($line =~ /(\b$InitAttribute\b)/) {
3745 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
3748 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
3749 ERROR("MISPLACED_INIT",
3750 "$attr should be placed after $var\n" . $herecurr)) ||
3751 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
3752 WARN("MISPLACED_INIT",
3753 "$attr should be placed after $var\n" . $herecurr))) &&
3755 $fixed[$linenr - 1] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
3760 # prefer usleep_range over udelay
3761 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
3762 # ignore udelay's < 10, however
3765 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
3769 # warn about unexpectedly long msleep's
3770 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
3773 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
3777 # check for comparisons of jiffies
3778 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
3779 WARN("JIFFIES_COMPARISON",
3780 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
3783 # check for comparisons of get_jiffies_64()
3784 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
3785 WARN("JIFFIES_COMPARISON",
3786 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
3789 # warn about #ifdefs in C files
3790 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3791 # print "#ifdef in C files should be avoided\n";
3792 # print "$herecurr";
3796 # warn about spacing in #ifdefs
3797 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3798 if (ERROR("SPACING",
3799 "exactly one space required after that #$1\n" . $herecurr) &&
3801 $fixed[$linenr - 1] =~
3802 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
3807 # check for spinlock_t definitions without a comment.
3808 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
3809 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
3811 if (!ctx_has_comment($first_line, $linenr)) {
3812 CHK("UNCOMMENTED_DEFINITION",
3813 "$1 definition without comment\n" . $herecurr);
3816 # check for memory barriers without a comment.
3817 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
3818 if (!ctx_has_comment($first_line, $linenr)) {
3819 CHK("MEMORY_BARRIER",
3820 "memory barrier without comment\n" . $herecurr);
3823 # check of hardware specific defines
3824 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
3826 "architecture specific defines should be avoided\n" . $herecurr);
3829 # Check that the storage class is at the beginning of a declaration
3830 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
3831 WARN("STORAGE_CLASS",
3832 "storage class should be at the beginning of the declaration\n" . $herecurr)
3835 # check the location of the inline attribute, that it is between
3836 # storage class and type.
3837 if ($line =~ /\b$Type\s+$Inline\b/ ||
3838 $line =~ /\b$Inline\s+$Storage\b/) {
3839 ERROR("INLINE_LOCATION",
3840 "inline keyword should sit between storage class and type\n" . $herecurr);
3843 # Check for __inline__ and __inline, prefer inline
3844 if ($line =~ /\b(__inline__|__inline)\b/) {
3846 "plain inline is preferred over $1\n" . $herecurr) &&
3848 $fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/;
3853 # Check for __attribute__ packed, prefer __packed
3854 if ($line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
3855 WARN("PREFER_PACKED",
3856 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
3859 # Check for __attribute__ aligned, prefer __aligned
3860 if ($line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
3861 WARN("PREFER_ALIGNED",
3862 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
3865 # Check for __attribute__ format(printf, prefer __printf
3866 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
3867 if (WARN("PREFER_PRINTF",
3868 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
3870 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
3875 # Check for __attribute__ format(scanf, prefer __scanf
3876 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
3877 if (WARN("PREFER_SCANF",
3878 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
3880 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
3884 # check for sizeof(&)
3885 if ($line =~ /\bsizeof\s*\(\s*\&/) {
3886 WARN("SIZEOF_ADDRESS",
3887 "sizeof(& should be avoided\n" . $herecurr);
3890 # check for sizeof without parenthesis
3891 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
3892 if (WARN("SIZEOF_PARENTHESIS",
3893 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
3895 $fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
3899 # check for line continuations in quoted strings with odd counts of "
3900 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
3901 WARN("LINE_CONTINUATIONS",
3902 "Avoid line continuations in quoted strings\n" . $herecurr);
3905 # check for struct spinlock declarations
3906 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
3907 WARN("USE_SPINLOCK_T",
3908 "struct spinlock should be spinlock_t\n" . $herecurr);
3911 # check for seq_printf uses that could be seq_puts
3912 if ($line =~ /\bseq_printf\s*\(/) {
3913 my $fmt = get_quoted_string($line, $rawline);
3914 if ($fmt !~ /[^\\]\%/) {
3915 if (WARN("PREFER_SEQ_PUTS",
3916 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
3918 $fixed[$linenr - 1] =~ s/\bseq_printf\b/seq_puts/;
3923 # Check for misused memsets
3924 if ($^V && $^V ge 5.10.0 &&
3926 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
3932 if ($ms_size =~ /^(0x|)0$/i) {
3934 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
3935 } elsif ($ms_size =~ /^(0x|)1$/i) {
3937 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
3941 # typecasts on min/max could be min_t/max_t
3942 if ($^V && $^V ge 5.10.0 &&
3944 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
3945 if (defined $2 || defined $7) {
3947 my $cast1 = deparenthesize($2);
3949 my $cast2 = deparenthesize($7);
3953 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
3954 $cast = "$cast1 or $cast2";
3955 } elsif ($cast1 ne "") {
3961 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
3965 # check usleep_range arguments
3966 if ($^V && $^V ge 5.10.0 &&
3968 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
3972 WARN("USLEEP_RANGE",
3973 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3974 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
3976 WARN("USLEEP_RANGE",
3977 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3981 # check for new externs in .h files.
3982 if ($realfile =~ /\.h$/ &&
3983 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
3984 if (CHK("AVOID_EXTERNS",
3985 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
3987 $fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
3991 # check for new externs in .c files.
3992 if ($realfile =~ /\.c$/ && defined $stat &&
3993 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
3995 my $function_name = $1;
3996 my $paren_space = $2;
3999 if (defined $cond) {
4000 substr($s, 0, length($cond), '');
4002 if ($s =~ /^\s*;/ &&
4003 $function_name ne 'uninitialized_var')
4005 WARN("AVOID_EXTERNS",
4006 "externs should be avoided in .c files\n" . $herecurr);
4009 if ($paren_space =~ /\n/) {
4010 WARN("FUNCTION_ARGUMENTS",
4011 "arguments for function declarations should follow identifier\n" . $herecurr);
4014 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4015 $stat =~ /^.\s*extern\s+/)
4017 WARN("AVOID_EXTERNS",
4018 "externs should be avoided in .c files\n" . $herecurr);
4021 # checks for new __setup's
4022 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4025 if (!grep(/$name/, @setup_docs)) {
4026 CHK("UNDOCUMENTED_SETUP",
4027 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4031 # check for pointless casting of kmalloc return
4032 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4033 WARN("UNNECESSARY_CASTS",
4034 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4038 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4039 if ($^V && $^V ge 5.10.0 &&
4040 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4041 CHK("ALLOC_SIZEOF_STRUCT",
4042 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4045 # check for krealloc arg reuse
4046 if ($^V && $^V ge 5.10.0 &&
4047 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
4048 WARN("KREALLOC_ARG_REUSE",
4049 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
4052 # check for alloc argument mismatch
4053 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
4054 WARN("ALLOC_ARRAY_ARGS",
4055 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
4058 # check for multiple semicolons
4059 if ($line =~ /;\s*;\s*$/) {
4060 if (WARN("ONE_SEMICOLON",
4061 "Statements terminations use 1 semicolon\n" . $herecurr) &&
4063 $fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g;
4067 # check for switch/default statements without a break;
4068 if ($^V && $^V ge 5.10.0 &&
4070 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
4072 my $herectx = $here . "\n";
4073 my $cnt = statement_rawlines($stat);
4074 for (my $n = 0; $n < $cnt; $n++) {
4075 $herectx .= raw_line($linenr, $n) . "\n";
4077 WARN("DEFAULT_NO_BREAK",
4078 "switch default: should use break\n" . $herectx);
4081 # check for gcc specific __FUNCTION__
4082 if ($line =~ /\b__FUNCTION__\b/) {
4083 if (WARN("USE_FUNC",
4084 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
4086 $fixed[$linenr - 1] =~ s/\b__FUNCTION__\b/__func__/g;
4090 # check for use of yield()
4091 if ($line =~ /\byield\s*\(\s*\)/) {
4093 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
4096 # check for comparisons against true and false
4097 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
4105 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
4107 my $type = lc($otype);
4108 if ($type =~ /^(?:true|false)$/) {
4109 if (("$test" eq "==" && "$type" eq "true") ||
4110 ("$test" eq "!=" && "$type" eq "false")) {
4114 CHK("BOOL_COMPARISON",
4115 "Using comparison to $otype is error prone\n" . $herecurr);
4117 ## maybe suggesting a correct construct would better
4118 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
4123 # check for semaphores initialized locked
4124 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
4125 WARN("CONSIDER_COMPLETION",
4126 "consider using a completion\n" . $herecurr);
4129 # recommend kstrto* over simple_strto* and strict_strto*
4130 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
4131 WARN("CONSIDER_KSTRTO",
4132 "$1 is obsolete, use k$3 instead\n" . $herecurr);
4135 # check for __initcall(), use device_initcall() explicitly please
4136 if ($line =~ /^.\s*__initcall\s*\(/) {
4137 WARN("USE_DEVICE_INITCALL",
4138 "please use device_initcall() instead of __initcall()\n" . $herecurr);
4141 # check for various ops structs, ensure they are const.
4142 my $struct_ops = qr{acpi_dock_ops|
4143 address_space_operations|
4145 block_device_operations|
4150 file_lock_operations|
4160 lock_manager_operations|
4166 pipe_buf_operations|
4167 platform_hibernation_ops|
4168 platform_suspend_ops|
4173 soc_pcmcia_socket_ops|
4179 if ($line !~ /\bconst\b/ &&
4180 $line =~ /\bstruct\s+($struct_ops)\b/) {
4181 WARN("CONST_STRUCT",
4182 "struct $1 should normally be const\n" .
4186 # use of NR_CPUS is usually wrong
4187 # ignore definitions of NR_CPUS and usage to define arrays as likely right
4188 if ($line =~ /\bNR_CPUS\b/ &&
4189 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
4190 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
4191 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
4192 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
4193 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
4196 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
4199 # check for %L{u,d,i} in strings
4201 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4202 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4203 $string =~ s/%%/__/g;
4204 if ($string =~ /(?<!%)%L[udi]/) {
4206 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4211 # whine mightly about in_atomic
4212 if ($line =~ /\bin_atomic\s*\(/) {
4213 if ($realfile =~ m@^drivers/@) {
4215 "do not use in_atomic in drivers\n" . $herecurr);
4216 } elsif ($realfile !~ m@^kernel/@) {
4218 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
4222 # check for lockdep_set_novalidate_class
4223 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
4224 $line =~ /__lockdep_no_validate__\s*\)/ ) {
4225 if ($realfile !~ m@^kernel/lockdep@ &&
4226 $realfile !~ m@^include/linux/lockdep@ &&
4227 $realfile !~ m@^drivers/base/core@) {
4229 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
4233 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
4234 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
4235 WARN("EXPORTED_WORLD_WRITABLE",
4236 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
4240 # If we have no input at all, then there is nothing to report on
4241 # so just keep quiet.
4242 if ($#rawlines == -1) {
4246 # In mailback mode only produce a report in the negative, for
4247 # things that appear to be patches.
4248 if ($mailback && ($clean == 1 || !$is_patch)) {
4252 # This is not a patch, and we are are in 'no-patch' mode so
4254 if (!$chk_patch && !$is_patch) {
4259 ERROR("NOT_UNIFIED_DIFF",
4260 "Does not appear to be a unified-diff format patch\n");
4262 if ($is_patch && $chk_signoff && $signoff == 0) {
4263 ERROR("MISSING_SIGN_OFF",
4264 "Missing Signed-off-by: line(s)\n");
4267 print report_dump();
4268 if ($summary && !($clean == 1 && $quiet == 1)) {
4269 print "$filename " if ($summary_file);
4270 print "total: $cnt_error errors, $cnt_warn warnings, " .
4271 (($check)? "$cnt_chk checks, " : "") .
4272 "$cnt_lines lines checked\n";
4273 print "\n" if ($quiet == 0);
4278 if ($^V lt 5.10.0) {
4279 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
4280 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
4283 # If there were whitespace errors which cleanpatch can fix
4284 # then suggest that.
4285 if ($rpt_cleaners) {
4286 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
4287 print " scripts/cleanfile\n\n";
4292 hash_show_words(\%use_type, "Used");
4293 hash_show_words(\%ignore_type, "Ignored");
4295 if ($clean == 0 && $fix && "@rawlines" ne "@fixed") {
4296 my $newfile = $filename . ".EXPERIMENTAL-checkpatch-fixes";
4300 open($f, '>', $newfile)
4301 or die "$P: Can't open $newfile for write\n";
4302 foreach my $fixed_line (@fixed) {
4305 if ($linecount > 3) {
4306 $fixed_line =~ s/^\+//;
4307 print $f $fixed_line. "\n";
4310 print $f $fixed_line . "\n";
4317 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
4319 Do _NOT_ trust the results written to this file.
4320 Do _NOT_ submit these changes without inspecting them for correctness.
4322 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
4323 No warranties, expressed or implied...
4329 if ($clean == 1 && $quiet == 0) {
4330 print "$vname has no obvious style problems and is ready for submission.\n"
4332 if ($clean == 0 && $quiet == 0) {
4334 $vname has style problems, please review.
4336 If any of these errors are false positives, please report
4337 them to the maintainer, see CHECKPATCH in MAINTAINERS.