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|)|
327 seq_vprintf|seq_printf|seq_puts
330 our $signature_tags = qr{(?xi:
343 qr{(?:unsigned\s+)?char},
344 qr{(?:unsigned\s+)?short},
345 qr{(?:unsigned\s+)?int},
346 qr{(?:unsigned\s+)?long},
347 qr{(?:unsigned\s+)?long\s+int},
348 qr{(?:unsigned\s+)?long\s+long},
349 qr{(?:unsigned\s+)?long\s+long\s+int},
358 qr{${Ident}_handler},
359 qr{${Ident}_handler_fn},
361 our @typeListWithAttr = (
363 qr{struct\s+$InitAttribute\s+$Ident},
364 qr{union\s+$InitAttribute\s+$Ident},
367 our @modifierList = (
371 our $allowed_asm_includes = qr{(?x:
375 # memory.h: ARM has a custom one
378 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
379 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
380 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
381 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
383 (?:$Modifier\s+|const\s+)*
385 (?:typeof|__typeof__)\s*\([^\)]*\)|
389 (?:\s+$Modifier|\s+const)*
391 $NonptrTypeWithAttr = qr{
392 (?:$Modifier\s+|const\s+)*
394 (?:typeof|__typeof__)\s*\([^\)]*\)|
398 (?:\s+$Modifier|\s+const)*
402 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*|\[\])+|(?:\s*\[\s*\])+)?
403 (?:\s+$Inline|\s+$Modifier)*
405 $Declare = qr{(?:$Storage\s+)?$Type};
409 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
411 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
412 # requires at least perl version v5.10.0
413 # Any use must be runtime checked with $^V
415 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
416 our $LvalOrFunc = qr{($Lval)\s*($balanced_parens{0,1})\s*};
417 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
421 return "" if (!defined($string));
422 $string =~ s@^\s*\(\s*@@g;
423 $string =~ s@\s*\)\s*$@@g;
424 $string =~ s@\s+@ @g;
428 sub seed_camelcase_file {
431 return if (!(-f $file));
435 open(my $include_file, '<', "$file")
436 or warn "$P: Can't read '$file' $!\n";
437 my $text = <$include_file>;
438 close($include_file);
440 my @lines = split('\n', $text);
442 foreach my $line (@lines) {
443 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
444 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*[\(\[,;]/) {
448 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
454 my $camelcase_seeded = 0;
455 sub seed_camelcase_includes {
456 return if ($camelcase_seeded);
459 my $camelcase_cache = "";
460 my @include_files = ();
462 $camelcase_seeded = 1;
465 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
466 chomp $git_last_include_commit;
467 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
469 my $last_mod_date = 0;
470 $files = `find $root/include -name "*.h"`;
471 @include_files = split('\n', $files);
472 foreach my $file (@include_files) {
473 my $date = POSIX::strftime("%Y%m%d%H%M",
474 localtime((stat $file)[9]));
475 $last_mod_date = $date if ($last_mod_date < $date);
477 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
480 if ($camelcase_cache ne "" && -f $camelcase_cache) {
481 open(my $camelcase_file, '<', "$camelcase_cache")
482 or warn "$P: Can't read '$camelcase_cache' $!\n";
483 while (<$camelcase_file>) {
487 close($camelcase_file);
493 $files = `git ls-files "include/*.h"`;
494 @include_files = split('\n', $files);
497 foreach my $file (@include_files) {
498 seed_camelcase_file($file);
501 if ($camelcase_cache ne "") {
502 unlink glob ".checkpatch-camelcase.*";
503 open(my $camelcase_file, '>', "$camelcase_cache")
504 or warn "$P: Can't write '$camelcase_cache' $!\n";
505 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
506 print $camelcase_file ("$_\n");
508 close($camelcase_file);
512 $chk_signoff = 0 if ($file);
518 for my $filename (@ARGV) {
521 open($FILE, '-|', "diff -u /dev/null $filename") ||
522 die "$P: $filename: diff failed - $!\n";
523 } elsif ($filename eq '-') {
524 open($FILE, '<&STDIN');
526 open($FILE, '<', "$filename") ||
527 die "$P: $filename: open failed - $!\n";
529 if ($filename eq '-') {
530 $vname = 'Your patch';
539 if (!process($filename)) {
549 sub top_of_kernel_tree {
553 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
554 "README", "Documentation", "arch", "include", "drivers",
555 "fs", "init", "ipc", "kernel", "lib", "scripts",
558 foreach my $check (@tree_check) {
559 if (! -e $root . '/' . $check) {
567 my ($formatted_email) = @_;
573 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
576 $comment = $3 if defined $3;
577 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
579 $comment = $2 if defined $2;
580 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
582 $comment = $2 if defined $2;
583 $formatted_email =~ s/$address.*$//;
584 $name = $formatted_email;
586 $name =~ s/^\"|\"$//g;
587 # If there's a name left after stripping spaces and
588 # leading quotes, and the address doesn't have both
589 # leading and trailing angle brackets, the address
591 # "joe smith joe@smith.com" bad
592 # "joe smith <joe@smith.com" bad
593 if ($name ne "" && $address !~ /^<[^>]+>$/) {
601 $name =~ s/^\"|\"$//g;
602 $address = trim($address);
603 $address =~ s/^\<|\>$//g;
605 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
606 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
610 return ($name, $address, $comment);
614 my ($name, $address) = @_;
619 $name =~ s/^\"|\"$//g;
620 $address = trim($address);
622 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
623 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
628 $formatted_email = "$address";
630 $formatted_email = "$name <$address>";
633 return $formatted_email;
639 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
640 if (-e "$path/$conf") {
641 return "$path/$conf";
653 for my $c (split(//, $str)) {
657 for (; ($n % 8) != 0; $n++) {
669 (my $res = shift) =~ tr/\t/ /c;
676 # Drop the diff line leader and expand tabs
678 $line = expand_tabs($line);
680 # Pick the indent from the front of the line.
681 my ($white) = ($line =~ /^(\s*)/);
683 return (length($line), length($white));
686 my $sanitise_quote = '';
688 sub sanitise_line_reset {
689 my ($in_comment) = @_;
692 $sanitise_quote = '*/';
694 $sanitise_quote = '';
707 # Always copy over the diff marker.
708 $res = substr($line, 0, 1);
710 for ($off = 1; $off < length($line); $off++) {
711 $c = substr($line, $off, 1);
713 # Comments we are wacking completly including the begin
714 # and end, all to $;.
715 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
716 $sanitise_quote = '*/';
718 substr($res, $off, 2, "$;$;");
722 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
723 $sanitise_quote = '';
724 substr($res, $off, 2, "$;$;");
728 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
729 $sanitise_quote = '//';
731 substr($res, $off, 2, $sanitise_quote);
736 # A \ in a string means ignore the next character.
737 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
739 substr($res, $off, 2, 'XX');
744 if ($c eq "'" || $c eq '"') {
745 if ($sanitise_quote eq '') {
746 $sanitise_quote = $c;
748 substr($res, $off, 1, $c);
750 } elsif ($sanitise_quote eq $c) {
751 $sanitise_quote = '';
755 #print "c<$c> SQ<$sanitise_quote>\n";
756 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
757 substr($res, $off, 1, $;);
758 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
759 substr($res, $off, 1, $;);
760 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
761 substr($res, $off, 1, 'X');
763 substr($res, $off, 1, $c);
767 if ($sanitise_quote eq '//') {
768 $sanitise_quote = '';
771 # The pathname on a #include may be surrounded by '<' and '>'.
772 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
773 my $clean = 'X' x length($1);
774 $res =~ s@\<.*\>@<$clean>@;
776 # The whole of a #error is a string.
777 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
778 my $clean = 'X' x length($1);
779 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
785 sub get_quoted_string {
786 my ($line, $rawline) = @_;
788 return "" if ($line !~ m/(\"[X]+\")/g);
789 return substr($rawline, $-[0], $+[0] - $-[0]);
792 sub ctx_statement_block {
793 my ($linenr, $remain, $off) = @_;
794 my $line = $linenr - 1;
811 @stack = (['', 0]) if ($#stack == -1);
813 #warn "CSB: blk<$blk> remain<$remain>\n";
814 # If we are about to drop off the end, pull in more
817 for (; $remain > 0; $line++) {
818 last if (!defined $lines[$line]);
819 next if ($lines[$line] =~ /^-/);
822 $blk .= $lines[$line] . "\n";
827 # Bail if there is no further context.
828 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
832 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
838 $c = substr($blk, $off, 1);
839 $remainder = substr($blk, $off);
841 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
843 # Handle nested #if/#else.
844 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
845 push(@stack, [ $type, $level ]);
846 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
847 ($type, $level) = @{$stack[$#stack - 1]};
848 } elsif ($remainder =~ /^#\s*endif\b/) {
849 ($type, $level) = @{pop(@stack)};
852 # Statement ends at the ';' or a close '}' at the
854 if ($level == 0 && $c eq ';') {
858 # An else is really a conditional as long as its not else if
859 if ($level == 0 && $coff_set == 0 &&
860 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
861 $remainder =~ /^(else)(?:\s|{)/ &&
862 $remainder !~ /^else\s+if\b/) {
863 $coff = $off + length($1) - 1;
865 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
866 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
869 if (($type eq '' || $type eq '(') && $c eq '(') {
873 if ($type eq '(' && $c eq ')') {
875 $type = ($level != 0)? '(' : '';
877 if ($level == 0 && $coff < $soff) {
880 #warn "CSB: mark coff<$coff>\n";
883 if (($type eq '' || $type eq '{') && $c eq '{') {
887 if ($type eq '{' && $c eq '}') {
889 $type = ($level != 0)? '{' : '';
892 if (substr($blk, $off + 1, 1) eq ';') {
898 # Preprocessor commands end at the newline unless escaped.
899 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
907 # We are truly at the end, so shuffle to the next line.
914 my $statement = substr($blk, $soff, $off - $soff + 1);
915 my $condition = substr($blk, $soff, $coff - $soff + 1);
917 #warn "STATEMENT<$statement>\n";
918 #warn "CONDITION<$condition>\n";
920 #print "coff<$coff> soff<$off> loff<$loff>\n";
922 return ($statement, $condition,
923 $line, $remain + 1, $off - $loff + 1, $level);
926 sub statement_lines {
929 # Strip the diff line prefixes and rip blank lines at start and end.
930 $stmt =~ s/(^|\n)./$1/g;
934 my @stmt_lines = ($stmt =~ /\n/g);
936 return $#stmt_lines + 2;
939 sub statement_rawlines {
942 my @stmt_lines = ($stmt =~ /\n/g);
944 return $#stmt_lines + 2;
947 sub statement_block_size {
950 $stmt =~ s/(^|\n)./$1/g;
956 my @stmt_lines = ($stmt =~ /\n/g);
957 my @stmt_statements = ($stmt =~ /;/g);
959 my $stmt_lines = $#stmt_lines + 2;
960 my $stmt_statements = $#stmt_statements + 1;
962 if ($stmt_lines > $stmt_statements) {
965 return $stmt_statements;
969 sub ctx_statement_full {
970 my ($linenr, $remain, $off) = @_;
971 my ($statement, $condition, $level);
975 # Grab the first conditional/block pair.
976 ($statement, $condition, $linenr, $remain, $off, $level) =
977 ctx_statement_block($linenr, $remain, $off);
978 #print "F: c<$condition> s<$statement> remain<$remain>\n";
979 push(@chunks, [ $condition, $statement ]);
980 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
981 return ($level, $linenr, @chunks);
984 # Pull in the following conditional/block pairs and see if they
985 # could continue the statement.
987 ($statement, $condition, $linenr, $remain, $off, $level) =
988 ctx_statement_block($linenr, $remain, $off);
989 #print "C: c<$condition> s<$statement> remain<$remain>\n";
990 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
992 push(@chunks, [ $condition, $statement ]);
995 return ($level, $linenr, @chunks);
999 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1001 my $start = $linenr - 1;
1008 my @stack = ($level);
1009 for ($line = $start; $remain > 0; $line++) {
1010 next if ($rawlines[$line] =~ /^-/);
1013 $blk .= $rawlines[$line];
1015 # Handle nested #if/#else.
1016 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1017 push(@stack, $level);
1018 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1019 $level = $stack[$#stack - 1];
1020 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1021 $level = pop(@stack);
1024 foreach my $c (split(//, $lines[$line])) {
1025 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1031 if ($c eq $close && $level > 0) {
1033 last if ($level == 0);
1034 } elsif ($c eq $open) {
1039 if (!$outer || $level <= 1) {
1040 push(@res, $rawlines[$line]);
1043 last if ($level == 0);
1046 return ($level, @res);
1048 sub ctx_block_outer {
1049 my ($linenr, $remain) = @_;
1051 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1055 my ($linenr, $remain) = @_;
1057 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1061 my ($linenr, $remain, $off) = @_;
1063 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1066 sub ctx_block_level {
1067 my ($linenr, $remain) = @_;
1069 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1071 sub ctx_statement_level {
1072 my ($linenr, $remain, $off) = @_;
1074 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1077 sub ctx_locate_comment {
1078 my ($first_line, $end_line) = @_;
1080 # Catch a comment on the end of the line itself.
1081 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1082 return $current_comment if (defined $current_comment);
1084 # Look through the context and try and figure out if there is a
1087 $current_comment = '';
1088 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1089 my $line = $rawlines[$linenr - 1];
1091 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1094 if ($line =~ m@/\*@) {
1097 if (!$in_comment && $current_comment ne '') {
1098 $current_comment = '';
1100 $current_comment .= $line . "\n" if ($in_comment);
1101 if ($line =~ m@\*/@) {
1106 chomp($current_comment);
1107 return($current_comment);
1109 sub ctx_has_comment {
1110 my ($first_line, $end_line) = @_;
1111 my $cmt = ctx_locate_comment($first_line, $end_line);
1113 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1114 ##print "CMMT: $cmt\n";
1116 return ($cmt ne '');
1120 my ($linenr, $cnt) = @_;
1122 my $offset = $linenr - 1;
1127 $line = $rawlines[$offset++];
1128 next if (defined($line) && $line =~ /^-/);
1140 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1143 $coded = sprintf("^%c", unpack('C', $2) + 64);
1152 my $av_preprocessor = 0;
1157 sub annotate_reset {
1158 $av_preprocessor = 0;
1160 @av_paren_type = ('E');
1161 $av_pend_colon = 'O';
1164 sub annotate_values {
1165 my ($stream, $type) = @_;
1168 my $var = '_' x length($stream);
1171 print "$stream\n" if ($dbg_values > 1);
1173 while (length($cur)) {
1174 @av_paren_type = ('E') if ($#av_paren_type < 0);
1175 print " <" . join('', @av_paren_type) .
1176 "> <$type> <$av_pending>" if ($dbg_values > 1);
1177 if ($cur =~ /^(\s+)/o) {
1178 print "WS($1)\n" if ($dbg_values > 1);
1179 if ($1 =~ /\n/ && $av_preprocessor) {
1180 $type = pop(@av_paren_type);
1181 $av_preprocessor = 0;
1184 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1185 print "CAST($1)\n" if ($dbg_values > 1);
1186 push(@av_paren_type, $type);
1189 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1190 print "DECLARE($1)\n" if ($dbg_values > 1);
1193 } elsif ($cur =~ /^($Modifier)\s*/) {
1194 print "MODIFIER($1)\n" if ($dbg_values > 1);
1197 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1198 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1199 $av_preprocessor = 1;
1200 push(@av_paren_type, $type);
1206 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1207 print "UNDEF($1)\n" if ($dbg_values > 1);
1208 $av_preprocessor = 1;
1209 push(@av_paren_type, $type);
1211 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1212 print "PRE_START($1)\n" if ($dbg_values > 1);
1213 $av_preprocessor = 1;
1215 push(@av_paren_type, $type);
1216 push(@av_paren_type, $type);
1219 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1220 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1221 $av_preprocessor = 1;
1223 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1227 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1228 print "PRE_END($1)\n" if ($dbg_values > 1);
1230 $av_preprocessor = 1;
1232 # Assume all arms of the conditional end as this
1233 # one does, and continue as if the #endif was not here.
1234 pop(@av_paren_type);
1235 push(@av_paren_type, $type);
1238 } elsif ($cur =~ /^(\\\n)/o) {
1239 print "PRECONT($1)\n" if ($dbg_values > 1);
1241 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1242 print "ATTR($1)\n" if ($dbg_values > 1);
1243 $av_pending = $type;
1246 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1247 print "SIZEOF($1)\n" if ($dbg_values > 1);
1253 } elsif ($cur =~ /^(if|while|for)\b/o) {
1254 print "COND($1)\n" if ($dbg_values > 1);
1258 } elsif ($cur =~/^(case)/o) {
1259 print "CASE($1)\n" if ($dbg_values > 1);
1260 $av_pend_colon = 'C';
1263 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1264 print "KEYWORD($1)\n" if ($dbg_values > 1);
1267 } elsif ($cur =~ /^(\()/o) {
1268 print "PAREN('$1')\n" if ($dbg_values > 1);
1269 push(@av_paren_type, $av_pending);
1273 } elsif ($cur =~ /^(\))/o) {
1274 my $new_type = pop(@av_paren_type);
1275 if ($new_type ne '_') {
1277 print "PAREN('$1') -> $type\n"
1278 if ($dbg_values > 1);
1280 print "PAREN('$1')\n" if ($dbg_values > 1);
1283 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1284 print "FUNC($1)\n" if ($dbg_values > 1);
1288 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1289 if (defined $2 && $type eq 'C' || $type eq 'T') {
1290 $av_pend_colon = 'B';
1291 } elsif ($type eq 'E') {
1292 $av_pend_colon = 'L';
1294 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1297 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1298 print "IDENT($1)\n" if ($dbg_values > 1);
1301 } elsif ($cur =~ /^($Assignment)/o) {
1302 print "ASSIGN($1)\n" if ($dbg_values > 1);
1305 } elsif ($cur =~/^(;|{|})/) {
1306 print "END($1)\n" if ($dbg_values > 1);
1308 $av_pend_colon = 'O';
1310 } elsif ($cur =~/^(,)/) {
1311 print "COMMA($1)\n" if ($dbg_values > 1);
1314 } elsif ($cur =~ /^(\?)/o) {
1315 print "QUESTION($1)\n" if ($dbg_values > 1);
1318 } elsif ($cur =~ /^(:)/o) {
1319 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1321 substr($var, length($res), 1, $av_pend_colon);
1322 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1327 $av_pend_colon = 'O';
1329 } elsif ($cur =~ /^(\[)/o) {
1330 print "CLOSE($1)\n" if ($dbg_values > 1);
1333 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1336 print "OPV($1)\n" if ($dbg_values > 1);
1343 substr($var, length($res), 1, $variant);
1346 } elsif ($cur =~ /^($Operators)/o) {
1347 print "OP($1)\n" if ($dbg_values > 1);
1348 if ($1 ne '++' && $1 ne '--') {
1352 } elsif ($cur =~ /(^.)/o) {
1353 print "C($1)\n" if ($dbg_values > 1);
1356 $cur = substr($cur, length($1));
1357 $res .= $type x length($1);
1361 return ($res, $var);
1365 my ($possible, $line) = @_;
1366 my $notPermitted = qr{(?:
1383 ^(?:typedef|struct|enum)\b
1385 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1386 if ($possible !~ $notPermitted) {
1387 # Check for modifiers.
1388 $possible =~ s/\s*$Storage\s*//g;
1389 $possible =~ s/\s*$Sparse\s*//g;
1390 if ($possible =~ /^\s*$/) {
1392 } elsif ($possible =~ /\s/) {
1393 $possible =~ s/\s*$Type\s*//g;
1394 for my $modifier (split(' ', $possible)) {
1395 if ($modifier !~ $notPermitted) {
1396 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1397 push(@modifierList, $modifier);
1402 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1403 push(@typeList, $possible);
1407 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1414 return defined $use_type{$_[0]} if (scalar keys %use_type > 0);
1416 return !defined $ignore_type{$_[0]};
1420 if (!show_type($_[1]) ||
1421 (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) {
1426 $line = "$prefix$_[0]:$_[1]: $_[2]\n";
1428 $line = "$prefix$_[0]: $_[2]\n";
1430 $line = (split('\n', $line))[0] . "\n" if ($terse);
1432 push(our @report, $line);
1441 if (report("ERROR", $_[0], $_[1])) {
1449 if (report("WARNING", $_[0], $_[1])) {
1457 if ($check && report("CHECK", $_[0], $_[1])) {
1465 sub check_absolute_file {
1466 my ($absolute, $herecurr) = @_;
1467 my $file = $absolute;
1469 ##print "absolute<$absolute>\n";
1471 # See if any suffix of this path is a path within the tree.
1472 while ($file =~ s@^[^/]*/@@) {
1473 if (-f "$root/$file") {
1474 ##print "file<$file>\n";
1482 # It is, so see if the prefix is acceptable.
1483 my $prefix = $absolute;
1484 substr($prefix, -length($file)) = '';
1486 ##print "prefix<$prefix>\n";
1487 if ($prefix ne ".../") {
1488 WARN("USE_RELATIVE_PATH",
1489 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1496 $string =~ s/^\s+|\s+$//g;
1504 $string =~ s/^\s+//;
1512 $string =~ s/\s+$//;
1517 sub string_find_replace {
1518 my ($string, $find, $replace) = @_;
1520 $string =~ s/$find/$replace/g;
1528 my $source_indent = 8;
1529 my $max_spaces_before_tab = $source_indent - 1;
1530 my $spaces_to_tab = " " x $source_indent;
1532 #convert leading spaces to tabs
1533 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1534 #Remove spaces before a tab
1535 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1540 sub pos_last_openparen {
1545 my $opens = $line =~ tr/\(/\(/;
1546 my $closes = $line =~ tr/\)/\)/;
1548 my $last_openparen = 0;
1550 if (($opens == 0) || ($closes >= $opens)) {
1554 my $len = length($line);
1556 for ($pos = 0; $pos < $len; $pos++) {
1557 my $string = substr($line, $pos);
1558 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1559 $pos += length($1) - 1;
1560 } elsif (substr($line, $pos, 1) eq '(') {
1561 $last_openparen = $pos;
1562 } elsif (index($string, '(') == -1) {
1567 return $last_openparen + 1;
1571 my $filename = shift;
1577 my $stashrawline="";
1588 my $in_header_lines = 1;
1589 my $in_commit_log = 0; #Scanning lines before patch
1591 my $non_utf8_charset = 0;
1599 # Trace the real file/line as we go.
1605 my $comment_edge = 0;
1609 my $prev_values = 'E';
1612 my %suppress_ifbraces;
1613 my %suppress_whiletrailers;
1614 my %suppress_export;
1615 my $suppress_statement = 0;
1617 my %signatures = ();
1619 # Pre-scan the patch sanitizing the lines.
1620 # Pre-scan the patch looking for any __setup documentation.
1622 my @setup_docs = ();
1625 my $camelcase_file_seeded = 0;
1627 sanitise_line_reset();
1629 foreach my $rawline (@rawlines) {
1633 push(@fixed, $rawline) if ($fix);
1635 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1637 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1642 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1651 # Guestimate if this is a continuing comment. Run
1652 # the context looking for a comment "edge". If this
1653 # edge is a close comment then we must be in a comment
1657 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1658 next if (defined $rawlines[$ln - 1] &&
1659 $rawlines[$ln - 1] =~ /^-/);
1661 #print "RAW<$rawlines[$ln - 1]>\n";
1662 last if (!defined $rawlines[$ln - 1]);
1663 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1664 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1669 if (defined $edge && $edge eq '*/') {
1673 # Guestimate if this is a continuing comment. If this
1674 # is the start of a diff block and this line starts
1675 # ' *' then it is very likely a comment.
1676 if (!defined $edge &&
1677 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1682 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1683 sanitise_line_reset($in_comment);
1685 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1686 # Standardise the strings and chars within the input to
1687 # simplify matching -- only bother with positive lines.
1688 $line = sanitise_line($rawline);
1690 push(@lines, $line);
1693 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1698 #print "==>$rawline\n";
1699 #print "-->$line\n";
1701 if ($setup_docs && $line =~ /^\+/) {
1702 push(@setup_docs, $line);
1710 foreach my $line (@lines) {
1712 my $sline = $line; #copy of $line
1713 $sline =~ s/$;/ /g; #with comments as spaces
1715 my $rawline = $rawlines[$linenr - 1];
1717 #extract the line range in the file after the patch is applied
1718 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1720 $first_line = $linenr + 1;
1730 %suppress_ifbraces = ();
1731 %suppress_whiletrailers = ();
1732 %suppress_export = ();
1733 $suppress_statement = 0;
1736 # track the line number as we move through the hunk, note that
1737 # new versions of GNU diff omit the leading space on completely
1738 # blank context lines so we need to count that too.
1739 } elsif ($line =~ /^( |\+|$)/) {
1741 $realcnt-- if ($realcnt != 0);
1743 # Measure the line length and indent.
1744 ($length, $indent) = line_stats($rawline);
1746 # Track the previous line.
1747 ($prevline, $stashline) = ($stashline, $line);
1748 ($previndent, $stashindent) = ($stashindent, $indent);
1749 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1751 #warn "line<$line>\n";
1753 } elsif ($realcnt == 1) {
1757 my $hunk_line = ($realcnt != 0);
1759 #make up the handle for any error we report on this line
1760 $prefix = "$filename:$realline: " if ($emacs && $file);
1761 $prefix = "$filename:$linenr: " if ($emacs && !$file);
1763 $here = "#$linenr: " if (!$file);
1764 $here = "#$realline: " if ($file);
1766 # extract the filename as it passes
1767 if ($line =~ /^diff --git.*?(\S+)$/) {
1769 $realfile =~ s@^([^/]*)/@@;
1771 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1773 $realfile =~ s@^([^/]*)/@@;
1777 if (!$file && $tree && $p1_prefix ne '' &&
1778 -e "$root/$p1_prefix") {
1779 WARN("PATCH_PREFIX",
1780 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1783 if ($realfile =~ m@^include/asm/@) {
1784 ERROR("MODIFIED_INCLUDE_ASM",
1785 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1790 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1792 my $hereline = "$here\n$rawline\n";
1793 my $herecurr = "$here\n$rawline\n";
1794 my $hereprev = "$here\n$prevrawline\n$rawline\n";
1796 $cnt_lines++ if ($realcnt != 0);
1798 # Check for incorrect file permissions
1799 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1800 my $permhere = $here . "FILE: $realfile\n";
1801 if ($realfile !~ m@scripts/@ &&
1802 $realfile !~ /\.(py|pl|awk|sh)$/) {
1803 ERROR("EXECUTE_PERMISSIONS",
1804 "do not set execute permissions for source files\n" . $permhere);
1808 # Check the patch for a signoff:
1809 if ($line =~ /^\s*signed-off-by:/i) {
1814 # Check signature styles
1815 if (!$in_header_lines &&
1816 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
1817 my $space_before = $1;
1819 my $space_after = $3;
1821 my $ucfirst_sign_off = ucfirst(lc($sign_off));
1823 if ($sign_off !~ /$signature_tags/) {
1824 WARN("BAD_SIGN_OFF",
1825 "Non-standard signature: $sign_off\n" . $herecurr);
1827 if (defined $space_before && $space_before ne "") {
1828 if (WARN("BAD_SIGN_OFF",
1829 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
1831 $fixed[$linenr - 1] =
1832 "$ucfirst_sign_off $email";
1835 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
1836 if (WARN("BAD_SIGN_OFF",
1837 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
1839 $fixed[$linenr - 1] =
1840 "$ucfirst_sign_off $email";
1844 if (!defined $space_after || $space_after ne " ") {
1845 if (WARN("BAD_SIGN_OFF",
1846 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
1848 $fixed[$linenr - 1] =
1849 "$ucfirst_sign_off $email";
1853 my ($email_name, $email_address, $comment) = parse_email($email);
1854 my $suggested_email = format_email(($email_name, $email_address));
1855 if ($suggested_email eq "") {
1856 ERROR("BAD_SIGN_OFF",
1857 "Unrecognized email address: '$email'\n" . $herecurr);
1859 my $dequoted = $suggested_email;
1860 $dequoted =~ s/^"//;
1861 $dequoted =~ s/" </ </;
1862 # Don't force email to have quotes
1863 # Allow just an angle bracketed address
1864 if ("$dequoted$comment" ne $email &&
1865 "<$email_address>$comment" ne $email &&
1866 "$suggested_email$comment" ne $email) {
1867 WARN("BAD_SIGN_OFF",
1868 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
1872 # Check for duplicate signatures
1873 my $sig_nospace = $line;
1874 $sig_nospace =~ s/\s//g;
1875 $sig_nospace = lc($sig_nospace);
1876 if (defined $signatures{$sig_nospace}) {
1877 WARN("BAD_SIGN_OFF",
1878 "Duplicate signature\n" . $herecurr);
1880 $signatures{$sig_nospace} = 1;
1884 # Check for wrappage within a valid hunk of the file
1885 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1886 ERROR("CORRUPTED_PATCH",
1887 "patch seems to be corrupt (line wrapped?)\n" .
1888 $herecurr) if (!$emitted_corrupt++);
1891 # Check for absolute kernel paths.
1893 while ($line =~ m{(?:^|\s)(/\S*)}g) {
1896 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1897 check_absolute_file($1, $herecurr)) {
1900 check_absolute_file($file, $herecurr);
1905 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1906 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1907 $rawline !~ m/^$UTF8*$/) {
1908 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1910 my $blank = copy_spacing($rawline);
1911 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1912 my $hereptr = "$hereline$ptr\n";
1915 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1918 # Check if it's the start of a commit log
1919 # (not a header line and we haven't seen the patch filename)
1920 if ($in_header_lines && $realfile =~ /^$/ &&
1921 $rawline !~ /^(commit\b|from\b|[\w-]+:).+$/i) {
1922 $in_header_lines = 0;
1926 # Check if there is UTF-8 in a commit log when a mail header has explicitly
1927 # declined it, i.e defined some charset where it is missing.
1928 if ($in_header_lines &&
1929 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
1931 $non_utf8_charset = 1;
1934 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
1935 $rawline =~ /$NON_ASCII_UTF8/) {
1936 WARN("UTF8_BEFORE_PATCH",
1937 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
1940 # ignore non-hunk lines and lines being removed
1941 next if (!$hunk_line || $line =~ /^-/);
1943 #trailing whitespace
1944 if ($line =~ /^\+.*\015/) {
1945 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1946 if (ERROR("DOS_LINE_ENDINGS",
1947 "DOS line endings\n" . $herevet) &&
1949 $fixed[$linenr - 1] =~ s/[\s\015]+$//;
1951 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1952 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1953 if (ERROR("TRAILING_WHITESPACE",
1954 "trailing whitespace\n" . $herevet) &&
1956 $fixed[$linenr - 1] =~ s/\s+$//;
1962 # check for Kconfig help text having a real description
1963 # Only applies when adding the entry originally, after that we do not have
1964 # sufficient context to determine whether it is indeed long enough.
1965 if ($realfile =~ /Kconfig/ &&
1966 $line =~ /.\s*config\s+/) {
1969 my $ln = $linenr + 1;
1973 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
1974 $f = $lines[$ln - 1];
1975 $cnt-- if ($lines[$ln - 1] !~ /^-/);
1976 $is_end = $lines[$ln - 1] =~ /^\+/;
1978 next if ($f =~ /^-/);
1980 if ($lines[$ln - 1] =~ /.\s*(?:bool|tristate)\s*\"/) {
1982 } elsif ($lines[$ln - 1] =~ /.\s*(?:---)?help(?:---)?$/) {
1989 next if ($f =~ /^$/);
1990 if ($f =~ /^\s*config\s/) {
1996 WARN("CONFIG_DESCRIPTION",
1997 "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_start && $is_end && $length < 4);
1998 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2001 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2002 if ($realfile =~ /Kconfig/ &&
2003 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2004 WARN("CONFIG_EXPERIMENTAL",
2005 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2008 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2009 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2012 'EXTRA_AFLAGS' => 'asflags-y',
2013 'EXTRA_CFLAGS' => 'ccflags-y',
2014 'EXTRA_CPPFLAGS' => 'cppflags-y',
2015 'EXTRA_LDFLAGS' => 'ldflags-y',
2018 WARN("DEPRECATED_VARIABLE",
2019 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2022 # check we are in a valid source file if not then ignore this hunk
2023 next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/);
2026 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2027 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2028 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2029 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2030 $length > $max_line_length)
2033 "line over $max_line_length characters\n" . $herecurr);
2036 # Check for user-visible strings broken across lines, which breaks the ability
2037 # to grep for the string. Limited to strings used as parameters (those
2038 # following an open parenthesis), which almost completely eliminates false
2039 # positives, as well as warning only once per parameter rather than once per
2040 # line of the string. Make an exception when the previous string ends in a
2041 # newline (multiple lines in one string constant) or \n\t (common in inline
2042 # assembly to indent the instruction on the following line).
2043 if ($line =~ /^\+\s*"/ &&
2044 $prevline =~ /"\s*$/ &&
2045 $prevline =~ /\(/ &&
2046 $prevrawline !~ /\\n(?:\\t)*"\s*$/) {
2047 WARN("SPLIT_STRING",
2048 "quoted string split across lines\n" . $hereprev);
2051 # check for spaces before a quoted newline
2052 if ($rawline =~ /^.*\".*\s\\n/) {
2053 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2054 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2056 $fixed[$linenr - 1] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2061 # check for adding lines without a newline.
2062 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2063 WARN("MISSING_EOF_NEWLINE",
2064 "adding a line without newline at end of file\n" . $herecurr);
2067 # Blackfin: use hi/lo macros
2068 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2069 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2070 my $herevet = "$here\n" . cat_vet($line) . "\n";
2072 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2074 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2075 my $herevet = "$here\n" . cat_vet($line) . "\n";
2077 "use the HI() macro, not (... >> 16)\n" . $herevet);
2081 # check we are in a valid source file C or perl if not then ignore this hunk
2082 next if ($realfile !~ /\.(h|c|pl)$/);
2084 # at the beginning of a line any tabs must come first and anything
2085 # more than 8 must use tabs.
2086 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2087 $rawline =~ /^\+\s* \s*/) {
2088 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2090 if (ERROR("CODE_INDENT",
2091 "code indent should use tabs where possible\n" . $herevet) &&
2093 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2097 # check for space before tabs.
2098 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2099 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2100 if (WARN("SPACE_BEFORE_TAB",
2101 "please, no space before tabs\n" . $herevet) &&
2103 $fixed[$linenr - 1] =~
2104 s/(^\+.*) +\t/$1\t/;
2108 # check for && or || at the start of a line
2109 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2110 CHK("LOGICAL_CONTINUATIONS",
2111 "Logical continuations should be on the previous line\n" . $hereprev);
2114 # check multi-line statement indentation matches previous line
2115 if ($^V && $^V ge 5.10.0 &&
2116 $prevline =~ /^\+(\t*)(if \(|$Ident\().*(\&\&|\|\||,)\s*$/) {
2117 $prevline =~ /^\+(\t*)(.*)$/;
2121 my $pos = pos_last_openparen($rest);
2123 $line =~ /^(\+| )([ \t]*)/;
2126 my $goodtabindent = $oldindent .
2129 my $goodspaceindent = $oldindent . " " x $pos;
2131 if ($newindent ne $goodtabindent &&
2132 $newindent ne $goodspaceindent) {
2134 if (CHK("PARENTHESIS_ALIGNMENT",
2135 "Alignment should match open parenthesis\n" . $hereprev) &&
2136 $fix && $line =~ /^\+/) {
2137 $fixed[$linenr - 1] =~
2138 s/^\+[ \t]*/\+$goodtabindent/;
2144 if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) {
2146 "No space is necessary after a cast\n" . $hereprev) &&
2148 $fixed[$linenr - 1] =~
2149 s/^(\+.*\*[ \t]*\))[ \t]+/$1/;
2153 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2154 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2155 $rawline =~ /^\+[ \t]*\*/) {
2156 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2157 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2160 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2161 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2162 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2163 $rawline =~ /^\+/ && #line is new
2164 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2165 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2166 "networking block comments start with * on subsequent lines\n" . $hereprev);
2169 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2170 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2171 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2172 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2173 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2174 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2175 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2178 # check for spaces at the beginning of a line.
2180 # 1) within comments
2181 # 2) indented preprocessor commands
2183 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2184 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2185 if (WARN("LEADING_SPACE",
2186 "please, no spaces at the start of a line\n" . $herevet) &&
2188 $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2192 # check we are in a valid C source file if not then ignore this hunk
2193 next if ($realfile !~ /\.(h|c)$/);
2195 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2196 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2197 WARN("CONFIG_EXPERIMENTAL",
2198 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2201 # check for RCS/CVS revision markers
2202 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2204 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2207 # Blackfin: don't use __builtin_bfin_[cs]sync
2208 if ($line =~ /__builtin_bfin_csync/) {
2209 my $herevet = "$here\n" . cat_vet($line) . "\n";
2211 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2213 if ($line =~ /__builtin_bfin_ssync/) {
2214 my $herevet = "$here\n" . cat_vet($line) . "\n";
2216 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2219 # check for old HOTPLUG __dev<foo> section markings
2220 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2221 WARN("HOTPLUG_SECTION",
2222 "Using $1 is unnecessary\n" . $herecurr);
2225 # Check for potential 'bare' types
2226 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2228 #print "LINE<$line>\n";
2229 if ($linenr >= $suppress_statement &&
2230 $realcnt && $sline =~ /.\s*\S/) {
2231 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2232 ctx_statement_block($linenr, $realcnt, 0);
2233 $stat =~ s/\n./\n /g;
2234 $cond =~ s/\n./\n /g;
2236 #print "linenr<$linenr> <$stat>\n";
2237 # If this statement has no statement boundaries within
2238 # it there is no point in retrying a statement scan
2239 # until we hit end of it.
2240 my $frag = $stat; $frag =~ s/;+\s*$//;
2241 if ($frag !~ /(?:{|;)/) {
2242 #print "skip<$line_nr_next>\n";
2243 $suppress_statement = $line_nr_next;
2246 # Find the real next line.
2247 $realline_next = $line_nr_next;
2248 if (defined $realline_next &&
2249 (!defined $lines[$realline_next - 1] ||
2250 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2257 # Ignore goto labels.
2258 if ($s =~ /$Ident:\*$/s) {
2260 # Ignore functions being called
2261 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2263 } elsif ($s =~ /^.\s*else\b/s) {
2265 # declarations always start with types
2266 } 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) {
2269 possible($type, "A:" . $s);
2271 # definitions in global scope can only start with types
2272 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2273 possible($1, "B:" . $s);
2276 # any (foo ... *) is a pointer cast, and foo is a type
2277 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2278 possible($1, "C:" . $s);
2281 # Check for any sort of function declaration.
2282 # int foo(something bar, other baz);
2283 # void (*store_gdt)(x86_descr_ptr *);
2284 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2285 my ($name_len) = length($1);
2288 substr($ctx, 0, $name_len + 1, '');
2289 $ctx =~ s/\)[^\)]*$//;
2291 for my $arg (split(/\s*,\s*/, $ctx)) {
2292 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2294 possible($1, "D:" . $s);
2302 # Checks which may be anchored in the context.
2305 # Check for switch () and associated case and default
2306 # statements should be at the same indent.
2307 if ($line=~/\bswitch\s*\(.*\)/) {
2310 my @ctx = ctx_block_outer($linenr, $realcnt);
2312 for my $ctx (@ctx) {
2313 my ($clen, $cindent) = line_stats($ctx);
2314 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2315 $indent != $cindent) {
2316 $err .= "$sep$ctx\n";
2323 ERROR("SWITCH_CASE_INDENT_LEVEL",
2324 "switch and case should be at the same indent\n$hereline$err");
2328 # if/while/etc brace do not go on next line, unless defining a do while loop,
2329 # or if that brace on the next line is for something else
2330 if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2331 my $pre_ctx = "$1$2";
2333 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2335 if ($line =~ /^\+\t{6,}/) {
2336 WARN("DEEP_INDENTATION",
2337 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2340 my $ctx_cnt = $realcnt - $#ctx - 1;
2341 my $ctx = join("\n", @ctx);
2343 my $ctx_ln = $linenr;
2344 my $ctx_skip = $realcnt;
2346 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2347 defined $lines[$ctx_ln - 1] &&
2348 $lines[$ctx_ln - 1] =~ /^-/)) {
2349 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2350 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2354 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2355 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2357 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2359 "that open brace { should be on the previous line\n" .
2360 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2362 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2363 $ctx =~ /\)\s*\;\s*$/ &&
2364 defined $lines[$ctx_ln - 1])
2366 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2367 if ($nindent > $indent) {
2368 WARN("TRAILING_SEMICOLON",
2369 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2370 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2375 # Check relative indent for conditionals and blocks.
2376 if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2377 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2378 ctx_statement_block($linenr, $realcnt, 0)
2379 if (!defined $stat);
2380 my ($s, $c) = ($stat, $cond);
2382 substr($s, 0, length($c), '');
2384 # Make sure we remove the line prefixes as we have
2385 # none on the first line, and are going to readd them
2389 # Find out how long the conditional actually is.
2390 my @newlines = ($c =~ /\n/gs);
2391 my $cond_lines = 1 + $#newlines;
2393 # We want to check the first line inside the block
2394 # starting at the end of the conditional, so remove:
2395 # 1) any blank line termination
2396 # 2) any opening brace { on end of the line
2398 my $continuation = 0;
2400 $s =~ s/^.*\bdo\b//;
2402 if ($s =~ s/^\s*\\//) {
2405 if ($s =~ s/^\s*?\n//) {
2410 # Also ignore a loop construct at the end of a
2411 # preprocessor statement.
2412 if (($prevline =~ /^.\s*#\s*define\s/ ||
2413 $prevline =~ /\\\s*$/) && $continuation == 0) {
2419 while ($cond_ptr != $cond_lines) {
2420 $cond_ptr = $cond_lines;
2422 # If we see an #else/#elif then the code
2424 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2429 # 1) blank lines, they should be at 0,
2430 # 2) preprocessor lines, and
2432 if ($continuation ||
2434 $s =~ /^\s*#\s*?/ ||
2435 $s =~ /^\s*$Ident\s*:/) {
2436 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2437 if ($s =~ s/^.*?\n//) {
2443 my (undef, $sindent) = line_stats("+" . $s);
2444 my $stat_real = raw_line($linenr, $cond_lines);
2446 # Check if either of these lines are modified, else
2447 # this is not this patch's fault.
2448 if (!defined($stat_real) ||
2449 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2452 if (defined($stat_real) && $cond_lines > 1) {
2453 $stat_real = "[...]\n$stat_real";
2456 #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";
2458 if ($check && (($sindent % 8) != 0 ||
2459 ($sindent <= $indent && $s ne ''))) {
2460 WARN("SUSPECT_CODE_INDENT",
2461 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2465 # Track the 'values' across context and added lines.
2466 my $opline = $line; $opline =~ s/^./ /;
2467 my ($curr_values, $curr_vars) =
2468 annotate_values($opline . "\n", $prev_values);
2469 $curr_values = $prev_values . $curr_values;
2471 my $outline = $opline; $outline =~ s/\t/ /g;
2472 print "$linenr > .$outline\n";
2473 print "$linenr > $curr_values\n";
2474 print "$linenr > $curr_vars\n";
2476 $prev_values = substr($curr_values, -1);
2478 #ignore lines not being added
2479 next if ($line =~ /^[^\+]/);
2481 # TEST: allow direct testing of the type matcher.
2483 if ($line =~ /^.\s*$Declare\s*$/) {
2485 "TEST: is type\n" . $herecurr);
2486 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2487 ERROR("TEST_NOT_TYPE",
2488 "TEST: is not type ($1 is)\n". $herecurr);
2492 # TEST: allow direct testing of the attribute matcher.
2494 if ($line =~ /^.\s*$Modifier\s*$/) {
2496 "TEST: is attr\n" . $herecurr);
2497 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2498 ERROR("TEST_NOT_ATTR",
2499 "TEST: is not attr ($1 is)\n". $herecurr);
2504 # check for initialisation to aggregates open brace on the next line
2505 if ($line =~ /^.\s*{/ &&
2506 $prevline =~ /(?:^|[^=])=\s*$/) {
2508 "that open brace { should be on the previous line\n" . $hereprev);
2512 # Checks which are anchored on the added line.
2515 # check for malformed paths in #include statements (uses RAW line)
2516 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2518 if ($path =~ m{//}) {
2519 ERROR("MALFORMED_INCLUDE",
2520 "malformed #include filename\n" . $herecurr);
2522 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2523 ERROR("UAPI_INCLUDE",
2524 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2528 # no C99 // comments
2529 if ($line =~ m{//}) {
2530 if (ERROR("C99_COMMENTS",
2531 "do not use C99 // comments\n" . $herecurr) &&
2533 my $line = $fixed[$linenr - 1];
2534 if ($line =~ /\/\/(.*)$/) {
2535 my $comment = trim($1);
2536 $fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@;
2540 # Remove C99 comments.
2542 $opline =~ s@//.*@@;
2544 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
2545 # the whole statement.
2546 #print "APW <$lines[$realline_next - 1]>\n";
2547 if (defined $realline_next &&
2548 exists $lines[$realline_next - 1] &&
2549 !defined $suppress_export{$realline_next} &&
2550 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2551 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2552 # Handle definitions which produce identifiers with
2555 # EXPORT_SYMBOL(something_foo);
2557 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
2558 $name =~ /^${Ident}_$2/) {
2559 #print "FOO C name<$name>\n";
2560 $suppress_export{$realline_next} = 1;
2562 } elsif ($stat !~ /(?:
2564 ^.DEFINE_$Ident\(\Q$name\E\)|
2565 ^.DECLARE_$Ident\(\Q$name\E\)|
2566 ^.LIST_HEAD\(\Q$name\E\)|
2567 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
2568 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
2570 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
2571 $suppress_export{$realline_next} = 2;
2573 $suppress_export{$realline_next} = 1;
2576 if (!defined $suppress_export{$linenr} &&
2577 $prevline =~ /^.\s*$/ &&
2578 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
2579 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
2580 #print "FOO B <$lines[$linenr - 1]>\n";
2581 $suppress_export{$linenr} = 2;
2583 if (defined $suppress_export{$linenr} &&
2584 $suppress_export{$linenr} == 2) {
2585 WARN("EXPORT_SYMBOL",
2586 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
2589 # check for global initialisers.
2590 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
2591 if (ERROR("GLOBAL_INITIALISERS",
2592 "do not initialise globals to 0 or NULL\n" .
2595 $fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
2598 # check for static initialisers.
2599 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
2600 if (ERROR("INITIALISED_STATIC",
2601 "do not initialise statics to 0 or NULL\n" .
2604 $fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
2608 # check for static const char * arrays.
2609 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
2610 WARN("STATIC_CONST_CHAR_ARRAY",
2611 "static const char * array should probably be static const char * const\n" .
2615 # check for static char foo[] = "bar" declarations.
2616 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
2617 WARN("STATIC_CONST_CHAR_ARRAY",
2618 "static char array declaration should probably be static const char\n" .
2622 # check for declarations of struct pci_device_id
2623 if ($line =~ /\bstruct\s+pci_device_id\s+\w+\s*\[\s*\]\s*\=\s*\{/) {
2624 WARN("DEFINE_PCI_DEVICE_TABLE",
2625 "Use DEFINE_PCI_DEVICE_TABLE for struct pci_device_id\n" . $herecurr);
2628 # check for new typedefs, only function parameters and sparse annotations
2630 if ($line =~ /\btypedef\s/ &&
2631 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
2632 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
2633 $line !~ /\b$typeTypedefs\b/ &&
2634 $line !~ /\b__bitwise(?:__|)\b/) {
2635 WARN("NEW_TYPEDEFS",
2636 "do not add new typedefs\n" . $herecurr);
2639 # * goes on variable not on type
2641 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
2643 my ($ident, $from, $to) = ($1, $2, $2);
2645 # Should start with a space.
2646 $to =~ s/^(\S)/ $1/;
2647 # Should not end with a space.
2649 # '*'s should not have spaces between.
2650 while ($to =~ s/\*\s+\*/\*\*/) {
2653 ## print "1: from<$from> to<$to> ident<$ident>\n";
2655 if (ERROR("POINTER_LOCATION",
2656 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
2658 my $sub_from = $ident;
2659 my $sub_to = $ident;
2660 $sub_to =~ s/\Q$from\E/$to/;
2661 $fixed[$linenr - 1] =~
2662 s@\Q$sub_from\E@$sub_to@;
2666 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
2668 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
2670 # Should start with a space.
2671 $to =~ s/^(\S)/ $1/;
2672 # Should not end with a space.
2674 # '*'s should not have spaces between.
2675 while ($to =~ s/\*\s+\*/\*\*/) {
2677 # Modifiers should have spaces.
2678 $to =~ s/(\b$Modifier$)/$1 /;
2680 ## print "2: from<$from> to<$to> ident<$ident>\n";
2681 if ($from ne $to && $ident !~ /^$Modifier$/) {
2682 if (ERROR("POINTER_LOCATION",
2683 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
2686 my $sub_from = $match;
2687 my $sub_to = $match;
2688 $sub_to =~ s/\Q$from\E/$to/;
2689 $fixed[$linenr - 1] =~
2690 s@\Q$sub_from\E@$sub_to@;
2695 # # no BUG() or BUG_ON()
2696 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
2697 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
2698 # print "$herecurr";
2702 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
2703 WARN("LINUX_VERSION_CODE",
2704 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
2707 # check for uses of printk_ratelimit
2708 if ($line =~ /\bprintk_ratelimit\s*\(/) {
2709 WARN("PRINTK_RATELIMITED",
2710 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
2713 # printk should use KERN_* levels. Note that follow on printk's on the
2714 # same line do not need a level, so we use the current block context
2715 # to try and find and validate the current printk. In summary the current
2716 # printk includes all preceding printk's which have no newline on the end.
2717 # we assume the first bad printk is the one to report.
2718 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
2720 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
2721 #print "CHECK<$lines[$ln - 1]\n";
2722 # we have a preceding printk if it ends
2723 # with "\n" ignore it, else it is to blame
2724 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
2725 if ($rawlines[$ln - 1] !~ m{\\n"}) {
2732 WARN("PRINTK_WITHOUT_KERN_LEVEL",
2733 "printk() should include KERN_ facility level\n" . $herecurr);
2737 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
2739 my $level = lc($orig);
2740 $level = "warn" if ($level eq "warning");
2741 my $level2 = $level;
2742 $level2 = "dbg" if ($level eq "debug");
2743 WARN("PREFER_PR_LEVEL",
2744 "Prefer netdev_$level2(netdev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
2747 if ($line =~ /\bpr_warning\s*\(/) {
2748 if (WARN("PREFER_PR_LEVEL",
2749 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
2751 $fixed[$linenr - 1] =~
2752 s/\bpr_warning\b/pr_warn/;
2756 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
2758 my $level = lc($orig);
2759 $level = "warn" if ($level eq "warning");
2760 $level = "dbg" if ($level eq "debug");
2761 WARN("PREFER_DEV_LEVEL",
2762 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
2765 # function brace can't be on same line, except for #defines of do while,
2766 # or if closed on same line
2767 if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
2768 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
2770 "open brace '{' following function declarations go on the next line\n" . $herecurr);
2773 # open braces for enum, union and struct go on the same line.
2774 if ($line =~ /^.\s*{/ &&
2775 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
2777 "open brace '{' following $1 go on the same line\n" . $hereprev);
2780 # missing space after union, struct or enum definition
2781 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
2783 "missing space after $1 definition\n" . $herecurr) &&
2785 $fixed[$linenr - 1] =~
2786 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
2790 # check for spacing round square brackets; allowed:
2791 # 1. with a type on the left -- int [] a;
2792 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
2793 # 3. inside a curly brace -- = { [0...10] = 5 }
2794 while ($line =~ /(.*?\s)\[/g) {
2795 my ($where, $prefix) = ($-[1], $1);
2796 if ($prefix !~ /$Type\s+$/ &&
2797 ($where != 0 || $prefix !~ /^.\s+$/) &&
2798 $prefix !~ /[{,]\s+$/) {
2799 if (ERROR("BRACKET_SPACE",
2800 "space prohibited before open square bracket '['\n" . $herecurr) &&
2802 $fixed[$linenr - 1] =~
2803 s/^(\+.*?)\s+\[/$1\[/;
2808 # check for spaces between functions and their parentheses.
2809 while ($line =~ /($Ident)\s+\(/g) {
2811 my $ctx_before = substr($line, 0, $-[1]);
2812 my $ctx = "$ctx_before$name";
2814 # Ignore those directives where spaces _are_ permitted.
2816 if|for|while|switch|return|case|
2817 volatile|__volatile__|
2818 __attribute__|format|__extension__|
2821 # cpp #define statements have non-optional spaces, ie
2822 # if there is a space between the name and the open
2823 # parenthesis it is simply not a parameter group.
2824 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
2826 # cpp #elif statement condition may start with a (
2827 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
2829 # If this whole things ends with a type its most
2830 # likely a typedef for a function.
2831 } elsif ($ctx =~ /$Type$/) {
2835 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
2837 $fixed[$linenr - 1] =~
2838 s/\b$name\s+\(/$name\(/;
2843 # Check operator spacing.
2844 if (!($line=~/\#\s*include/)) {
2845 my $fixed_line = "";
2849 <<=|>>=|<=|>=|==|!=|
2850 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2851 =>|->|<<|>>|<|>|=|!|~|
2852 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2855 my @elements = split(/($ops|;)/, $opline);
2857 ## print("element count: <" . $#elements . ">\n");
2858 ## foreach my $el (@elements) {
2859 ## print("el: <$el>\n");
2862 my @fix_elements = ();
2865 foreach my $el (@elements) {
2866 push(@fix_elements, substr($rawline, $off, length($el)));
2867 $off += length($el);
2872 my $blank = copy_spacing($opline);
2873 my $last_after = -1;
2875 for (my $n = 0; $n < $#elements; $n += 2) {
2877 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
2879 ## print("n: <$n> good: <$good>\n");
2881 $off += length($elements[$n]);
2883 # Pick up the preceding and succeeding characters.
2884 my $ca = substr($opline, 0, $off);
2886 if (length($opline) >= ($off + length($elements[$n + 1]))) {
2887 $cc = substr($opline, $off + length($elements[$n + 1]));
2889 my $cb = "$ca$;$cc";
2892 $a = 'V' if ($elements[$n] ne '');
2893 $a = 'W' if ($elements[$n] =~ /\s$/);
2894 $a = 'C' if ($elements[$n] =~ /$;$/);
2895 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2896 $a = 'O' if ($elements[$n] eq '');
2897 $a = 'E' if ($ca =~ /^\s*$/);
2899 my $op = $elements[$n + 1];
2902 if (defined $elements[$n + 2]) {
2903 $c = 'V' if ($elements[$n + 2] ne '');
2904 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
2905 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
2906 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2907 $c = 'O' if ($elements[$n + 2] eq '');
2908 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2913 my $ctx = "${a}x${c}";
2915 my $at = "(ctx:$ctx)";
2917 my $ptr = substr($blank, 0, $off) . "^";
2918 my $hereptr = "$hereline$ptr\n";
2920 # Pull out the value of this operator.
2921 my $op_type = substr($curr_values, $off + 1, 1);
2923 # Get the full operator variant.
2924 my $opv = $op . substr($curr_vars, $off, 1);
2926 # Ignore operators passed as parameters.
2927 if ($op_type ne 'V' &&
2928 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2931 # } elsif ($op =~ /^$;+$/) {
2933 # ; should have either the end of line or a space or \ after it
2934 } elsif ($op eq ';') {
2935 if ($ctx !~ /.x[WEBC]/ &&
2936 $cc !~ /^\\/ && $cc !~ /^;/) {
2937 if (ERROR("SPACING",
2938 "space required after that '$op' $at\n" . $hereptr)) {
2939 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2945 } elsif ($op eq '//') {
2949 # : when part of a bitfield
2950 } elsif ($op eq '->' || $opv eq ':B') {
2951 if ($ctx =~ /Wx.|.xW/) {
2952 if (ERROR("SPACING",
2953 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
2954 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
2955 if (defined $fix_elements[$n + 2]) {
2956 $fix_elements[$n + 2] =~ s/^\s+//;
2962 # , must have a space on the right.
2963 } elsif ($op eq ',') {
2964 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
2965 if (ERROR("SPACING",
2966 "space required after that '$op' $at\n" . $hereptr)) {
2967 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
2973 # '*' as part of a type definition -- reported already.
2974 } elsif ($opv eq '*_') {
2975 #warn "'*' is part of type\n";
2977 # unary operators should have a space before and
2978 # none after. May be left adjacent to another
2979 # unary operator, or a cast
2980 } elsif ($op eq '!' || $op eq '~' ||
2981 $opv eq '*U' || $opv eq '-U' ||
2982 $opv eq '&U' || $opv eq '&&U') {
2983 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2984 if (ERROR("SPACING",
2985 "space required before that '$op' $at\n" . $hereptr)) {
2986 if ($n != $last_after + 2) {
2987 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
2992 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2993 # A unary '*' may be const
2995 } elsif ($ctx =~ /.xW/) {
2996 if (ERROR("SPACING",
2997 "space prohibited after that '$op' $at\n" . $hereptr)) {
2998 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
2999 if (defined $fix_elements[$n + 2]) {
3000 $fix_elements[$n + 2] =~ s/^\s+//;
3006 # unary ++ and unary -- are allowed no space on one side.
3007 } elsif ($op eq '++' or $op eq '--') {
3008 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3009 if (ERROR("SPACING",
3010 "space required one side of that '$op' $at\n" . $hereptr)) {
3011 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3015 if ($ctx =~ /Wx[BE]/ ||
3016 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3017 if (ERROR("SPACING",
3018 "space prohibited before that '$op' $at\n" . $hereptr)) {
3019 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3023 if ($ctx =~ /ExW/) {
3024 if (ERROR("SPACING",
3025 "space prohibited after that '$op' $at\n" . $hereptr)) {
3026 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3027 if (defined $fix_elements[$n + 2]) {
3028 $fix_elements[$n + 2] =~ s/^\s+//;
3034 # << and >> may either have or not have spaces both sides
3035 } elsif ($op eq '<<' or $op eq '>>' or
3036 $op eq '&' or $op eq '^' or $op eq '|' or
3037 $op eq '+' or $op eq '-' or
3038 $op eq '*' or $op eq '/' or
3041 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3042 if (ERROR("SPACING",
3043 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3044 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3045 if (defined $fix_elements[$n + 2]) {
3046 $fix_elements[$n + 2] =~ s/^\s+//;
3052 # A colon needs no spaces before when it is
3053 # terminating a case value or a label.
3054 } elsif ($opv eq ':C' || $opv eq ':L') {
3055 if ($ctx =~ /Wx./) {
3056 if (ERROR("SPACING",
3057 "space prohibited before that '$op' $at\n" . $hereptr)) {
3058 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3063 # All the others need spaces both sides.
3064 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3067 # Ignore email addresses <foo@bar>
3069 $cc =~ /^\S+\@\S+>/) ||
3071 $ca =~ /<\S+\@\S+$/))
3076 # messages are ERROR, but ?: are CHK
3078 my $msg_type = \&ERROR;
3079 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3081 if (&{$msg_type}("SPACING",
3082 "spaces required around that '$op' $at\n" . $hereptr)) {
3083 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3084 if (defined $fix_elements[$n + 2]) {
3085 $fix_elements[$n + 2] =~ s/^\s+//;
3091 $off += length($elements[$n + 1]);
3093 ## print("n: <$n> GOOD: <$good>\n");
3095 $fixed_line = $fixed_line . $good;
3098 if (($#elements % 2) == 0) {
3099 $fixed_line = $fixed_line . $fix_elements[$#elements];
3102 if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) {
3103 $fixed[$linenr - 1] = $fixed_line;
3109 # check for whitespace before a non-naked semicolon
3110 if ($line =~ /^\+.*\S\s+;/) {
3112 "space prohibited before semicolon\n" . $herecurr) &&
3114 1 while $fixed[$linenr - 1] =~
3115 s/^(\+.*\S)\s+;/$1;/;
3119 # check for multiple assignments
3120 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3121 CHK("MULTIPLE_ASSIGNMENTS",
3122 "multiple assignments should be avoided\n" . $herecurr);
3125 ## # check for multiple declarations, allowing for a function declaration
3127 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3128 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3130 ## # Remove any bracketed sections to ensure we do not
3131 ## # falsly report the parameters of functions.
3133 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3135 ## if ($ln =~ /,/) {
3136 ## WARN("MULTIPLE_DECLARATION",
3137 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3141 #need space before brace following if, while, etc
3142 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3144 if (ERROR("SPACING",
3145 "space required before the open brace '{'\n" . $herecurr) &&
3147 $fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/;
3151 ## # check for blank lines before declarations
3152 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3153 ## $prevrawline =~ /^.\s*$/) {
3155 ## "No blank lines before declarations\n" . $hereprev);
3159 # closing brace should have a space following it when it has anything
3161 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3162 if (ERROR("SPACING",
3163 "space required after that close brace '}'\n" . $herecurr) &&
3165 $fixed[$linenr - 1] =~
3166 s/}((?!(?:,|;|\)))\S)/} $1/;
3170 # check spacing on square brackets
3171 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3172 if (ERROR("SPACING",
3173 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3175 $fixed[$linenr - 1] =~
3179 if ($line =~ /\s\]/) {
3180 if (ERROR("SPACING",
3181 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3183 $fixed[$linenr - 1] =~
3188 # check spacing on parentheses
3189 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3190 $line !~ /for\s*\(\s+;/) {
3191 if (ERROR("SPACING",
3192 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3194 $fixed[$linenr - 1] =~
3198 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3199 $line !~ /for\s*\(.*;\s+\)/ &&
3200 $line !~ /:\s+\)/) {
3201 if (ERROR("SPACING",
3202 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3204 $fixed[$linenr - 1] =~
3209 #goto labels aren't indented, allow a single space however
3210 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3211 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3212 if (WARN("INDENTED_LABEL",
3213 "labels should not be indented\n" . $herecurr) &&
3215 $fixed[$linenr - 1] =~
3220 # Return is not a function.
3221 if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
3225 # Flatten any parentheses
3226 $value =~ s/\(/ \(/g;
3227 $value =~ s/\)/\) /g;
3228 while ($value =~ s/\[[^\[\]]*\]/1/ ||
3229 $value !~ /(?:$Ident|-?$Constant)\s*
3231 (?:$Ident|-?$Constant)/x &&
3232 $value =~ s/\([^\(\)]*\)/1/) {
3234 #print "value<$value>\n";
3235 if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
3236 ERROR("RETURN_PARENTHESES",
3237 "return is not a function, parentheses are not required\n" . $herecurr);
3239 } elsif ($spacing !~ /\s+/) {
3241 "space required before the open parenthesis '('\n" . $herecurr);
3244 # Return of what appears to be an errno should normally be -'ve
3245 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3247 if ($name ne 'EOF' && $name ne 'ERROR') {
3248 WARN("USE_NEGATIVE_ERRNO",
3249 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3253 # Need a space before open parenthesis after if, while etc
3254 if ($line =~ /\b(if|while|for|switch)\(/) {
3255 if (ERROR("SPACING",
3256 "space required before the open parenthesis '('\n" . $herecurr) &&
3258 $fixed[$linenr - 1] =~
3259 s/\b(if|while|for|switch)\(/$1 \(/;
3263 # Check for illegal assignment in if conditional -- and check for trailing
3264 # statements after the conditional.
3265 if ($line =~ /do\s*(?!{)/) {
3266 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3267 ctx_statement_block($linenr, $realcnt, 0)
3268 if (!defined $stat);
3269 my ($stat_next) = ctx_statement_block($line_nr_next,
3270 $remain_next, $off_next);
3271 $stat_next =~ s/\n./\n /g;
3272 ##print "stat<$stat> stat_next<$stat_next>\n";
3274 if ($stat_next =~ /^\s*while\b/) {
3275 # If the statement carries leading newlines,
3276 # then count those as offsets.
3278 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3280 statement_rawlines($whitespace) - 1;
3282 $suppress_whiletrailers{$line_nr_next +
3286 if (!defined $suppress_whiletrailers{$linenr} &&
3287 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3288 my ($s, $c) = ($stat, $cond);
3290 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3291 ERROR("ASSIGN_IN_IF",
3292 "do not use assignment in if condition\n" . $herecurr);
3295 # Find out what is on the end of the line after the
3297 substr($s, 0, length($c), '');
3299 $s =~ s/$;//g; # Remove any comments
3300 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3301 $c !~ /}\s*while\s*/)
3303 # Find out how long the conditional actually is.
3304 my @newlines = ($c =~ /\n/gs);
3305 my $cond_lines = 1 + $#newlines;
3308 $stat_real = raw_line($linenr, $cond_lines)
3309 . "\n" if ($cond_lines);
3310 if (defined($stat_real) && $cond_lines > 1) {
3311 $stat_real = "[...]\n$stat_real";
3314 ERROR("TRAILING_STATEMENTS",
3315 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3319 # Check for bitwise tests written as boolean
3331 WARN("HEXADECIMAL_BOOLEAN_TEST",
3332 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3335 # if and else should not have general statements after it
3336 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3338 $s =~ s/$;//g; # Remove any comments
3339 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3340 ERROR("TRAILING_STATEMENTS",
3341 "trailing statements should be on next line\n" . $herecurr);
3344 # if should not continue a brace
3345 if ($line =~ /}\s*if\b/) {
3346 ERROR("TRAILING_STATEMENTS",
3347 "trailing statements should be on next line\n" .
3350 # case and default should not have general statements after them
3351 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
3353 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
3357 ERROR("TRAILING_STATEMENTS",
3358 "trailing statements should be on next line\n" . $herecurr);
3361 # Check for }<nl>else {, these must be at the same
3362 # indent level to be relevant to each other.
3363 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
3364 $previndent == $indent) {
3365 ERROR("ELSE_AFTER_BRACE",
3366 "else should follow close brace '}'\n" . $hereprev);
3369 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
3370 $previndent == $indent) {
3371 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
3373 # Find out what is on the end of the line after the
3375 substr($s, 0, length($c), '');
3378 if ($s =~ /^\s*;/) {
3379 ERROR("WHILE_AFTER_BRACE",
3380 "while should follow close brace '}'\n" . $hereprev);
3384 #Specific variable tests
3385 while ($line =~ m{($Constant|$Lval)}g) {
3388 #gcc binary extension
3389 if ($var =~ /^$Binary$/) {
3390 if (WARN("GCC_BINARY_CONSTANT",
3391 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
3393 my $hexval = sprintf("0x%x", oct($var));
3394 $fixed[$linenr - 1] =~
3395 s/\b$var\b/$hexval/;
3400 if ($var !~ /^$Constant$/ &&
3401 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
3402 #Ignore Page<foo> variants
3403 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
3404 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
3405 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) {
3406 while ($var =~ m{($Ident)}g) {
3408 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
3410 seed_camelcase_includes();
3411 if (!$file && !$camelcase_file_seeded) {
3412 seed_camelcase_file($realfile);
3413 $camelcase_file_seeded = 1;
3416 if (!defined $camelcase{$word}) {
3417 $camelcase{$word} = 1;
3419 "Avoid CamelCase: <$word>\n" . $herecurr);
3425 #no spaces allowed after \ in define
3426 if ($line =~ /\#\s*define.*\\\s+$/) {
3427 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
3428 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
3430 $fixed[$linenr - 1] =~ s/\s+$//;
3434 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
3435 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
3437 my $checkfile = "include/linux/$file";
3438 if (-f "$root/$checkfile" &&
3439 $realfile ne $checkfile &&
3440 $1 !~ /$allowed_asm_includes/)
3442 if ($realfile =~ m{^arch/}) {
3443 CHK("ARCH_INCLUDE_LINUX",
3444 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3446 WARN("INCLUDE_LINUX",
3447 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
3452 # multi-statement macros should be enclosed in a do while loop, grab the
3453 # first statement and ensure its the whole macro if its not enclosed
3454 # in a known good container
3455 if ($realfile !~ m@/vmlinux.lds.h$@ &&
3456 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
3459 my ($off, $dstat, $dcond, $rest);
3461 ($dstat, $dcond, $ln, $cnt, $off) =
3462 ctx_statement_block($linenr, $realcnt, 0);
3464 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
3465 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
3467 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
3469 $dstat =~ s/\\\n.//g;
3470 $dstat =~ s/^\s*//s;
3471 $dstat =~ s/\s*$//s;
3473 # Flatten any parentheses and braces
3474 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
3475 $dstat =~ s/\{[^\{\}]*\}/1/ ||
3476 $dstat =~ s/\[[^\[\]]*\]/1/)
3480 # Flatten any obvious string concatentation.
3481 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
3482 $dstat =~ s/$Ident\s*("X*")/$1/)
3486 my $exceptions = qr{
3498 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
3500 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
3501 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
3502 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
3503 $dstat !~ /^'X'$/ && # character constants
3504 $dstat !~ /$exceptions/ &&
3505 $dstat !~ /^\.$Ident\s*=/ && # .foo =
3506 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
3507 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
3508 $dstat !~ /^for\s*$Constant$/ && # for (...)
3509 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
3510 $dstat !~ /^do\s*{/ && # do {...
3511 $dstat !~ /^\({/ && # ({...
3512 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
3515 my $herectx = $here . "\n";
3516 my $cnt = statement_rawlines($ctx);
3518 for (my $n = 0; $n < $cnt; $n++) {
3519 $herectx .= raw_line($linenr, $n) . "\n";
3522 if ($dstat =~ /;/) {
3523 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
3524 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
3526 ERROR("COMPLEX_MACRO",
3527 "Macros with complex values should be enclosed in parenthesis\n" . "$herectx");
3531 # check for line continuations outside of #defines, preprocessor #, and asm
3534 if ($prevline !~ /^..*\\$/ &&
3535 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
3536 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
3537 $line =~ /^\+.*\\$/) {
3538 WARN("LINE_CONTINUATIONS",
3539 "Avoid unnecessary line continuations\n" . $herecurr);
3543 # do {} while (0) macro tests:
3544 # single-statement macros do not need to be enclosed in do while (0) loop,
3545 # macro should not end with a semicolon
3546 if ($^V && $^V ge 5.10.0 &&
3547 $realfile !~ m@/vmlinux.lds.h$@ &&
3548 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
3551 my ($off, $dstat, $dcond, $rest);
3553 ($dstat, $dcond, $ln, $cnt, $off) =
3554 ctx_statement_block($linenr, $realcnt, 0);
3557 $dstat =~ s/\\\n.//g;
3559 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
3564 my $cnt = statement_rawlines($ctx);
3565 my $herectx = $here . "\n";
3567 for (my $n = 0; $n < $cnt; $n++) {
3568 $herectx .= raw_line($linenr, $n) . "\n";
3571 if (($stmts =~ tr/;/;/) == 1 &&
3572 $stmts !~ /^\s*(if|while|for|switch)\b/) {
3573 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
3574 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
3576 if (defined $semis && $semis ne "") {
3577 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
3578 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
3583 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
3584 # all assignments may have only one of the following with an assignment:
3587 # VMLINUX_SYMBOL(...)
3588 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
3589 WARN("MISSING_VMLINUX_SYMBOL",
3590 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
3593 # check for redundant bracing round if etc
3594 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
3595 my ($level, $endln, @chunks) =
3596 ctx_statement_full($linenr, $realcnt, 1);
3597 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
3598 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
3599 if ($#chunks > 0 && $level == 0) {
3603 my $herectx = $here . "\n";
3604 my $ln = $linenr - 1;
3605 for my $chunk (@chunks) {
3606 my ($cond, $block) = @{$chunk};
3608 # If the condition carries leading newlines, then count those as offsets.
3609 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
3610 my $offset = statement_rawlines($whitespace) - 1;
3612 $allowed[$allow] = 0;
3613 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
3615 # We have looked at and allowed this specific line.
3616 $suppress_ifbraces{$ln + $offset} = 1;
3618 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
3619 $ln += statement_rawlines($block) - 1;
3621 substr($block, 0, length($cond), '');
3623 $seen++ if ($block =~ /^\s*{/);
3625 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
3626 if (statement_lines($cond) > 1) {
3627 #print "APW: ALLOWED: cond<$cond>\n";
3628 $allowed[$allow] = 1;
3630 if ($block =~/\b(?:if|for|while)\b/) {
3631 #print "APW: ALLOWED: block<$block>\n";
3632 $allowed[$allow] = 1;
3634 if (statement_block_size($block) > 1) {
3635 #print "APW: ALLOWED: lines block<$block>\n";
3636 $allowed[$allow] = 1;
3641 my $sum_allowed = 0;
3642 foreach (@allowed) {
3645 if ($sum_allowed == 0) {
3647 "braces {} are not necessary for any arm of this statement\n" . $herectx);
3648 } elsif ($sum_allowed != $allow &&
3651 "braces {} should be used on all arms of this statement\n" . $herectx);
3656 if (!defined $suppress_ifbraces{$linenr - 1} &&
3657 $line =~ /\b(if|while|for|else)\b/) {
3660 # Check the pre-context.
3661 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
3662 #print "APW: ALLOWED: pre<$1>\n";
3666 my ($level, $endln, @chunks) =
3667 ctx_statement_full($linenr, $realcnt, $-[0]);
3669 # Check the condition.
3670 my ($cond, $block) = @{$chunks[0]};
3671 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
3672 if (defined $cond) {
3673 substr($block, 0, length($cond), '');
3675 if (statement_lines($cond) > 1) {
3676 #print "APW: ALLOWED: cond<$cond>\n";
3679 if ($block =~/\b(?:if|for|while)\b/) {
3680 #print "APW: ALLOWED: block<$block>\n";
3683 if (statement_block_size($block) > 1) {
3684 #print "APW: ALLOWED: lines block<$block>\n";
3687 # Check the post-context.
3688 if (defined $chunks[1]) {
3689 my ($cond, $block) = @{$chunks[1]};
3690 if (defined $cond) {
3691 substr($block, 0, length($cond), '');
3693 if ($block =~ /^\s*\{/) {
3694 #print "APW: ALLOWED: chunk-1 block<$block>\n";
3698 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
3699 my $herectx = $here . "\n";
3700 my $cnt = statement_rawlines($block);
3702 for (my $n = 0; $n < $cnt; $n++) {
3703 $herectx .= raw_line($linenr, $n) . "\n";
3707 "braces {} are not necessary for single statement blocks\n" . $herectx);
3711 # check for unnecessary blank lines around braces
3712 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
3714 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
3716 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
3718 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
3721 # no volatiles please
3722 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
3723 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
3725 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
3729 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
3730 CHK("REDUNDANT_CODE",
3731 "if this code is redundant consider removing it\n" .
3735 # check for needless "if (<foo>) fn(<foo>)" uses
3736 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
3737 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
3738 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
3740 "$1(NULL) is safe this check is probably not required\n" . $hereprev);
3744 # check for bad placement of section $InitAttribute (e.g.: __initdata)
3745 if ($line =~ /(\b$InitAttribute\b)/) {
3747 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
3750 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
3751 ERROR("MISPLACED_INIT",
3752 "$attr should be placed after $var\n" . $herecurr)) ||
3753 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
3754 WARN("MISPLACED_INIT",
3755 "$attr should be placed after $var\n" . $herecurr))) &&
3757 $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;
3762 # prefer usleep_range over udelay
3763 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
3764 # ignore udelay's < 10, however
3767 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
3771 # warn about unexpectedly long msleep's
3772 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
3775 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
3779 # check for comparisons of jiffies
3780 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
3781 WARN("JIFFIES_COMPARISON",
3782 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
3785 # check for comparisons of get_jiffies_64()
3786 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
3787 WARN("JIFFIES_COMPARISON",
3788 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
3791 # warn about #ifdefs in C files
3792 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
3793 # print "#ifdef in C files should be avoided\n";
3794 # print "$herecurr";
3798 # warn about spacing in #ifdefs
3799 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
3800 if (ERROR("SPACING",
3801 "exactly one space required after that #$1\n" . $herecurr) &&
3803 $fixed[$linenr - 1] =~
3804 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
3809 # check for spinlock_t definitions without a comment.
3810 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
3811 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
3813 if (!ctx_has_comment($first_line, $linenr)) {
3814 CHK("UNCOMMENTED_DEFINITION",
3815 "$1 definition without comment\n" . $herecurr);
3818 # check for memory barriers without a comment.
3819 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
3820 if (!ctx_has_comment($first_line, $linenr)) {
3821 CHK("MEMORY_BARRIER",
3822 "memory barrier without comment\n" . $herecurr);
3825 # check of hardware specific defines
3826 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
3828 "architecture specific defines should be avoided\n" . $herecurr);
3831 # Check that the storage class is at the beginning of a declaration
3832 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
3833 WARN("STORAGE_CLASS",
3834 "storage class should be at the beginning of the declaration\n" . $herecurr)
3837 # check the location of the inline attribute, that it is between
3838 # storage class and type.
3839 if ($line =~ /\b$Type\s+$Inline\b/ ||
3840 $line =~ /\b$Inline\s+$Storage\b/) {
3841 ERROR("INLINE_LOCATION",
3842 "inline keyword should sit between storage class and type\n" . $herecurr);
3845 # Check for __inline__ and __inline, prefer inline
3846 if ($line =~ /\b(__inline__|__inline)\b/) {
3848 "plain inline is preferred over $1\n" . $herecurr) &&
3850 $fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/;
3855 # Check for __attribute__ packed, prefer __packed
3856 if ($line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
3857 WARN("PREFER_PACKED",
3858 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
3861 # Check for __attribute__ aligned, prefer __aligned
3862 if ($line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
3863 WARN("PREFER_ALIGNED",
3864 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
3867 # Check for __attribute__ format(printf, prefer __printf
3868 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
3869 if (WARN("PREFER_PRINTF",
3870 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
3872 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
3877 # Check for __attribute__ format(scanf, prefer __scanf
3878 if ($line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
3879 if (WARN("PREFER_SCANF",
3880 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
3882 $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
3886 # check for sizeof(&)
3887 if ($line =~ /\bsizeof\s*\(\s*\&/) {
3888 WARN("SIZEOF_ADDRESS",
3889 "sizeof(& should be avoided\n" . $herecurr);
3892 # check for sizeof without parenthesis
3893 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
3894 if (WARN("SIZEOF_PARENTHESIS",
3895 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
3897 $fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
3901 # check for line continuations in quoted strings with odd counts of "
3902 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
3903 WARN("LINE_CONTINUATIONS",
3904 "Avoid line continuations in quoted strings\n" . $herecurr);
3907 # check for struct spinlock declarations
3908 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
3909 WARN("USE_SPINLOCK_T",
3910 "struct spinlock should be spinlock_t\n" . $herecurr);
3913 # check for seq_printf uses that could be seq_puts
3914 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
3915 my $fmt = get_quoted_string($line, $rawline);
3916 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
3917 if (WARN("PREFER_SEQ_PUTS",
3918 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
3920 $fixed[$linenr - 1] =~ s/\bseq_printf\b/seq_puts/;
3925 # Check for misused memsets
3926 if ($^V && $^V ge 5.10.0 &&
3928 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
3934 if ($ms_size =~ /^(0x|)0$/i) {
3936 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
3937 } elsif ($ms_size =~ /^(0x|)1$/i) {
3939 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
3943 # typecasts on min/max could be min_t/max_t
3944 if ($^V && $^V ge 5.10.0 &&
3946 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
3947 if (defined $2 || defined $7) {
3949 my $cast1 = deparenthesize($2);
3951 my $cast2 = deparenthesize($7);
3955 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
3956 $cast = "$cast1 or $cast2";
3957 } elsif ($cast1 ne "") {
3963 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
3967 # check usleep_range arguments
3968 if ($^V && $^V ge 5.10.0 &&
3970 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
3974 WARN("USLEEP_RANGE",
3975 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3976 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
3978 WARN("USLEEP_RANGE",
3979 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
3983 # check for new externs in .h files.
3984 if ($realfile =~ /\.h$/ &&
3985 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
3986 if (CHK("AVOID_EXTERNS",
3987 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
3989 $fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
3993 # check for new externs in .c files.
3994 if ($realfile =~ /\.c$/ && defined $stat &&
3995 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
3997 my $function_name = $1;
3998 my $paren_space = $2;
4001 if (defined $cond) {
4002 substr($s, 0, length($cond), '');
4004 if ($s =~ /^\s*;/ &&
4005 $function_name ne 'uninitialized_var')
4007 WARN("AVOID_EXTERNS",
4008 "externs should be avoided in .c files\n" . $herecurr);
4011 if ($paren_space =~ /\n/) {
4012 WARN("FUNCTION_ARGUMENTS",
4013 "arguments for function declarations should follow identifier\n" . $herecurr);
4016 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4017 $stat =~ /^.\s*extern\s+/)
4019 WARN("AVOID_EXTERNS",
4020 "externs should be avoided in .c files\n" . $herecurr);
4023 # checks for new __setup's
4024 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4027 if (!grep(/$name/, @setup_docs)) {
4028 CHK("UNDOCUMENTED_SETUP",
4029 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4033 # check for pointless casting of kmalloc return
4034 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4035 WARN("UNNECESSARY_CASTS",
4036 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4040 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4041 if ($^V && $^V ge 5.10.0 &&
4042 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4043 CHK("ALLOC_SIZEOF_STRUCT",
4044 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4047 # check for krealloc arg reuse
4048 if ($^V && $^V ge 5.10.0 &&
4049 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
4050 WARN("KREALLOC_ARG_REUSE",
4051 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
4054 # check for alloc argument mismatch
4055 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
4056 WARN("ALLOC_ARRAY_ARGS",
4057 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
4060 # check for multiple semicolons
4061 if ($line =~ /;\s*;\s*$/) {
4062 if (WARN("ONE_SEMICOLON",
4063 "Statements terminations use 1 semicolon\n" . $herecurr) &&
4065 $fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g;
4069 # check for switch/default statements without a break;
4070 if ($^V && $^V ge 5.10.0 &&
4072 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
4074 my $herectx = $here . "\n";
4075 my $cnt = statement_rawlines($stat);
4076 for (my $n = 0; $n < $cnt; $n++) {
4077 $herectx .= raw_line($linenr, $n) . "\n";
4079 WARN("DEFAULT_NO_BREAK",
4080 "switch default: should use break\n" . $herectx);
4083 # check for gcc specific __FUNCTION__
4084 if ($line =~ /\b__FUNCTION__\b/) {
4085 if (WARN("USE_FUNC",
4086 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
4088 $fixed[$linenr - 1] =~ s/\b__FUNCTION__\b/__func__/g;
4092 # check for use of yield()
4093 if ($line =~ /\byield\s*\(\s*\)/) {
4095 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
4098 # check for comparisons against true and false
4099 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
4107 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
4109 my $type = lc($otype);
4110 if ($type =~ /^(?:true|false)$/) {
4111 if (("$test" eq "==" && "$type" eq "true") ||
4112 ("$test" eq "!=" && "$type" eq "false")) {
4116 CHK("BOOL_COMPARISON",
4117 "Using comparison to $otype is error prone\n" . $herecurr);
4119 ## maybe suggesting a correct construct would better
4120 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
4125 # check for semaphores initialized locked
4126 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
4127 WARN("CONSIDER_COMPLETION",
4128 "consider using a completion\n" . $herecurr);
4131 # recommend kstrto* over simple_strto* and strict_strto*
4132 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
4133 WARN("CONSIDER_KSTRTO",
4134 "$1 is obsolete, use k$3 instead\n" . $herecurr);
4137 # check for __initcall(), use device_initcall() explicitly please
4138 if ($line =~ /^.\s*__initcall\s*\(/) {
4139 WARN("USE_DEVICE_INITCALL",
4140 "please use device_initcall() instead of __initcall()\n" . $herecurr);
4143 # check for various ops structs, ensure they are const.
4144 my $struct_ops = qr{acpi_dock_ops|
4145 address_space_operations|
4147 block_device_operations|
4152 file_lock_operations|
4162 lock_manager_operations|
4168 pipe_buf_operations|
4169 platform_hibernation_ops|
4170 platform_suspend_ops|
4175 soc_pcmcia_socket_ops|
4181 if ($line !~ /\bconst\b/ &&
4182 $line =~ /\bstruct\s+($struct_ops)\b/) {
4183 WARN("CONST_STRUCT",
4184 "struct $1 should normally be const\n" .
4188 # use of NR_CPUS is usually wrong
4189 # ignore definitions of NR_CPUS and usage to define arrays as likely right
4190 if ($line =~ /\bNR_CPUS\b/ &&
4191 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
4192 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
4193 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
4194 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
4195 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
4198 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
4201 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
4202 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
4203 ERROR("DEFINE_ARCH_HAS",
4204 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
4207 # check for %L{u,d,i} in strings
4209 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4210 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4211 $string =~ s/%%/__/g;
4212 if ($string =~ /(?<!%)%L[udi]/) {
4214 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4219 # whine mightly about in_atomic
4220 if ($line =~ /\bin_atomic\s*\(/) {
4221 if ($realfile =~ m@^drivers/@) {
4223 "do not use in_atomic in drivers\n" . $herecurr);
4224 } elsif ($realfile !~ m@^kernel/@) {
4226 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
4230 # check for lockdep_set_novalidate_class
4231 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
4232 $line =~ /__lockdep_no_validate__\s*\)/ ) {
4233 if ($realfile !~ m@^kernel/lockdep@ &&
4234 $realfile !~ m@^include/linux/lockdep@ &&
4235 $realfile !~ m@^drivers/base/core@) {
4237 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
4241 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
4242 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
4243 WARN("EXPORTED_WORLD_WRITABLE",
4244 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
4248 # If we have no input at all, then there is nothing to report on
4249 # so just keep quiet.
4250 if ($#rawlines == -1) {
4254 # In mailback mode only produce a report in the negative, for
4255 # things that appear to be patches.
4256 if ($mailback && ($clean == 1 || !$is_patch)) {
4260 # This is not a patch, and we are are in 'no-patch' mode so
4262 if (!$chk_patch && !$is_patch) {
4267 ERROR("NOT_UNIFIED_DIFF",
4268 "Does not appear to be a unified-diff format patch\n");
4270 if ($is_patch && $chk_signoff && $signoff == 0) {
4271 ERROR("MISSING_SIGN_OFF",
4272 "Missing Signed-off-by: line(s)\n");
4275 print report_dump();
4276 if ($summary && !($clean == 1 && $quiet == 1)) {
4277 print "$filename " if ($summary_file);
4278 print "total: $cnt_error errors, $cnt_warn warnings, " .
4279 (($check)? "$cnt_chk checks, " : "") .
4280 "$cnt_lines lines checked\n";
4281 print "\n" if ($quiet == 0);
4286 if ($^V lt 5.10.0) {
4287 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
4288 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
4291 # If there were whitespace errors which cleanpatch can fix
4292 # then suggest that.
4293 if ($rpt_cleaners) {
4294 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
4295 print " scripts/cleanfile\n\n";
4300 hash_show_words(\%use_type, "Used");
4301 hash_show_words(\%ignore_type, "Ignored");
4303 if ($clean == 0 && $fix && "@rawlines" ne "@fixed") {
4304 my $newfile = $filename . ".EXPERIMENTAL-checkpatch-fixes";
4308 open($f, '>', $newfile)
4309 or die "$P: Can't open $newfile for write\n";
4310 foreach my $fixed_line (@fixed) {
4313 if ($linecount > 3) {
4314 $fixed_line =~ s/^\+//;
4315 print $f $fixed_line. "\n";
4318 print $f $fixed_line . "\n";
4325 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
4327 Do _NOT_ trust the results written to this file.
4328 Do _NOT_ submit these changes without inspecting them for correctness.
4330 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
4331 No warranties, expressed or implied...
4337 if ($clean == 1 && $quiet == 0) {
4338 print "$vname has no obvious style problems and is ready for submission.\n"
4340 if ($clean == 0 && $quiet == 0) {
4342 $vname has style problems, please review.
4344 If any of these errors are false positives, please report
4345 them to the maintainer, see CHECKPATCH in MAINTAINERS.