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
14 my $D = dirname(abs_path($P));
18 use Getopt::Long qw(:config no_auto_abbrev);
44 my $configuration_file = ".checkpatch.conf";
45 my $max_line_length = 80;
46 my $ignore_perl_version = 0;
47 my $minimum_perl_version = 5.10.0;
48 my $min_conf_desc_length = 4;
49 my $spelling_file = "$D/spelling.txt";
55 Usage: $P [OPTION]... [FILE]...
60 --no-tree run without a kernel tree
61 --no-signoff do not check for 'Signed-off-by' line
62 --patch treat FILE as patchfile (default)
63 --emacs emacs compile window format
64 --terse one line per report
65 -f, --file treat FILE as regular source file
66 --subjective, --strict enable more subjective tests
67 --types TYPE(,TYPE2...) show only these comma separated message types
68 --ignore TYPE(,TYPE2...) ignore various comma separated message types
69 --max-line-length=n set the maximum line length, if exceeded, warn
70 --min-conf-desc-length=n set the min description length, if shorter, warn
71 --show-types show the message "types" in the output
72 --root=PATH PATH to the kernel tree root
73 --no-summary suppress the per-file summary
74 --mailback only produce a report in case of warnings/errors
75 --summary-file include the filename in summary
76 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
77 'values', 'possible', 'type', and 'attr' (default
79 --test-only=WORD report only warnings/errors containing WORD
81 --fix EXPERIMENTAL - may create horrible results
82 If correctable single-line errors exist, create
83 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84 with potential errors corrected to the preferred
86 --fix-inplace EXPERIMENTAL - may create horrible results
87 Is the same as --fix, but overwrites the input
88 file. It's your fault if there's no backup or git
89 --ignore-perl-version override checking of perl version. expect
91 -h, --help, --version display this help and exit
93 When FILE is - read standard input.
99 my $conf = which_conf($configuration_file);
102 open(my $conffile, '<', "$conf")
103 or warn "$P: Can't find a readable $configuration_file file $!\n";
105 while (<$conffile>) {
108 $line =~ s/\s*\n?$//g;
112 next if ($line =~ m/^\s*#/);
113 next if ($line =~ m/^\s*$/);
115 my @words = split(" ", $line);
116 foreach my $word (@words) {
117 last if ($word =~ m/^#/);
118 push (@conf_args, $word);
122 unshift(@ARGV, @conf_args) if @conf_args;
126 'q|quiet+' => \$quiet,
128 'signoff!' => \$chk_signoff,
129 'patch!' => \$chk_patch,
133 'subjective!' => \$check,
134 'strict!' => \$check,
135 'ignore=s' => \@ignore,
137 'show-types!' => \$show_types,
138 'max-line-length=i' => \$max_line_length,
139 'min-conf-desc-length=i' => \$min_conf_desc_length,
141 'summary!' => \$summary,
142 'mailback!' => \$mailback,
143 'summary-file!' => \$summary_file,
145 'fix-inplace!' => \$fix_inplace,
146 'ignore-perl-version!' => \$ignore_perl_version,
147 'debug=s' => \%debug,
148 'test-only=s' => \$tst_only,
155 $fix = 1 if ($fix_inplace);
156 $check_orig = $check;
160 if ($^V && $^V lt $minimum_perl_version) {
161 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
162 if (!$ignore_perl_version) {
168 print "$P: no input files\n";
172 sub hash_save_array_words {
173 my ($hashRef, $arrayRef) = @_;
175 my @array = split(/,/, join(',', @$arrayRef));
176 foreach my $word (@array) {
177 $word =~ s/\s*\n?$//g;
180 $word =~ tr/[a-z]/[A-Z]/;
182 next if ($word =~ m/^\s*#/);
183 next if ($word =~ m/^\s*$/);
189 sub hash_show_words {
190 my ($hashRef, $prefix) = @_;
192 if ($quiet == 0 && keys %$hashRef) {
193 print "NOTE: $prefix message types:";
194 foreach my $word (sort keys %$hashRef) {
201 hash_save_array_words(\%ignore_type, \@ignore);
202 hash_save_array_words(\%use_type, \@use);
205 my $dbg_possible = 0;
208 for my $key (keys %debug) {
210 eval "\${dbg_$key} = '$debug{$key}';";
214 my $rpt_cleaners = 0;
223 if (!top_of_kernel_tree($root)) {
224 die "$P: $root: --root does not point at a valid tree\n";
227 if (top_of_kernel_tree('.')) {
229 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
230 top_of_kernel_tree($1)) {
235 if (!defined $root) {
236 print "Must be run from the top-level dir. of a kernel tree\n";
241 my $emitted_corrupt = 0;
244 [A-Za-z_][A-Za-z\d_]*
245 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
247 our $Storage = qr{extern|static|asmlinkage};
259 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
260 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
261 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
262 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
263 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
265 # Notes to $Attribute:
266 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
286 ____cacheline_aligned|
287 ____cacheline_aligned_in_smp|
288 ____cacheline_internodealigned_in_smp|
292 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
293 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
294 our $Lval = qr{$Ident(?:$Member)*};
296 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
297 our $Binary = qr{(?i)0b[01]+$Int_type?};
298 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
299 our $Int = qr{[0-9]+$Int_type?};
300 our $Octal = qr{0[0-7]+$Int_type?};
301 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
302 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
303 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
304 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
305 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
306 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
307 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
308 our $Arithmetic = qr{\+|-|\*|\/|%};
312 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
315 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
318 our $NonptrTypeMisordered;
319 our $NonptrTypeWithAttr;
323 our $DeclareMisordered;
325 our $NON_ASCII_UTF8 = qr{
326 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
327 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
328 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
329 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
330 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
331 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
332 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
336 [\x09\x0A\x0D\x20-\x7E] # ASCII
340 our $typeTypedefs = qr{(?x:
341 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
345 our $logFunctions = qr{(?x:
346 printk(?:_ratelimited|_once|)|
347 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
348 WARN(?:_RATELIMIT|_ONCE|)|
351 seq_vprintf|seq_printf|seq_puts
354 our $signature_tags = qr{(?xi:
365 our @typeListMisordered = (
366 qr{char\s+(?:un)?signed},
367 qr{int\s+(?:(?:un)?signed\s+)?short\s},
368 qr{int\s+short(?:\s+(?:un)?signed)},
369 qr{short\s+int(?:\s+(?:un)?signed)},
370 qr{(?:un)?signed\s+int\s+short},
371 qr{short\s+(?:un)?signed},
372 qr{long\s+int\s+(?:un)?signed},
373 qr{int\s+long\s+(?:un)?signed},
374 qr{long\s+(?:un)?signed\s+int},
375 qr{int\s+(?:un)?signed\s+long},
376 qr{int\s+(?:un)?signed},
377 qr{int\s+long\s+long\s+(?:un)?signed},
378 qr{long\s+long\s+int\s+(?:un)?signed},
379 qr{long\s+long\s+(?:un)?signed\s+int},
380 qr{long\s+long\s+(?:un)?signed},
381 qr{long\s+(?:un)?signed},
386 qr{(?:(?:un)?signed\s+)?char},
387 qr{(?:(?:un)?signed\s+)?short\s+int},
388 qr{(?:(?:un)?signed\s+)?short},
389 qr{(?:(?:un)?signed\s+)?int},
390 qr{(?:(?:un)?signed\s+)?long\s+int},
391 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
392 qr{(?:(?:un)?signed\s+)?long\s+long},
393 qr{(?:(?:un)?signed\s+)?long},
402 qr{${Ident}_handler},
403 qr{${Ident}_handler_fn},
406 our @typeListWithAttr = (
408 qr{struct\s+$InitAttribute\s+$Ident},
409 qr{union\s+$InitAttribute\s+$Ident},
412 our @modifierList = (
416 our @mode_permission_funcs = (
418 ["module_param_(?:array|named|string)", 4],
419 ["module_param_array_named", 5],
420 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
421 ["proc_create(?:_data|)", 2],
422 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
425 #Create a search pattern for all these functions to speed up a loop below
426 our $mode_perms_search = "";
427 foreach my $entry (@mode_permission_funcs) {
428 $mode_perms_search .= '|' if ($mode_perms_search ne "");
429 $mode_perms_search .= $entry->[0];
432 our $allowed_asm_includes = qr{(?x:
438 # memory.h: ARM has a custom one
440 # Load common spelling mistakes and build regular expression list.
444 if (open(my $spelling, '<', $spelling_file)) {
446 while (<$spelling>) {
449 $line =~ s/\s*\n?$//g;
452 next if ($line =~ m/^\s*#/);
453 next if ($line =~ m/^\s*$/);
455 my ($suspect, $fix) = split(/\|\|/, $line);
457 push(@spelling_list, $suspect);
458 $spelling_fix{$suspect} = $fix;
461 $misspellings = join("|", @spelling_list);
463 warn "No typos will be found - file '$spelling_file': $!\n";
467 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
468 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
469 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
470 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
471 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
473 (?:$Modifier\s+|const\s+)*
475 (?:typeof|__typeof__)\s*\([^\)]*\)|
479 (?:\s+$Modifier|\s+const)*
481 $NonptrTypeMisordered = qr{
482 (?:$Modifier\s+|const\s+)*
486 (?:\s+$Modifier|\s+const)*
488 $NonptrTypeWithAttr = qr{
489 (?:$Modifier\s+|const\s+)*
491 (?:typeof|__typeof__)\s*\([^\)]*\)|
495 (?:\s+$Modifier|\s+const)*
499 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
500 (?:\s+$Inline|\s+$Modifier)*
502 $TypeMisordered = qr{
503 $NonptrTypeMisordered
504 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
505 (?:\s+$Inline|\s+$Modifier)*
507 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
508 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
512 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
514 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
515 # requires at least perl version v5.10.0
516 # Any use must be runtime checked with $^V
518 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
519 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
520 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
522 our $declaration_macros = qr{(?x:
523 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
524 (?:$Storage\s+)?LIST_HEAD\s*\(|
525 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
530 return "" if (!defined($string));
532 while ($string =~ /^\s*\(.*\)\s*$/) {
533 $string =~ s@^\s*\(\s*@@;
534 $string =~ s@\s*\)\s*$@@;
537 $string =~ s@\s+@ @g;
542 sub seed_camelcase_file {
545 return if (!(-f $file));
549 open(my $include_file, '<', "$file")
550 or warn "$P: Can't read '$file' $!\n";
551 my $text = <$include_file>;
552 close($include_file);
554 my @lines = split('\n', $text);
556 foreach my $line (@lines) {
557 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
558 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
560 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
562 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
568 my $camelcase_seeded = 0;
569 sub seed_camelcase_includes {
570 return if ($camelcase_seeded);
573 my $camelcase_cache = "";
574 my @include_files = ();
576 $camelcase_seeded = 1;
579 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
580 chomp $git_last_include_commit;
581 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
583 my $last_mod_date = 0;
584 $files = `find $root/include -name "*.h"`;
585 @include_files = split('\n', $files);
586 foreach my $file (@include_files) {
587 my $date = POSIX::strftime("%Y%m%d%H%M",
588 localtime((stat $file)[9]));
589 $last_mod_date = $date if ($last_mod_date < $date);
591 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
594 if ($camelcase_cache ne "" && -f $camelcase_cache) {
595 open(my $camelcase_file, '<', "$camelcase_cache")
596 or warn "$P: Can't read '$camelcase_cache' $!\n";
597 while (<$camelcase_file>) {
601 close($camelcase_file);
607 $files = `git ls-files "include/*.h"`;
608 @include_files = split('\n', $files);
611 foreach my $file (@include_files) {
612 seed_camelcase_file($file);
615 if ($camelcase_cache ne "") {
616 unlink glob ".checkpatch-camelcase.*";
617 open(my $camelcase_file, '>', "$camelcase_cache")
618 or warn "$P: Can't write '$camelcase_cache' $!\n";
619 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
620 print $camelcase_file ("$_\n");
622 close($camelcase_file);
626 sub git_commit_info {
627 my ($commit, $id, $desc) = @_;
629 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
631 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
632 $output =~ s/^\s*//gm;
633 my @lines = split("\n", $output);
635 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
636 # Maybe one day convert this block of bash into something that returns
637 # all matching commit ids, but it's very slow...
639 # echo "checking commits $1..."
640 # git rev-list --remotes | grep -i "^$1" |
641 # while read line ; do
642 # git log --format='%H %s' -1 $line |
643 # echo "commit $(cut -c 1-12,41-)"
645 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
647 $id = substr($lines[0], 0, 12);
648 $desc = substr($lines[0], 41);
654 $chk_signoff = 0 if ($file);
659 my @fixed_inserted = ();
660 my @fixed_deleted = ();
664 for my $filename (@ARGV) {
667 open($FILE, '-|', "diff -u /dev/null $filename") ||
668 die "$P: $filename: diff failed - $!\n";
669 } elsif ($filename eq '-') {
670 open($FILE, '<&STDIN');
672 open($FILE, '<', "$filename") ||
673 die "$P: $filename: open failed - $!\n";
675 if ($filename eq '-') {
676 $vname = 'Your patch';
685 if (!process($filename)) {
691 @fixed_inserted = ();
698 sub top_of_kernel_tree {
702 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
703 "README", "Documentation", "arch", "include", "drivers",
704 "fs", "init", "ipc", "kernel", "lib", "scripts",
707 foreach my $check (@tree_check) {
708 if (! -e $root . '/' . $check) {
716 my ($formatted_email) = @_;
722 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
725 $comment = $3 if defined $3;
726 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
728 $comment = $2 if defined $2;
729 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
731 $comment = $2 if defined $2;
732 $formatted_email =~ s/$address.*$//;
733 $name = $formatted_email;
735 $name =~ s/^\"|\"$//g;
736 # If there's a name left after stripping spaces and
737 # leading quotes, and the address doesn't have both
738 # leading and trailing angle brackets, the address
740 # "joe smith joe@smith.com" bad
741 # "joe smith <joe@smith.com" bad
742 if ($name ne "" && $address !~ /^<[^>]+>$/) {
750 $name =~ s/^\"|\"$//g;
751 $address = trim($address);
752 $address =~ s/^\<|\>$//g;
754 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
755 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
759 return ($name, $address, $comment);
763 my ($name, $address) = @_;
768 $name =~ s/^\"|\"$//g;
769 $address = trim($address);
771 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
772 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
777 $formatted_email = "$address";
779 $formatted_email = "$name <$address>";
782 return $formatted_email;
788 foreach my $path (split(/:/, $ENV{PATH})) {
789 if (-e "$path/$bin") {
800 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
801 if (-e "$path/$conf") {
802 return "$path/$conf";
814 for my $c (split(//, $str)) {
818 for (; ($n % 8) != 0; $n++) {
830 (my $res = shift) =~ tr/\t/ /c;
837 # Drop the diff line leader and expand tabs
839 $line = expand_tabs($line);
841 # Pick the indent from the front of the line.
842 my ($white) = ($line =~ /^(\s*)/);
844 return (length($line), length($white));
847 my $sanitise_quote = '';
849 sub sanitise_line_reset {
850 my ($in_comment) = @_;
853 $sanitise_quote = '*/';
855 $sanitise_quote = '';
868 # Always copy over the diff marker.
869 $res = substr($line, 0, 1);
871 for ($off = 1; $off < length($line); $off++) {
872 $c = substr($line, $off, 1);
874 # Comments we are wacking completly including the begin
875 # and end, all to $;.
876 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
877 $sanitise_quote = '*/';
879 substr($res, $off, 2, "$;$;");
883 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
884 $sanitise_quote = '';
885 substr($res, $off, 2, "$;$;");
889 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
890 $sanitise_quote = '//';
892 substr($res, $off, 2, $sanitise_quote);
897 # A \ in a string means ignore the next character.
898 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
900 substr($res, $off, 2, 'XX');
905 if ($c eq "'" || $c eq '"') {
906 if ($sanitise_quote eq '') {
907 $sanitise_quote = $c;
909 substr($res, $off, 1, $c);
911 } elsif ($sanitise_quote eq $c) {
912 $sanitise_quote = '';
916 #print "c<$c> SQ<$sanitise_quote>\n";
917 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
918 substr($res, $off, 1, $;);
919 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
920 substr($res, $off, 1, $;);
921 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
922 substr($res, $off, 1, 'X');
924 substr($res, $off, 1, $c);
928 if ($sanitise_quote eq '//') {
929 $sanitise_quote = '';
932 # The pathname on a #include may be surrounded by '<' and '>'.
933 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
934 my $clean = 'X' x length($1);
935 $res =~ s@\<.*\>@<$clean>@;
937 # The whole of a #error is a string.
938 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
939 my $clean = 'X' x length($1);
940 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
946 sub get_quoted_string {
947 my ($line, $rawline) = @_;
949 return "" if ($line !~ m/(\"[X]+\")/g);
950 return substr($rawline, $-[0], $+[0] - $-[0]);
953 sub ctx_statement_block {
954 my ($linenr, $remain, $off) = @_;
955 my $line = $linenr - 1;
972 @stack = (['', 0]) if ($#stack == -1);
974 #warn "CSB: blk<$blk> remain<$remain>\n";
975 # If we are about to drop off the end, pull in more
978 for (; $remain > 0; $line++) {
979 last if (!defined $lines[$line]);
980 next if ($lines[$line] =~ /^-/);
983 $blk .= $lines[$line] . "\n";
988 # Bail if there is no further context.
989 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
993 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
999 $c = substr($blk, $off, 1);
1000 $remainder = substr($blk, $off);
1002 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1004 # Handle nested #if/#else.
1005 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1006 push(@stack, [ $type, $level ]);
1007 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1008 ($type, $level) = @{$stack[$#stack - 1]};
1009 } elsif ($remainder =~ /^#\s*endif\b/) {
1010 ($type, $level) = @{pop(@stack)};
1013 # Statement ends at the ';' or a close '}' at the
1015 if ($level == 0 && $c eq ';') {
1019 # An else is really a conditional as long as its not else if
1020 if ($level == 0 && $coff_set == 0 &&
1021 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1022 $remainder =~ /^(else)(?:\s|{)/ &&
1023 $remainder !~ /^else\s+if\b/) {
1024 $coff = $off + length($1) - 1;
1026 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1027 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1030 if (($type eq '' || $type eq '(') && $c eq '(') {
1034 if ($type eq '(' && $c eq ')') {
1036 $type = ($level != 0)? '(' : '';
1038 if ($level == 0 && $coff < $soff) {
1041 #warn "CSB: mark coff<$coff>\n";
1044 if (($type eq '' || $type eq '{') && $c eq '{') {
1048 if ($type eq '{' && $c eq '}') {
1050 $type = ($level != 0)? '{' : '';
1053 if (substr($blk, $off + 1, 1) eq ';') {
1059 # Preprocessor commands end at the newline unless escaped.
1060 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1068 # We are truly at the end, so shuffle to the next line.
1075 my $statement = substr($blk, $soff, $off - $soff + 1);
1076 my $condition = substr($blk, $soff, $coff - $soff + 1);
1078 #warn "STATEMENT<$statement>\n";
1079 #warn "CONDITION<$condition>\n";
1081 #print "coff<$coff> soff<$off> loff<$loff>\n";
1083 return ($statement, $condition,
1084 $line, $remain + 1, $off - $loff + 1, $level);
1087 sub statement_lines {
1090 # Strip the diff line prefixes and rip blank lines at start and end.
1091 $stmt =~ s/(^|\n)./$1/g;
1095 my @stmt_lines = ($stmt =~ /\n/g);
1097 return $#stmt_lines + 2;
1100 sub statement_rawlines {
1103 my @stmt_lines = ($stmt =~ /\n/g);
1105 return $#stmt_lines + 2;
1108 sub statement_block_size {
1111 $stmt =~ s/(^|\n)./$1/g;
1117 my @stmt_lines = ($stmt =~ /\n/g);
1118 my @stmt_statements = ($stmt =~ /;/g);
1120 my $stmt_lines = $#stmt_lines + 2;
1121 my $stmt_statements = $#stmt_statements + 1;
1123 if ($stmt_lines > $stmt_statements) {
1126 return $stmt_statements;
1130 sub ctx_statement_full {
1131 my ($linenr, $remain, $off) = @_;
1132 my ($statement, $condition, $level);
1136 # Grab the first conditional/block pair.
1137 ($statement, $condition, $linenr, $remain, $off, $level) =
1138 ctx_statement_block($linenr, $remain, $off);
1139 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1140 push(@chunks, [ $condition, $statement ]);
1141 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1142 return ($level, $linenr, @chunks);
1145 # Pull in the following conditional/block pairs and see if they
1146 # could continue the statement.
1148 ($statement, $condition, $linenr, $remain, $off, $level) =
1149 ctx_statement_block($linenr, $remain, $off);
1150 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1151 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1153 push(@chunks, [ $condition, $statement ]);
1156 return ($level, $linenr, @chunks);
1160 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1162 my $start = $linenr - 1;
1169 my @stack = ($level);
1170 for ($line = $start; $remain > 0; $line++) {
1171 next if ($rawlines[$line] =~ /^-/);
1174 $blk .= $rawlines[$line];
1176 # Handle nested #if/#else.
1177 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1178 push(@stack, $level);
1179 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1180 $level = $stack[$#stack - 1];
1181 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1182 $level = pop(@stack);
1185 foreach my $c (split(//, $lines[$line])) {
1186 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1192 if ($c eq $close && $level > 0) {
1194 last if ($level == 0);
1195 } elsif ($c eq $open) {
1200 if (!$outer || $level <= 1) {
1201 push(@res, $rawlines[$line]);
1204 last if ($level == 0);
1207 return ($level, @res);
1209 sub ctx_block_outer {
1210 my ($linenr, $remain) = @_;
1212 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1216 my ($linenr, $remain) = @_;
1218 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1222 my ($linenr, $remain, $off) = @_;
1224 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1227 sub ctx_block_level {
1228 my ($linenr, $remain) = @_;
1230 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1232 sub ctx_statement_level {
1233 my ($linenr, $remain, $off) = @_;
1235 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1238 sub ctx_locate_comment {
1239 my ($first_line, $end_line) = @_;
1241 # Catch a comment on the end of the line itself.
1242 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1243 return $current_comment if (defined $current_comment);
1245 # Look through the context and try and figure out if there is a
1248 $current_comment = '';
1249 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1250 my $line = $rawlines[$linenr - 1];
1252 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1255 if ($line =~ m@/\*@) {
1258 if (!$in_comment && $current_comment ne '') {
1259 $current_comment = '';
1261 $current_comment .= $line . "\n" if ($in_comment);
1262 if ($line =~ m@\*/@) {
1267 chomp($current_comment);
1268 return($current_comment);
1270 sub ctx_has_comment {
1271 my ($first_line, $end_line) = @_;
1272 my $cmt = ctx_locate_comment($first_line, $end_line);
1274 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1275 ##print "CMMT: $cmt\n";
1277 return ($cmt ne '');
1281 my ($linenr, $cnt) = @_;
1283 my $offset = $linenr - 1;
1288 $line = $rawlines[$offset++];
1289 next if (defined($line) && $line =~ /^-/);
1301 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1304 $coded = sprintf("^%c", unpack('C', $2) + 64);
1313 my $av_preprocessor = 0;
1318 sub annotate_reset {
1319 $av_preprocessor = 0;
1321 @av_paren_type = ('E');
1322 $av_pend_colon = 'O';
1325 sub annotate_values {
1326 my ($stream, $type) = @_;
1329 my $var = '_' x length($stream);
1332 print "$stream\n" if ($dbg_values > 1);
1334 while (length($cur)) {
1335 @av_paren_type = ('E') if ($#av_paren_type < 0);
1336 print " <" . join('', @av_paren_type) .
1337 "> <$type> <$av_pending>" if ($dbg_values > 1);
1338 if ($cur =~ /^(\s+)/o) {
1339 print "WS($1)\n" if ($dbg_values > 1);
1340 if ($1 =~ /\n/ && $av_preprocessor) {
1341 $type = pop(@av_paren_type);
1342 $av_preprocessor = 0;
1345 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1346 print "CAST($1)\n" if ($dbg_values > 1);
1347 push(@av_paren_type, $type);
1350 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1351 print "DECLARE($1)\n" if ($dbg_values > 1);
1354 } elsif ($cur =~ /^($Modifier)\s*/) {
1355 print "MODIFIER($1)\n" if ($dbg_values > 1);
1358 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1359 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1360 $av_preprocessor = 1;
1361 push(@av_paren_type, $type);
1367 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1368 print "UNDEF($1)\n" if ($dbg_values > 1);
1369 $av_preprocessor = 1;
1370 push(@av_paren_type, $type);
1372 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1373 print "PRE_START($1)\n" if ($dbg_values > 1);
1374 $av_preprocessor = 1;
1376 push(@av_paren_type, $type);
1377 push(@av_paren_type, $type);
1380 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1381 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1382 $av_preprocessor = 1;
1384 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1388 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1389 print "PRE_END($1)\n" if ($dbg_values > 1);
1391 $av_preprocessor = 1;
1393 # Assume all arms of the conditional end as this
1394 # one does, and continue as if the #endif was not here.
1395 pop(@av_paren_type);
1396 push(@av_paren_type, $type);
1399 } elsif ($cur =~ /^(\\\n)/o) {
1400 print "PRECONT($1)\n" if ($dbg_values > 1);
1402 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1403 print "ATTR($1)\n" if ($dbg_values > 1);
1404 $av_pending = $type;
1407 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1408 print "SIZEOF($1)\n" if ($dbg_values > 1);
1414 } elsif ($cur =~ /^(if|while|for)\b/o) {
1415 print "COND($1)\n" if ($dbg_values > 1);
1419 } elsif ($cur =~/^(case)/o) {
1420 print "CASE($1)\n" if ($dbg_values > 1);
1421 $av_pend_colon = 'C';
1424 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1425 print "KEYWORD($1)\n" if ($dbg_values > 1);
1428 } elsif ($cur =~ /^(\()/o) {
1429 print "PAREN('$1')\n" if ($dbg_values > 1);
1430 push(@av_paren_type, $av_pending);
1434 } elsif ($cur =~ /^(\))/o) {
1435 my $new_type = pop(@av_paren_type);
1436 if ($new_type ne '_') {
1438 print "PAREN('$1') -> $type\n"
1439 if ($dbg_values > 1);
1441 print "PAREN('$1')\n" if ($dbg_values > 1);
1444 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1445 print "FUNC($1)\n" if ($dbg_values > 1);
1449 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1450 if (defined $2 && $type eq 'C' || $type eq 'T') {
1451 $av_pend_colon = 'B';
1452 } elsif ($type eq 'E') {
1453 $av_pend_colon = 'L';
1455 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1458 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1459 print "IDENT($1)\n" if ($dbg_values > 1);
1462 } elsif ($cur =~ /^($Assignment)/o) {
1463 print "ASSIGN($1)\n" if ($dbg_values > 1);
1466 } elsif ($cur =~/^(;|{|})/) {
1467 print "END($1)\n" if ($dbg_values > 1);
1469 $av_pend_colon = 'O';
1471 } elsif ($cur =~/^(,)/) {
1472 print "COMMA($1)\n" if ($dbg_values > 1);
1475 } elsif ($cur =~ /^(\?)/o) {
1476 print "QUESTION($1)\n" if ($dbg_values > 1);
1479 } elsif ($cur =~ /^(:)/o) {
1480 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1482 substr($var, length($res), 1, $av_pend_colon);
1483 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1488 $av_pend_colon = 'O';
1490 } elsif ($cur =~ /^(\[)/o) {
1491 print "CLOSE($1)\n" if ($dbg_values > 1);
1494 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1497 print "OPV($1)\n" if ($dbg_values > 1);
1504 substr($var, length($res), 1, $variant);
1507 } elsif ($cur =~ /^($Operators)/o) {
1508 print "OP($1)\n" if ($dbg_values > 1);
1509 if ($1 ne '++' && $1 ne '--') {
1513 } elsif ($cur =~ /(^.)/o) {
1514 print "C($1)\n" if ($dbg_values > 1);
1517 $cur = substr($cur, length($1));
1518 $res .= $type x length($1);
1522 return ($res, $var);
1526 my ($possible, $line) = @_;
1527 my $notPermitted = qr{(?:
1544 ^(?:typedef|struct|enum)\b
1546 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1547 if ($possible !~ $notPermitted) {
1548 # Check for modifiers.
1549 $possible =~ s/\s*$Storage\s*//g;
1550 $possible =~ s/\s*$Sparse\s*//g;
1551 if ($possible =~ /^\s*$/) {
1553 } elsif ($possible =~ /\s/) {
1554 $possible =~ s/\s*$Type\s*//g;
1555 for my $modifier (split(' ', $possible)) {
1556 if ($modifier !~ $notPermitted) {
1557 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1558 push(@modifierList, $modifier);
1563 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1564 push(@typeList, $possible);
1568 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1577 return defined $use_type{$type} if (scalar keys %use_type > 0);
1579 return !defined $ignore_type{$type};
1583 my ($level, $type, $msg) = @_;
1585 if (!show_type($type) ||
1586 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1591 $line = "$prefix$level:$type: $msg\n";
1593 $line = "$prefix$level: $msg\n";
1595 $line = (split('\n', $line))[0] . "\n" if ($terse);
1597 push(our @report, $line);
1606 sub fixup_current_range {
1607 my ($lineRef, $offset, $length) = @_;
1609 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1612 my $no = $o + $offset;
1613 my $nl = $l + $length;
1614 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1618 sub fix_inserted_deleted_lines {
1619 my ($linesRef, $insertedRef, $deletedRef) = @_;
1621 my $range_last_linenr = 0;
1622 my $delta_offset = 0;
1627 my $next_insert = 0;
1628 my $next_delete = 0;
1632 my $inserted = @{$insertedRef}[$next_insert++];
1633 my $deleted = @{$deletedRef}[$next_delete++];
1635 foreach my $old_line (@{$linesRef}) {
1637 my $line = $old_line; #don't modify the array
1638 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1640 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1641 $range_last_linenr = $new_linenr;
1642 fixup_current_range(\$line, $delta_offset, 0);
1645 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1646 $deleted = @{$deletedRef}[$next_delete++];
1648 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1651 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1652 push(@lines, ${$inserted}{'LINE'});
1653 $inserted = @{$insertedRef}[$next_insert++];
1655 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1659 push(@lines, $line);
1669 sub fix_insert_line {
1670 my ($linenr, $line) = @_;
1676 push(@fixed_inserted, $inserted);
1679 sub fix_delete_line {
1680 my ($linenr, $line) = @_;
1687 push(@fixed_deleted, $deleted);
1691 my ($type, $msg) = @_;
1693 if (report("ERROR", $type, $msg)) {
1701 my ($type, $msg) = @_;
1703 if (report("WARNING", $type, $msg)) {
1711 my ($type, $msg) = @_;
1713 if ($check && report("CHECK", $type, $msg)) {
1721 sub check_absolute_file {
1722 my ($absolute, $herecurr) = @_;
1723 my $file = $absolute;
1725 ##print "absolute<$absolute>\n";
1727 # See if any suffix of this path is a path within the tree.
1728 while ($file =~ s@^[^/]*/@@) {
1729 if (-f "$root/$file") {
1730 ##print "file<$file>\n";
1738 # It is, so see if the prefix is acceptable.
1739 my $prefix = $absolute;
1740 substr($prefix, -length($file)) = '';
1742 ##print "prefix<$prefix>\n";
1743 if ($prefix ne ".../") {
1744 WARN("USE_RELATIVE_PATH",
1745 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1752 $string =~ s/^\s+|\s+$//g;
1760 $string =~ s/^\s+//;
1768 $string =~ s/\s+$//;
1773 sub string_find_replace {
1774 my ($string, $find, $replace) = @_;
1776 $string =~ s/$find/$replace/g;
1784 my $source_indent = 8;
1785 my $max_spaces_before_tab = $source_indent - 1;
1786 my $spaces_to_tab = " " x $source_indent;
1788 #convert leading spaces to tabs
1789 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1790 #Remove spaces before a tab
1791 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1796 sub pos_last_openparen {
1801 my $opens = $line =~ tr/\(/\(/;
1802 my $closes = $line =~ tr/\)/\)/;
1804 my $last_openparen = 0;
1806 if (($opens == 0) || ($closes >= $opens)) {
1810 my $len = length($line);
1812 for ($pos = 0; $pos < $len; $pos++) {
1813 my $string = substr($line, $pos);
1814 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1815 $pos += length($1) - 1;
1816 } elsif (substr($line, $pos, 1) eq '(') {
1817 $last_openparen = $pos;
1818 } elsif (index($string, '(') == -1) {
1823 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1827 my $filename = shift;
1833 my $stashrawline="";
1844 my $in_header_lines = $file ? 0 : 1;
1845 my $in_commit_log = 0; #Scanning lines before patch
1846 my $reported_maintainer_file = 0;
1847 my $non_utf8_charset = 0;
1849 my $last_blank_line = 0;
1857 # Trace the real file/line as we go.
1863 my $comment_edge = 0;
1867 my $prev_values = 'E';
1870 my %suppress_ifbraces;
1871 my %suppress_whiletrailers;
1872 my %suppress_export;
1873 my $suppress_statement = 0;
1875 my %signatures = ();
1877 # Pre-scan the patch sanitizing the lines.
1878 # Pre-scan the patch looking for any __setup documentation.
1880 my @setup_docs = ();
1883 my $camelcase_file_seeded = 0;
1885 sanitise_line_reset();
1887 foreach my $rawline (@rawlines) {
1891 push(@fixed, $rawline) if ($fix);
1893 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1895 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1900 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1909 # Guestimate if this is a continuing comment. Run
1910 # the context looking for a comment "edge". If this
1911 # edge is a close comment then we must be in a comment
1915 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1916 next if (defined $rawlines[$ln - 1] &&
1917 $rawlines[$ln - 1] =~ /^-/);
1919 #print "RAW<$rawlines[$ln - 1]>\n";
1920 last if (!defined $rawlines[$ln - 1]);
1921 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1922 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1927 if (defined $edge && $edge eq '*/') {
1931 # Guestimate if this is a continuing comment. If this
1932 # is the start of a diff block and this line starts
1933 # ' *' then it is very likely a comment.
1934 if (!defined $edge &&
1935 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1940 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1941 sanitise_line_reset($in_comment);
1943 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1944 # Standardise the strings and chars within the input to
1945 # simplify matching -- only bother with positive lines.
1946 $line = sanitise_line($rawline);
1948 push(@lines, $line);
1951 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1956 #print "==>$rawline\n";
1957 #print "-->$line\n";
1959 if ($setup_docs && $line =~ /^\+/) {
1960 push(@setup_docs, $line);
1969 foreach my $line (@lines) {
1972 my $sline = $line; #copy of $line
1973 $sline =~ s/$;/ /g; #with comments as spaces
1975 my $rawline = $rawlines[$linenr - 1];
1977 #extract the line range in the file after the patch is applied
1978 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1980 $first_line = $linenr + 1;
1990 %suppress_ifbraces = ();
1991 %suppress_whiletrailers = ();
1992 %suppress_export = ();
1993 $suppress_statement = 0;
1996 # track the line number as we move through the hunk, note that
1997 # new versions of GNU diff omit the leading space on completely
1998 # blank context lines so we need to count that too.
1999 } elsif ($line =~ /^( |\+|$)/) {
2001 $realcnt-- if ($realcnt != 0);
2003 # Measure the line length and indent.
2004 ($length, $indent) = line_stats($rawline);
2006 # Track the previous line.
2007 ($prevline, $stashline) = ($stashline, $line);
2008 ($previndent, $stashindent) = ($stashindent, $indent);
2009 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2011 #warn "line<$line>\n";
2013 } elsif ($realcnt == 1) {
2017 my $hunk_line = ($realcnt != 0);
2019 #make up the handle for any error we report on this line
2020 $prefix = "$filename:$realline: " if ($emacs && $file);
2021 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2023 $here = "#$linenr: " if (!$file);
2024 $here = "#$realline: " if ($file);
2027 # extract the filename as it passes
2028 if ($line =~ /^diff --git.*?(\S+)$/) {
2030 $realfile =~ s@^([^/]*)/@@ if (!$file);
2033 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2035 $realfile =~ s@^([^/]*)/@@ if (!$file);
2039 if (!$file && $tree && $p1_prefix ne '' &&
2040 -e "$root/$p1_prefix") {
2041 WARN("PATCH_PREFIX",
2042 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2045 if ($realfile =~ m@^include/asm/@) {
2046 ERROR("MODIFIED_INCLUDE_ASM",
2047 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2053 if ($realfile =~ m@^(drivers/net/|net/)@) {
2056 $check = $check_orig;
2061 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2063 my $hereline = "$here\n$rawline\n";
2064 my $herecurr = "$here\n$rawline\n";
2065 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2067 $cnt_lines++ if ($realcnt != 0);
2069 # Check for incorrect file permissions
2070 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2071 my $permhere = $here . "FILE: $realfile\n";
2072 if ($realfile !~ m@scripts/@ &&
2073 $realfile !~ /\.(py|pl|awk|sh)$/) {
2074 ERROR("EXECUTE_PERMISSIONS",
2075 "do not set execute permissions for source files\n" . $permhere);
2079 # Check the patch for a signoff:
2080 if ($line =~ /^\s*signed-off-by:/i) {
2085 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2086 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2087 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2088 $reported_maintainer_file = 1;
2091 # Check signature styles
2092 if (!$in_header_lines &&
2093 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2094 my $space_before = $1;
2096 my $space_after = $3;
2098 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2100 if ($sign_off !~ /$signature_tags/) {
2101 WARN("BAD_SIGN_OFF",
2102 "Non-standard signature: $sign_off\n" . $herecurr);
2104 if (defined $space_before && $space_before ne "") {
2105 if (WARN("BAD_SIGN_OFF",
2106 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2108 $fixed[$fixlinenr] =
2109 "$ucfirst_sign_off $email";
2112 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2113 if (WARN("BAD_SIGN_OFF",
2114 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2116 $fixed[$fixlinenr] =
2117 "$ucfirst_sign_off $email";
2121 if (!defined $space_after || $space_after ne " ") {
2122 if (WARN("BAD_SIGN_OFF",
2123 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2125 $fixed[$fixlinenr] =
2126 "$ucfirst_sign_off $email";
2130 my ($email_name, $email_address, $comment) = parse_email($email);
2131 my $suggested_email = format_email(($email_name, $email_address));
2132 if ($suggested_email eq "") {
2133 ERROR("BAD_SIGN_OFF",
2134 "Unrecognized email address: '$email'\n" . $herecurr);
2136 my $dequoted = $suggested_email;
2137 $dequoted =~ s/^"//;
2138 $dequoted =~ s/" </ </;
2139 # Don't force email to have quotes
2140 # Allow just an angle bracketed address
2141 if ("$dequoted$comment" ne $email &&
2142 "<$email_address>$comment" ne $email &&
2143 "$suggested_email$comment" ne $email) {
2144 WARN("BAD_SIGN_OFF",
2145 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2149 # Check for duplicate signatures
2150 my $sig_nospace = $line;
2151 $sig_nospace =~ s/\s//g;
2152 $sig_nospace = lc($sig_nospace);
2153 if (defined $signatures{$sig_nospace}) {
2154 WARN("BAD_SIGN_OFF",
2155 "Duplicate signature\n" . $herecurr);
2157 $signatures{$sig_nospace} = 1;
2161 # Check for old stable address
2162 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2163 ERROR("STABLE_ADDRESS",
2164 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2167 # Check for unwanted Gerrit info
2168 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2169 ERROR("GERRIT_CHANGE_ID",
2170 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2173 # Check for improperly formed commit descriptions
2174 if ($in_commit_log &&
2175 $line =~ /\bcommit\s+[0-9a-f]{5,}/i &&
2176 !($line =~ /\b[Cc]ommit [0-9a-f]{12,40} \("/ ||
2177 ($line =~ /\b[Cc]ommit [0-9a-f]{12,40}\s*$/ &&
2178 defined $rawlines[$linenr] &&
2179 $rawlines[$linenr] =~ /^\s*\("/))) {
2180 $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i;
2182 my $orig_commit = lc($2);
2183 my $id = '01234567890ab';
2184 my $desc = 'commit description';
2185 ($id, $desc) = git_commit_info($orig_commit, $id, $desc);
2186 ERROR("GIT_COMMIT_ID",
2187 "Please use 12 or more chars for the git commit ID like: '${init_char}ommit $id (\"$desc\")'\n" . $herecurr);
2190 # Check for added, moved or deleted files
2191 if (!$reported_maintainer_file && !$in_commit_log &&
2192 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2193 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2194 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2195 (defined($1) || defined($2))))) {
2196 $reported_maintainer_file = 1;
2197 WARN("FILE_PATH_CHANGES",
2198 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2201 # Check for wrappage within a valid hunk of the file
2202 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2203 ERROR("CORRUPTED_PATCH",
2204 "patch seems to be corrupt (line wrapped?)\n" .
2205 $herecurr) if (!$emitted_corrupt++);
2208 # Check for absolute kernel paths.
2210 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2213 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2214 check_absolute_file($1, $herecurr)) {
2217 check_absolute_file($file, $herecurr);
2222 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2223 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2224 $rawline !~ m/^$UTF8*$/) {
2225 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2227 my $blank = copy_spacing($rawline);
2228 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2229 my $hereptr = "$hereline$ptr\n";
2232 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2235 # Check if it's the start of a commit log
2236 # (not a header line and we haven't seen the patch filename)
2237 if ($in_header_lines && $realfile =~ /^$/ &&
2238 !($rawline =~ /^\s+\S/ ||
2239 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2240 $in_header_lines = 0;
2244 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2245 # declined it, i.e defined some charset where it is missing.
2246 if ($in_header_lines &&
2247 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2249 $non_utf8_charset = 1;
2252 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2253 $rawline =~ /$NON_ASCII_UTF8/) {
2254 WARN("UTF8_BEFORE_PATCH",
2255 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2258 # Check for various typo / spelling mistakes
2259 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2260 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2262 my $typo_fix = $spelling_fix{lc($typo)};
2263 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2264 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2265 my $msg_type = \&WARN;
2266 $msg_type = \&CHK if ($file);
2267 if (&{$msg_type}("TYPO_SPELLING",
2268 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2270 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2275 # ignore non-hunk lines and lines being removed
2276 next if (!$hunk_line || $line =~ /^-/);
2278 #trailing whitespace
2279 if ($line =~ /^\+.*\015/) {
2280 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2281 if (ERROR("DOS_LINE_ENDINGS",
2282 "DOS line endings\n" . $herevet) &&
2284 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2286 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2287 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2288 if (ERROR("TRAILING_WHITESPACE",
2289 "trailing whitespace\n" . $herevet) &&
2291 $fixed[$fixlinenr] =~ s/\s+$//;
2297 # Check for FSF mailing addresses.
2298 if ($rawline =~ /\bwrite to the Free/i ||
2299 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2300 $rawline =~ /\b51\s+Franklin\s+St/i) {
2301 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2302 my $msg_type = \&ERROR;
2303 $msg_type = \&CHK if ($file);
2304 &{$msg_type}("FSF_MAILING_ADDRESS",
2305 "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
2308 # check for Kconfig help text having a real description
2309 # Only applies when adding the entry originally, after that we do not have
2310 # sufficient context to determine whether it is indeed long enough.
2311 if ($realfile =~ /Kconfig/ &&
2312 $line =~ /^\+\s*config\s+/) {
2315 my $ln = $linenr + 1;
2319 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2320 $f = $lines[$ln - 1];
2321 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2322 $is_end = $lines[$ln - 1] =~ /^\+/;
2324 next if ($f =~ /^-/);
2325 last if (!$file && $f =~ /^\@\@/);
2327 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2329 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2336 next if ($f =~ /^$/);
2337 if ($f =~ /^\s*config\s/) {
2343 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2344 WARN("CONFIG_DESCRIPTION",
2345 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2347 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2350 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2351 if ($realfile =~ /Kconfig/ &&
2352 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2353 WARN("CONFIG_EXPERIMENTAL",
2354 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2357 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2358 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2361 'EXTRA_AFLAGS' => 'asflags-y',
2362 'EXTRA_CFLAGS' => 'ccflags-y',
2363 'EXTRA_CPPFLAGS' => 'cppflags-y',
2364 'EXTRA_LDFLAGS' => 'ldflags-y',
2367 WARN("DEPRECATED_VARIABLE",
2368 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2371 # check for DT compatible documentation
2372 if (defined $root &&
2373 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2374 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2376 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2378 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2379 my $vp_file = $dt_path . "vendor-prefixes.txt";
2381 foreach my $compat (@compats) {
2382 my $compat2 = $compat;
2383 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2384 my $compat3 = $compat;
2385 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2386 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2388 WARN("UNDOCUMENTED_DT_STRING",
2389 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2392 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2394 `grep -Eq "^$vendor\\b" $vp_file`;
2396 WARN("UNDOCUMENTED_DT_STRING",
2397 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2402 # check we are in a valid source file if not then ignore this hunk
2403 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2406 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2407 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2408 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2409 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2410 $length > $max_line_length)
2413 "line over $max_line_length characters\n" . $herecurr);
2416 # Check for user-visible strings broken across lines, which breaks the ability
2417 # to grep for the string. Make exceptions when the previous string ends in a
2418 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
2419 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
2420 if ($line =~ /^\+\s*"/ &&
2421 $prevline =~ /"\s*$/ &&
2422 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
2423 WARN("SPLIT_STRING",
2424 "quoted string split across lines\n" . $hereprev);
2427 # check for missing a space in a string concatination
2428 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
2429 WARN('MISSING_SPACE',
2430 "break quoted strings at a space character\n" . $hereprev);
2433 # check for spaces before a quoted newline
2434 if ($rawline =~ /^.*\".*\s\\n/) {
2435 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
2436 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
2438 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
2443 # check for adding lines without a newline.
2444 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2445 WARN("MISSING_EOF_NEWLINE",
2446 "adding a line without newline at end of file\n" . $herecurr);
2449 # Blackfin: use hi/lo macros
2450 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2451 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2452 my $herevet = "$here\n" . cat_vet($line) . "\n";
2454 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2456 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2457 my $herevet = "$here\n" . cat_vet($line) . "\n";
2459 "use the HI() macro, not (... >> 16)\n" . $herevet);
2463 # check we are in a valid source file C or perl if not then ignore this hunk
2464 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2466 # at the beginning of a line any tabs must come first and anything
2467 # more than 8 must use tabs.
2468 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2469 $rawline =~ /^\+\s* \s*/) {
2470 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2472 if (ERROR("CODE_INDENT",
2473 "code indent should use tabs where possible\n" . $herevet) &&
2475 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2479 # check for space before tabs.
2480 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2481 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2482 if (WARN("SPACE_BEFORE_TAB",
2483 "please, no space before tabs\n" . $herevet) &&
2485 while ($fixed[$fixlinenr] =~
2486 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2487 while ($fixed[$fixlinenr] =~
2488 s/(^\+.*) +\t/$1\t/) {}
2492 # check for && or || at the start of a line
2493 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2494 CHK("LOGICAL_CONTINUATIONS",
2495 "Logical continuations should be on the previous line\n" . $hereprev);
2498 # check multi-line statement indentation matches previous line
2499 if ($^V && $^V ge 5.10.0 &&
2500 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2501 $prevline =~ /^\+(\t*)(.*)$/;
2505 my $pos = pos_last_openparen($rest);
2507 $line =~ /^(\+| )([ \t]*)/;
2510 my $goodtabindent = $oldindent .
2513 my $goodspaceindent = $oldindent . " " x $pos;
2515 if ($newindent ne $goodtabindent &&
2516 $newindent ne $goodspaceindent) {
2518 if (CHK("PARENTHESIS_ALIGNMENT",
2519 "Alignment should match open parenthesis\n" . $hereprev) &&
2520 $fix && $line =~ /^\+/) {
2521 $fixed[$fixlinenr] =~
2522 s/^\+[ \t]*/\+$goodtabindent/;
2528 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;\({\[\<\>])/ &&
2529 (!defined($1) || $1 !~ /sizeof\s*/)) {
2531 "No space is necessary after a cast\n" . $herecurr) &&
2533 $fixed[$fixlinenr] =~
2534 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2538 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2539 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2540 $rawline =~ /^\+[ \t]*\*/ &&
2542 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2543 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2546 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2547 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2548 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2549 $rawline =~ /^\+/ && #line is new
2550 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2551 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2552 "networking block comments start with * on subsequent lines\n" . $hereprev);
2555 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2556 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2557 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2558 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2559 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2560 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2561 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2564 # check for missing blank lines after struct/union declarations
2565 # with exceptions for various attributes and macros
2566 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2568 !($line =~ /^\+\s*$/ ||
2569 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2570 $line =~ /^\+\s*MODULE_/i ||
2571 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2572 $line =~ /^\+[a-z_]*init/ ||
2573 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2574 $line =~ /^\+\s*DECLARE/ ||
2575 $line =~ /^\+\s*__setup/)) {
2576 if (CHK("LINE_SPACING",
2577 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2579 fix_insert_line($fixlinenr, "\+");
2583 # check for multiple consecutive blank lines
2584 if ($prevline =~ /^[\+ ]\s*$/ &&
2585 $line =~ /^\+\s*$/ &&
2586 $last_blank_line != ($linenr - 1)) {
2587 if (CHK("LINE_SPACING",
2588 "Please don't use multiple blank lines\n" . $hereprev) &&
2590 fix_delete_line($fixlinenr, $rawline);
2593 $last_blank_line = $linenr;
2596 # check for missing blank lines after declarations
2597 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2598 # actual declarations
2599 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2600 # function pointer declarations
2601 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2602 # foo bar; where foo is some local typedef or #define
2603 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2604 # known declaration macros
2605 $prevline =~ /^\+\s+$declaration_macros/) &&
2606 # for "else if" which can look like "$Ident $Ident"
2607 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2608 # other possible extensions of declaration lines
2609 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2610 # not starting a section or a macro "\" extended line
2611 $prevline =~ /(?:\{\s*|\\)$/) &&
2612 # looks like a declaration
2613 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2614 # function pointer declarations
2615 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2616 # foo bar; where foo is some local typedef or #define
2617 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2618 # known declaration macros
2619 $sline =~ /^\+\s+$declaration_macros/ ||
2620 # start of struct or union or enum
2621 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2622 # start or end of block or continuation of declaration
2623 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2624 # bitfield continuation
2625 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2626 # other possible extensions of declaration lines
2627 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2628 # indentation of previous and current line are the same
2629 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2630 if (WARN("LINE_SPACING",
2631 "Missing a blank line after declarations\n" . $hereprev) &&
2633 fix_insert_line($fixlinenr, "\+");
2637 # check for spaces at the beginning of a line.
2639 # 1) within comments
2640 # 2) indented preprocessor commands
2642 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2643 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2644 if (WARN("LEADING_SPACE",
2645 "please, no spaces at the start of a line\n" . $herevet) &&
2647 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2651 # check we are in a valid C source file if not then ignore this hunk
2652 next if ($realfile !~ /\.(h|c)$/);
2654 # check indentation of any line with a bare else
2655 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2656 # if the previous line is a break or return and is indented 1 tab more...
2657 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2658 my $tabs = length($1) + 1;
2659 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2660 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2661 defined $lines[$linenr] &&
2662 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2663 WARN("UNNECESSARY_ELSE",
2664 "else is not generally useful after a break or return\n" . $hereprev);
2668 # check indentation of a line with a break;
2669 # if the previous line is a goto or return and is indented the same # of tabs
2670 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2672 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2673 WARN("UNNECESSARY_BREAK",
2674 "break is not useful after a goto or return\n" . $hereprev);
2678 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2679 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2680 WARN("CONFIG_EXPERIMENTAL",
2681 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2684 # check for RCS/CVS revision markers
2685 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2687 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2690 # Blackfin: don't use __builtin_bfin_[cs]sync
2691 if ($line =~ /__builtin_bfin_csync/) {
2692 my $herevet = "$here\n" . cat_vet($line) . "\n";
2694 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2696 if ($line =~ /__builtin_bfin_ssync/) {
2697 my $herevet = "$here\n" . cat_vet($line) . "\n";
2699 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2702 # check for old HOTPLUG __dev<foo> section markings
2703 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2704 WARN("HOTPLUG_SECTION",
2705 "Using $1 is unnecessary\n" . $herecurr);
2708 # Check for potential 'bare' types
2709 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2711 #print "LINE<$line>\n";
2712 if ($linenr >= $suppress_statement &&
2713 $realcnt && $sline =~ /.\s*\S/) {
2714 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2715 ctx_statement_block($linenr, $realcnt, 0);
2716 $stat =~ s/\n./\n /g;
2717 $cond =~ s/\n./\n /g;
2719 #print "linenr<$linenr> <$stat>\n";
2720 # If this statement has no statement boundaries within
2721 # it there is no point in retrying a statement scan
2722 # until we hit end of it.
2723 my $frag = $stat; $frag =~ s/;+\s*$//;
2724 if ($frag !~ /(?:{|;)/) {
2725 #print "skip<$line_nr_next>\n";
2726 $suppress_statement = $line_nr_next;
2729 # Find the real next line.
2730 $realline_next = $line_nr_next;
2731 if (defined $realline_next &&
2732 (!defined $lines[$realline_next - 1] ||
2733 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2740 # Ignore goto labels.
2741 if ($s =~ /$Ident:\*$/s) {
2743 # Ignore functions being called
2744 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2746 } elsif ($s =~ /^.\s*else\b/s) {
2748 # declarations always start with types
2749 } 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) {
2752 possible($type, "A:" . $s);
2754 # definitions in global scope can only start with types
2755 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2756 possible($1, "B:" . $s);
2759 # any (foo ... *) is a pointer cast, and foo is a type
2760 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2761 possible($1, "C:" . $s);
2764 # Check for any sort of function declaration.
2765 # int foo(something bar, other baz);
2766 # void (*store_gdt)(x86_descr_ptr *);
2767 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2768 my ($name_len) = length($1);
2771 substr($ctx, 0, $name_len + 1, '');
2772 $ctx =~ s/\)[^\)]*$//;
2774 for my $arg (split(/\s*,\s*/, $ctx)) {
2775 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2777 possible($1, "D:" . $s);
2785 # Checks which may be anchored in the context.
2788 # Check for switch () and associated case and default
2789 # statements should be at the same indent.
2790 if ($line=~/\bswitch\s*\(.*\)/) {
2793 my @ctx = ctx_block_outer($linenr, $realcnt);
2795 for my $ctx (@ctx) {
2796 my ($clen, $cindent) = line_stats($ctx);
2797 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2798 $indent != $cindent) {
2799 $err .= "$sep$ctx\n";
2806 ERROR("SWITCH_CASE_INDENT_LEVEL",
2807 "switch and case should be at the same indent\n$hereline$err");
2811 # if/while/etc brace do not go on next line, unless defining a do while loop,
2812 # or if that brace on the next line is for something else
2813 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2814 my $pre_ctx = "$1$2";
2816 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2818 if ($line =~ /^\+\t{6,}/) {
2819 WARN("DEEP_INDENTATION",
2820 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2823 my $ctx_cnt = $realcnt - $#ctx - 1;
2824 my $ctx = join("\n", @ctx);
2826 my $ctx_ln = $linenr;
2827 my $ctx_skip = $realcnt;
2829 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2830 defined $lines[$ctx_ln - 1] &&
2831 $lines[$ctx_ln - 1] =~ /^-/)) {
2832 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2833 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2837 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2838 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2840 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2842 "that open brace { should be on the previous line\n" .
2843 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2845 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2846 $ctx =~ /\)\s*\;\s*$/ &&
2847 defined $lines[$ctx_ln - 1])
2849 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2850 if ($nindent > $indent) {
2851 WARN("TRAILING_SEMICOLON",
2852 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2853 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2858 # Check relative indent for conditionals and blocks.
2859 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2860 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2861 ctx_statement_block($linenr, $realcnt, 0)
2862 if (!defined $stat);
2863 my ($s, $c) = ($stat, $cond);
2865 substr($s, 0, length($c), '');
2867 # Make sure we remove the line prefixes as we have
2868 # none on the first line, and are going to readd them
2872 # Find out how long the conditional actually is.
2873 my @newlines = ($c =~ /\n/gs);
2874 my $cond_lines = 1 + $#newlines;
2876 # We want to check the first line inside the block
2877 # starting at the end of the conditional, so remove:
2878 # 1) any blank line termination
2879 # 2) any opening brace { on end of the line
2881 my $continuation = 0;
2883 $s =~ s/^.*\bdo\b//;
2885 if ($s =~ s/^\s*\\//) {
2888 if ($s =~ s/^\s*?\n//) {
2893 # Also ignore a loop construct at the end of a
2894 # preprocessor statement.
2895 if (($prevline =~ /^.\s*#\s*define\s/ ||
2896 $prevline =~ /\\\s*$/) && $continuation == 0) {
2902 while ($cond_ptr != $cond_lines) {
2903 $cond_ptr = $cond_lines;
2905 # If we see an #else/#elif then the code
2907 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2912 # 1) blank lines, they should be at 0,
2913 # 2) preprocessor lines, and
2915 if ($continuation ||
2917 $s =~ /^\s*#\s*?/ ||
2918 $s =~ /^\s*$Ident\s*:/) {
2919 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2920 if ($s =~ s/^.*?\n//) {
2926 my (undef, $sindent) = line_stats("+" . $s);
2927 my $stat_real = raw_line($linenr, $cond_lines);
2929 # Check if either of these lines are modified, else
2930 # this is not this patch's fault.
2931 if (!defined($stat_real) ||
2932 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2935 if (defined($stat_real) && $cond_lines > 1) {
2936 $stat_real = "[...]\n$stat_real";
2939 #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";
2941 if ($check && (($sindent % 8) != 0 ||
2942 ($sindent <= $indent && $s ne ''))) {
2943 WARN("SUSPECT_CODE_INDENT",
2944 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2948 # Track the 'values' across context and added lines.
2949 my $opline = $line; $opline =~ s/^./ /;
2950 my ($curr_values, $curr_vars) =
2951 annotate_values($opline . "\n", $prev_values);
2952 $curr_values = $prev_values . $curr_values;
2954 my $outline = $opline; $outline =~ s/\t/ /g;
2955 print "$linenr > .$outline\n";
2956 print "$linenr > $curr_values\n";
2957 print "$linenr > $curr_vars\n";
2959 $prev_values = substr($curr_values, -1);
2961 #ignore lines not being added
2962 next if ($line =~ /^[^\+]/);
2964 # TEST: allow direct testing of the type matcher.
2966 if ($line =~ /^.\s*$Declare\s*$/) {
2968 "TEST: is type\n" . $herecurr);
2969 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2970 ERROR("TEST_NOT_TYPE",
2971 "TEST: is not type ($1 is)\n". $herecurr);
2975 # TEST: allow direct testing of the attribute matcher.
2977 if ($line =~ /^.\s*$Modifier\s*$/) {
2979 "TEST: is attr\n" . $herecurr);
2980 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2981 ERROR("TEST_NOT_ATTR",
2982 "TEST: is not attr ($1 is)\n". $herecurr);
2987 # check for initialisation to aggregates open brace on the next line
2988 if ($line =~ /^.\s*{/ &&
2989 $prevline =~ /(?:^|[^=])=\s*$/) {
2990 if (ERROR("OPEN_BRACE",
2991 "that open brace { should be on the previous line\n" . $hereprev) &&
2992 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
2993 fix_delete_line($fixlinenr - 1, $prevrawline);
2994 fix_delete_line($fixlinenr, $rawline);
2995 my $fixedline = $prevrawline;
2996 $fixedline =~ s/\s*=\s*$/ = {/;
2997 fix_insert_line($fixlinenr, $fixedline);
2999 $fixedline =~ s/^(.\s*){\s*/$1/;
3000 fix_insert_line($fixlinenr, $fixedline);
3005 # Checks which are anchored on the added line.
3008 # check for malformed paths in #include statements (uses RAW line)
3009 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3011 if ($path =~ m{//}) {
3012 ERROR("MALFORMED_INCLUDE",
3013 "malformed #include filename\n" . $herecurr);
3015 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3016 ERROR("UAPI_INCLUDE",
3017 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3021 # no C99 // comments
3022 if ($line =~ m{//}) {
3023 if (ERROR("C99_COMMENTS",
3024 "do not use C99 // comments\n" . $herecurr) &&
3026 my $line = $fixed[$fixlinenr];
3027 if ($line =~ /\/\/(.*)$/) {
3028 my $comment = trim($1);
3029 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3033 # Remove C99 comments.
3035 $opline =~ s@//.*@@;
3037 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3038 # the whole statement.
3039 #print "APW <$lines[$realline_next - 1]>\n";
3040 if (defined $realline_next &&
3041 exists $lines[$realline_next - 1] &&
3042 !defined $suppress_export{$realline_next} &&
3043 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3044 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3045 # Handle definitions which produce identifiers with
3048 # EXPORT_SYMBOL(something_foo);
3050 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3051 $name =~ /^${Ident}_$2/) {
3052 #print "FOO C name<$name>\n";
3053 $suppress_export{$realline_next} = 1;
3055 } elsif ($stat !~ /(?:
3057 ^.DEFINE_$Ident\(\Q$name\E\)|
3058 ^.DECLARE_$Ident\(\Q$name\E\)|
3059 ^.LIST_HEAD\(\Q$name\E\)|
3060 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3061 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3063 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3064 $suppress_export{$realline_next} = 2;
3066 $suppress_export{$realline_next} = 1;
3069 if (!defined $suppress_export{$linenr} &&
3070 $prevline =~ /^.\s*$/ &&
3071 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3072 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3073 #print "FOO B <$lines[$linenr - 1]>\n";
3074 $suppress_export{$linenr} = 2;
3076 if (defined $suppress_export{$linenr} &&
3077 $suppress_export{$linenr} == 2) {
3078 WARN("EXPORT_SYMBOL",
3079 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3082 # check for global initialisers.
3083 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3084 if (ERROR("GLOBAL_INITIALISERS",
3085 "do not initialise globals to 0 or NULL\n" .
3088 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3091 # check for static initialisers.
3092 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3093 if (ERROR("INITIALISED_STATIC",
3094 "do not initialise statics to 0 or NULL\n" .
3097 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3101 # check for misordered declarations of char/short/int/long with signed/unsigned
3102 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3104 WARN("MISORDERED_TYPE",
3105 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3108 # check for static const char * arrays.
3109 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3110 WARN("STATIC_CONST_CHAR_ARRAY",
3111 "static const char * array should probably be static const char * const\n" .
3115 # check for static char foo[] = "bar" declarations.
3116 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3117 WARN("STATIC_CONST_CHAR_ARRAY",
3118 "static char array declaration should probably be static const char\n" .
3122 # check for non-global char *foo[] = {"bar", ...} declarations.
3123 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3124 WARN("STATIC_CONST_CHAR_ARRAY",
3125 "char * array declaration might be better as static const\n" .
3129 # check for function declarations without arguments like "int foo()"
3130 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3131 if (ERROR("FUNCTION_WITHOUT_ARGS",
3132 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3134 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3138 # check for uses of DEFINE_PCI_DEVICE_TABLE
3139 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3140 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3141 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3143 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3147 # check for new typedefs, only function parameters and sparse annotations
3149 if ($line =~ /\btypedef\s/ &&
3150 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3151 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3152 $line !~ /\b$typeTypedefs\b/ &&
3153 $line !~ /\b__bitwise(?:__|)\b/) {
3154 WARN("NEW_TYPEDEFS",
3155 "do not add new typedefs\n" . $herecurr);
3158 # * goes on variable not on type
3160 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3162 my ($ident, $from, $to) = ($1, $2, $2);
3164 # Should start with a space.
3165 $to =~ s/^(\S)/ $1/;
3166 # Should not end with a space.
3168 # '*'s should not have spaces between.
3169 while ($to =~ s/\*\s+\*/\*\*/) {
3172 ## print "1: from<$from> to<$to> ident<$ident>\n";
3174 if (ERROR("POINTER_LOCATION",
3175 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3177 my $sub_from = $ident;
3178 my $sub_to = $ident;
3179 $sub_to =~ s/\Q$from\E/$to/;
3180 $fixed[$fixlinenr] =~
3181 s@\Q$sub_from\E@$sub_to@;
3185 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3187 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3189 # Should start with a space.
3190 $to =~ s/^(\S)/ $1/;
3191 # Should not end with a space.
3193 # '*'s should not have spaces between.
3194 while ($to =~ s/\*\s+\*/\*\*/) {
3196 # Modifiers should have spaces.
3197 $to =~ s/(\b$Modifier$)/$1 /;
3199 ## print "2: from<$from> to<$to> ident<$ident>\n";
3200 if ($from ne $to && $ident !~ /^$Modifier$/) {
3201 if (ERROR("POINTER_LOCATION",
3202 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3205 my $sub_from = $match;
3206 my $sub_to = $match;
3207 $sub_to =~ s/\Q$from\E/$to/;
3208 $fixed[$fixlinenr] =~
3209 s@\Q$sub_from\E@$sub_to@;
3214 # # no BUG() or BUG_ON()
3215 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3216 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3217 # print "$herecurr";
3221 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3222 WARN("LINUX_VERSION_CODE",
3223 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3226 # check for uses of printk_ratelimit
3227 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3228 WARN("PRINTK_RATELIMITED",
3229 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3232 # printk should use KERN_* levels. Note that follow on printk's on the
3233 # same line do not need a level, so we use the current block context
3234 # to try and find and validate the current printk. In summary the current
3235 # printk includes all preceding printk's which have no newline on the end.
3236 # we assume the first bad printk is the one to report.
3237 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3239 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3240 #print "CHECK<$lines[$ln - 1]\n";
3241 # we have a preceding printk if it ends
3242 # with "\n" ignore it, else it is to blame
3243 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3244 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3251 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3252 "printk() should include KERN_ facility level\n" . $herecurr);
3256 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3258 my $level = lc($orig);
3259 $level = "warn" if ($level eq "warning");
3260 my $level2 = $level;
3261 $level2 = "dbg" if ($level eq "debug");
3262 WARN("PREFER_PR_LEVEL",
3263 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3266 if ($line =~ /\bpr_warning\s*\(/) {
3267 if (WARN("PREFER_PR_LEVEL",
3268 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3270 $fixed[$fixlinenr] =~
3271 s/\bpr_warning\b/pr_warn/;
3275 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3277 my $level = lc($orig);
3278 $level = "warn" if ($level eq "warning");
3279 $level = "dbg" if ($level eq "debug");
3280 WARN("PREFER_DEV_LEVEL",
3281 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3284 # function brace can't be on same line, except for #defines of do while,
3285 # or if closed on same line
3286 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3287 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3288 if (ERROR("OPEN_BRACE",
3289 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3291 fix_delete_line($fixlinenr, $rawline);
3292 my $fixed_line = $rawline;
3293 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3296 fix_insert_line($fixlinenr, ltrim($line1));
3297 fix_insert_line($fixlinenr, "\+{");
3298 if ($line2 !~ /^\s*$/) {
3299 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3304 # open braces for enum, union and struct go on the same line.
3305 if ($line =~ /^.\s*{/ &&
3306 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3307 if (ERROR("OPEN_BRACE",
3308 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3309 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3310 fix_delete_line($fixlinenr - 1, $prevrawline);
3311 fix_delete_line($fixlinenr, $rawline);
3312 my $fixedline = rtrim($prevrawline) . " {";
3313 fix_insert_line($fixlinenr, $fixedline);
3314 $fixedline = $rawline;
3315 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3316 if ($fixedline !~ /^\+\s*$/) {
3317 fix_insert_line($fixlinenr, $fixedline);
3322 # missing space after union, struct or enum definition
3323 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3325 "missing space after $1 definition\n" . $herecurr) &&
3327 $fixed[$fixlinenr] =~
3328 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3332 # Function pointer declarations
3333 # check spacing between type, funcptr, and args
3334 # canonical declaration is "type (*funcptr)(args...)"
3335 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3337 my $pre_pointer_space = $2;
3338 my $post_pointer_space = $3;
3340 my $post_funcname_space = $5;
3341 my $pre_args_space = $6;
3343 # the $Declare variable will capture all spaces after the type
3344 # so check it for a missing trailing missing space but pointer return types
3345 # don't need a space so don't warn for those.
3346 my $post_declare_space = "";
3347 if ($declare =~ /(\s+)$/) {
3348 $post_declare_space = $1;
3349 $declare = rtrim($declare);
3351 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3353 "missing space after return type\n" . $herecurr);
3354 $post_declare_space = " ";
3357 # unnecessary space "type (*funcptr)(args...)"
3358 # This test is not currently implemented because these declarations are
3360 # int foo(int bar, ...)
3361 # and this is form shouldn't/doesn't generate a checkpatch warning.
3363 # elsif ($declare =~ /\s{2,}$/) {
3365 # "Multiple spaces after return type\n" . $herecurr);
3368 # unnecessary space "type ( *funcptr)(args...)"
3369 if (defined $pre_pointer_space &&
3370 $pre_pointer_space =~ /^\s/) {
3372 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3375 # unnecessary space "type (* funcptr)(args...)"
3376 if (defined $post_pointer_space &&
3377 $post_pointer_space =~ /^\s/) {
3379 "Unnecessary space before function pointer name\n" . $herecurr);
3382 # unnecessary space "type (*funcptr )(args...)"
3383 if (defined $post_funcname_space &&
3384 $post_funcname_space =~ /^\s/) {
3386 "Unnecessary space after function pointer name\n" . $herecurr);
3389 # unnecessary space "type (*funcptr) (args...)"
3390 if (defined $pre_args_space &&
3391 $pre_args_space =~ /^\s/) {
3393 "Unnecessary space before function pointer arguments\n" . $herecurr);
3396 if (show_type("SPACING") && $fix) {
3397 $fixed[$fixlinenr] =~
3398 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3402 # check for spacing round square brackets; allowed:
3403 # 1. with a type on the left -- int [] a;
3404 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3405 # 3. inside a curly brace -- = { [0...10] = 5 }
3406 while ($line =~ /(.*?\s)\[/g) {
3407 my ($where, $prefix) = ($-[1], $1);
3408 if ($prefix !~ /$Type\s+$/ &&
3409 ($where != 0 || $prefix !~ /^.\s+$/) &&
3410 $prefix !~ /[{,]\s+$/) {
3411 if (ERROR("BRACKET_SPACE",
3412 "space prohibited before open square bracket '['\n" . $herecurr) &&
3414 $fixed[$fixlinenr] =~
3415 s/^(\+.*?)\s+\[/$1\[/;
3420 # check for spaces between functions and their parentheses.
3421 while ($line =~ /($Ident)\s+\(/g) {
3423 my $ctx_before = substr($line, 0, $-[1]);
3424 my $ctx = "$ctx_before$name";
3426 # Ignore those directives where spaces _are_ permitted.
3428 if|for|while|switch|return|case|
3429 volatile|__volatile__|
3430 __attribute__|format|__extension__|
3433 # cpp #define statements have non-optional spaces, ie
3434 # if there is a space between the name and the open
3435 # parenthesis it is simply not a parameter group.
3436 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3438 # cpp #elif statement condition may start with a (
3439 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3441 # If this whole things ends with a type its most
3442 # likely a typedef for a function.
3443 } elsif ($ctx =~ /$Type$/) {
3447 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3449 $fixed[$fixlinenr] =~
3450 s/\b$name\s+\(/$name\(/;
3455 # Check operator spacing.
3456 if (!($line=~/\#\s*include/)) {
3457 my $fixed_line = "";
3461 <<=|>>=|<=|>=|==|!=|
3462 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3463 =>|->|<<|>>|<|>|=|!|~|
3464 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3467 my @elements = split(/($ops|;)/, $opline);
3469 ## print("element count: <" . $#elements . ">\n");
3470 ## foreach my $el (@elements) {
3471 ## print("el: <$el>\n");
3474 my @fix_elements = ();
3477 foreach my $el (@elements) {
3478 push(@fix_elements, substr($rawline, $off, length($el)));
3479 $off += length($el);
3484 my $blank = copy_spacing($opline);
3485 my $last_after = -1;
3487 for (my $n = 0; $n < $#elements; $n += 2) {
3489 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3491 ## print("n: <$n> good: <$good>\n");
3493 $off += length($elements[$n]);
3495 # Pick up the preceding and succeeding characters.
3496 my $ca = substr($opline, 0, $off);
3498 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3499 $cc = substr($opline, $off + length($elements[$n + 1]));
3501 my $cb = "$ca$;$cc";
3504 $a = 'V' if ($elements[$n] ne '');
3505 $a = 'W' if ($elements[$n] =~ /\s$/);
3506 $a = 'C' if ($elements[$n] =~ /$;$/);
3507 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3508 $a = 'O' if ($elements[$n] eq '');
3509 $a = 'E' if ($ca =~ /^\s*$/);
3511 my $op = $elements[$n + 1];
3514 if (defined $elements[$n + 2]) {
3515 $c = 'V' if ($elements[$n + 2] ne '');
3516 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3517 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3518 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3519 $c = 'O' if ($elements[$n + 2] eq '');
3520 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3525 my $ctx = "${a}x${c}";
3527 my $at = "(ctx:$ctx)";
3529 my $ptr = substr($blank, 0, $off) . "^";
3530 my $hereptr = "$hereline$ptr\n";
3532 # Pull out the value of this operator.
3533 my $op_type = substr($curr_values, $off + 1, 1);
3535 # Get the full operator variant.
3536 my $opv = $op . substr($curr_vars, $off, 1);
3538 # Ignore operators passed as parameters.
3539 if ($op_type ne 'V' &&
3540 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3543 # } elsif ($op =~ /^$;+$/) {
3545 # ; should have either the end of line or a space or \ after it
3546 } elsif ($op eq ';') {
3547 if ($ctx !~ /.x[WEBC]/ &&
3548 $cc !~ /^\\/ && $cc !~ /^;/) {
3549 if (ERROR("SPACING",
3550 "space required after that '$op' $at\n" . $hereptr)) {
3551 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3557 } elsif ($op eq '//') {
3559 # : when part of a bitfield
3560 } elsif ($opv eq ':B') {
3561 # skip the bitfield test for now
3565 } elsif ($op eq '->') {
3566 if ($ctx =~ /Wx.|.xW/) {
3567 if (ERROR("SPACING",
3568 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3569 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3570 if (defined $fix_elements[$n + 2]) {
3571 $fix_elements[$n + 2] =~ s/^\s+//;
3577 # , must not have a space before and must have a space on the right.
3578 } elsif ($op eq ',') {
3579 my $rtrim_before = 0;
3580 my $space_after = 0;
3581 if ($ctx =~ /Wx./) {
3582 if (ERROR("SPACING",
3583 "space prohibited before that '$op' $at\n" . $hereptr)) {
3588 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3589 if (ERROR("SPACING",
3590 "space required after that '$op' $at\n" . $hereptr)) {
3596 if ($rtrim_before || $space_after) {
3597 if ($rtrim_before) {
3598 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3600 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3607 # '*' as part of a type definition -- reported already.
3608 } elsif ($opv eq '*_') {
3609 #warn "'*' is part of type\n";
3611 # unary operators should have a space before and
3612 # none after. May be left adjacent to another
3613 # unary operator, or a cast
3614 } elsif ($op eq '!' || $op eq '~' ||
3615 $opv eq '*U' || $opv eq '-U' ||
3616 $opv eq '&U' || $opv eq '&&U') {
3617 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3618 if (ERROR("SPACING",
3619 "space required before that '$op' $at\n" . $hereptr)) {
3620 if ($n != $last_after + 2) {
3621 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3626 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3627 # A unary '*' may be const
3629 } elsif ($ctx =~ /.xW/) {
3630 if (ERROR("SPACING",
3631 "space prohibited after that '$op' $at\n" . $hereptr)) {
3632 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3633 if (defined $fix_elements[$n + 2]) {
3634 $fix_elements[$n + 2] =~ s/^\s+//;
3640 # unary ++ and unary -- are allowed no space on one side.
3641 } elsif ($op eq '++' or $op eq '--') {
3642 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3643 if (ERROR("SPACING",
3644 "space required one side of that '$op' $at\n" . $hereptr)) {
3645 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3649 if ($ctx =~ /Wx[BE]/ ||
3650 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3651 if (ERROR("SPACING",
3652 "space prohibited before that '$op' $at\n" . $hereptr)) {
3653 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3657 if ($ctx =~ /ExW/) {
3658 if (ERROR("SPACING",
3659 "space prohibited after that '$op' $at\n" . $hereptr)) {
3660 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3661 if (defined $fix_elements[$n + 2]) {
3662 $fix_elements[$n + 2] =~ s/^\s+//;
3668 # << and >> may either have or not have spaces both sides
3669 } elsif ($op eq '<<' or $op eq '>>' or
3670 $op eq '&' or $op eq '^' or $op eq '|' or
3671 $op eq '+' or $op eq '-' or
3672 $op eq '*' or $op eq '/' or
3675 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3676 if (ERROR("SPACING",
3677 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3678 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3679 if (defined $fix_elements[$n + 2]) {
3680 $fix_elements[$n + 2] =~ s/^\s+//;
3686 # A colon needs no spaces before when it is
3687 # terminating a case value or a label.
3688 } elsif ($opv eq ':C' || $opv eq ':L') {
3689 if ($ctx =~ /Wx./) {
3690 if (ERROR("SPACING",
3691 "space prohibited before that '$op' $at\n" . $hereptr)) {
3692 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3697 # All the others need spaces both sides.
3698 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3701 # Ignore email addresses <foo@bar>
3703 $cc =~ /^\S+\@\S+>/) ||
3705 $ca =~ /<\S+\@\S+$/))
3710 # messages are ERROR, but ?: are CHK
3712 my $msg_type = \&ERROR;
3713 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3715 if (&{$msg_type}("SPACING",
3716 "spaces required around that '$op' $at\n" . $hereptr)) {
3717 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3718 if (defined $fix_elements[$n + 2]) {
3719 $fix_elements[$n + 2] =~ s/^\s+//;
3725 $off += length($elements[$n + 1]);
3727 ## print("n: <$n> GOOD: <$good>\n");
3729 $fixed_line = $fixed_line . $good;
3732 if (($#elements % 2) == 0) {
3733 $fixed_line = $fixed_line . $fix_elements[$#elements];
3736 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3737 $fixed[$fixlinenr] = $fixed_line;
3743 # check for whitespace before a non-naked semicolon
3744 if ($line =~ /^\+.*\S\s+;\s*$/) {
3746 "space prohibited before semicolon\n" . $herecurr) &&
3748 1 while $fixed[$fixlinenr] =~
3749 s/^(\+.*\S)\s+;/$1;/;
3753 # check for multiple assignments
3754 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3755 CHK("MULTIPLE_ASSIGNMENTS",
3756 "multiple assignments should be avoided\n" . $herecurr);
3759 ## # check for multiple declarations, allowing for a function declaration
3761 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3762 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3764 ## # Remove any bracketed sections to ensure we do not
3765 ## # falsly report the parameters of functions.
3767 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3769 ## if ($ln =~ /,/) {
3770 ## WARN("MULTIPLE_DECLARATION",
3771 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3775 #need space before brace following if, while, etc
3776 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3778 if (ERROR("SPACING",
3779 "space required before the open brace '{'\n" . $herecurr) &&
3781 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3785 ## # check for blank lines before declarations
3786 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3787 ## $prevrawline =~ /^.\s*$/) {
3789 ## "No blank lines before declarations\n" . $hereprev);
3793 # closing brace should have a space following it when it has anything
3795 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3796 if (ERROR("SPACING",
3797 "space required after that close brace '}'\n" . $herecurr) &&
3799 $fixed[$fixlinenr] =~
3800 s/}((?!(?:,|;|\)))\S)/} $1/;
3804 # check spacing on square brackets
3805 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3806 if (ERROR("SPACING",
3807 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3809 $fixed[$fixlinenr] =~
3813 if ($line =~ /\s\]/) {
3814 if (ERROR("SPACING",
3815 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3817 $fixed[$fixlinenr] =~
3822 # check spacing on parentheses
3823 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3824 $line !~ /for\s*\(\s+;/) {
3825 if (ERROR("SPACING",
3826 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3828 $fixed[$fixlinenr] =~
3832 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3833 $line !~ /for\s*\(.*;\s+\)/ &&
3834 $line !~ /:\s+\)/) {
3835 if (ERROR("SPACING",
3836 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3838 $fixed[$fixlinenr] =~
3843 # check unnecessary parentheses around addressof/dereference single $Lvals
3844 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3846 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3848 if (CHK("UNNECESSARY_PARENTHESES",
3849 "Unnecessary parentheses around $var\n" . $herecurr) &&
3851 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3855 # check for unnecessary parentheses around function pointer uses
3856 # ie: (foo->bar)(); should be foo->bar();
3857 # but not "if (foo->bar) (" to avoid some false positives
3858 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3860 if (CHK("UNNECESSARY_PARENTHESES",
3861 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3863 my $var2 = deparenthesize($var);
3865 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3869 #goto labels aren't indented, allow a single space however
3870 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3871 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3872 if (WARN("INDENTED_LABEL",
3873 "labels should not be indented\n" . $herecurr) &&
3875 $fixed[$fixlinenr] =~
3880 # return is not a function
3881 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3883 if ($^V && $^V ge 5.10.0 &&
3884 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3886 $value = deparenthesize($value);
3887 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3888 ERROR("RETURN_PARENTHESES",
3889 "return is not a function, parentheses are not required\n" . $herecurr);
3891 } elsif ($spacing !~ /\s+/) {
3893 "space required before the open parenthesis '('\n" . $herecurr);
3897 # unnecessary return in a void function
3898 # at end-of-function, with the previous line a single leading tab, then return;
3899 # and the line before that not a goto label target like "out:"
3900 if ($sline =~ /^[ \+]}\s*$/ &&
3901 $prevline =~ /^\+\treturn\s*;\s*$/ &&
3903 $lines[$linenr - 3] =~ /^[ +]/ &&
3904 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3906 "void function return statements are not generally useful\n" . $hereprev);
3909 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3910 if ($^V && $^V ge 5.10.0 &&
3911 $line =~ /\bif\s*((?:\(\s*){2,})/) {
3912 my $openparens = $1;
3913 my $count = $openparens =~ tr@\(@\(@;
3915 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3916 my $comp = $4; #Not $1 because of $LvalOrFunc
3917 $msg = " - maybe == should be = ?" if ($comp eq "==");
3918 WARN("UNNECESSARY_PARENTHESES",
3919 "Unnecessary parentheses$msg\n" . $herecurr);
3923 # Return of what appears to be an errno should normally be -'ve
3924 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3926 if ($name ne 'EOF' && $name ne 'ERROR') {
3927 WARN("USE_NEGATIVE_ERRNO",
3928 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3932 # Need a space before open parenthesis after if, while etc
3933 if ($line =~ /\b(if|while|for|switch)\(/) {
3934 if (ERROR("SPACING",
3935 "space required before the open parenthesis '('\n" . $herecurr) &&
3937 $fixed[$fixlinenr] =~
3938 s/\b(if|while|for|switch)\(/$1 \(/;
3942 # Check for illegal assignment in if conditional -- and check for trailing
3943 # statements after the conditional.
3944 if ($line =~ /do\s*(?!{)/) {
3945 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3946 ctx_statement_block($linenr, $realcnt, 0)
3947 if (!defined $stat);
3948 my ($stat_next) = ctx_statement_block($line_nr_next,
3949 $remain_next, $off_next);
3950 $stat_next =~ s/\n./\n /g;
3951 ##print "stat<$stat> stat_next<$stat_next>\n";
3953 if ($stat_next =~ /^\s*while\b/) {
3954 # If the statement carries leading newlines,
3955 # then count those as offsets.
3957 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3959 statement_rawlines($whitespace) - 1;
3961 $suppress_whiletrailers{$line_nr_next +
3965 if (!defined $suppress_whiletrailers{$linenr} &&
3966 defined($stat) && defined($cond) &&
3967 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3968 my ($s, $c) = ($stat, $cond);
3970 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3971 ERROR("ASSIGN_IN_IF",
3972 "do not use assignment in if condition\n" . $herecurr);
3975 # Find out what is on the end of the line after the
3977 substr($s, 0, length($c), '');
3979 $s =~ s/$;//g; # Remove any comments
3980 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3981 $c !~ /}\s*while\s*/)
3983 # Find out how long the conditional actually is.
3984 my @newlines = ($c =~ /\n/gs);
3985 my $cond_lines = 1 + $#newlines;
3988 $stat_real = raw_line($linenr, $cond_lines)
3989 . "\n" if ($cond_lines);
3990 if (defined($stat_real) && $cond_lines > 1) {
3991 $stat_real = "[...]\n$stat_real";
3994 ERROR("TRAILING_STATEMENTS",
3995 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3999 # Check for bitwise tests written as boolean
4011 WARN("HEXADECIMAL_BOOLEAN_TEST",
4012 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4015 # if and else should not have general statements after it
4016 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4018 $s =~ s/$;//g; # Remove any comments
4019 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4020 ERROR("TRAILING_STATEMENTS",
4021 "trailing statements should be on next line\n" . $herecurr);
4024 # if should not continue a brace
4025 if ($line =~ /}\s*if\b/) {
4026 ERROR("TRAILING_STATEMENTS",
4027 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4030 # case and default should not have general statements after them
4031 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4033 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4037 ERROR("TRAILING_STATEMENTS",
4038 "trailing statements should be on next line\n" . $herecurr);
4041 # Check for }<nl>else {, these must be at the same
4042 # indent level to be relevant to each other.
4043 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4044 $previndent == $indent) {
4045 if (ERROR("ELSE_AFTER_BRACE",
4046 "else should follow close brace '}'\n" . $hereprev) &&
4047 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4048 fix_delete_line($fixlinenr - 1, $prevrawline);
4049 fix_delete_line($fixlinenr, $rawline);
4050 my $fixedline = $prevrawline;
4051 $fixedline =~ s/}\s*$//;
4052 if ($fixedline !~ /^\+\s*$/) {
4053 fix_insert_line($fixlinenr, $fixedline);
4055 $fixedline = $rawline;
4056 $fixedline =~ s/^(.\s*)else/$1} else/;
4057 fix_insert_line($fixlinenr, $fixedline);
4061 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4062 $previndent == $indent) {
4063 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4065 # Find out what is on the end of the line after the
4067 substr($s, 0, length($c), '');
4070 if ($s =~ /^\s*;/) {
4071 if (ERROR("WHILE_AFTER_BRACE",
4072 "while should follow close brace '}'\n" . $hereprev) &&
4073 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4074 fix_delete_line($fixlinenr - 1, $prevrawline);
4075 fix_delete_line($fixlinenr, $rawline);
4076 my $fixedline = $prevrawline;
4077 my $trailing = $rawline;
4078 $trailing =~ s/^\+//;
4079 $trailing = trim($trailing);
4080 $fixedline =~ s/}\s*$/} $trailing/;
4081 fix_insert_line($fixlinenr, $fixedline);
4086 #Specific variable tests
4087 while ($line =~ m{($Constant|$Lval)}g) {
4090 #gcc binary extension
4091 if ($var =~ /^$Binary$/) {
4092 if (WARN("GCC_BINARY_CONSTANT",
4093 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4095 my $hexval = sprintf("0x%x", oct($var));
4096 $fixed[$fixlinenr] =~
4097 s/\b$var\b/$hexval/;
4102 if ($var !~ /^$Constant$/ &&
4103 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4104 #Ignore Page<foo> variants
4105 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4106 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4107 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4108 #Ignore some three character SI units explicitly, like MiB and KHz
4109 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4110 while ($var =~ m{($Ident)}g) {
4112 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4114 seed_camelcase_includes();
4115 if (!$file && !$camelcase_file_seeded) {
4116 seed_camelcase_file($realfile);
4117 $camelcase_file_seeded = 1;
4120 if (!defined $camelcase{$word}) {
4121 $camelcase{$word} = 1;
4123 "Avoid CamelCase: <$word>\n" . $herecurr);
4129 #no spaces allowed after \ in define
4130 if ($line =~ /\#\s*define.*\\\s+$/) {
4131 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4132 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4134 $fixed[$fixlinenr] =~ s/\s+$//;
4138 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4139 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4141 my $checkfile = "include/linux/$file";
4142 if (-f "$root/$checkfile" &&
4143 $realfile ne $checkfile &&
4144 $1 !~ /$allowed_asm_includes/)
4146 if ($realfile =~ m{^arch/}) {
4147 CHK("ARCH_INCLUDE_LINUX",
4148 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4150 WARN("INCLUDE_LINUX",
4151 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4156 # multi-statement macros should be enclosed in a do while loop, grab the
4157 # first statement and ensure its the whole macro if its not enclosed
4158 # in a known good container
4159 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4160 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4163 my ($off, $dstat, $dcond, $rest);
4165 my $has_flow_statement = 0;
4166 my $has_arg_concat = 0;
4167 ($dstat, $dcond, $ln, $cnt, $off) =
4168 ctx_statement_block($linenr, $realcnt, 0);
4170 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4171 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4173 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4174 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4176 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4178 $dstat =~ s/\\\n.//g;
4179 $dstat =~ s/^\s*//s;
4180 $dstat =~ s/\s*$//s;
4182 # Flatten any parentheses and braces
4183 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4184 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4185 $dstat =~ s/\[[^\[\]]*\]/1/)
4189 # Flatten any obvious string concatentation.
4190 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4191 $dstat =~ s/$Ident\s*("X*")/$1/)
4195 my $exceptions = qr{
4207 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4209 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4210 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4211 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4212 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4213 $dstat !~ /$exceptions/ &&
4214 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4215 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4216 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4217 $dstat !~ /^for\s*$Constant$/ && # for (...)
4218 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4219 $dstat !~ /^do\s*{/ && # do {...
4220 $dstat !~ /^\({/ && # ({...
4221 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4224 my $herectx = $here . "\n";
4225 my $cnt = statement_rawlines($ctx);
4227 for (my $n = 0; $n < $cnt; $n++) {
4228 $herectx .= raw_line($linenr, $n) . "\n";
4231 if ($dstat =~ /;/) {
4232 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4233 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4235 ERROR("COMPLEX_MACRO",
4236 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4240 # check for macros with flow control, but without ## concatenation
4241 # ## concatenation is commonly a macro that defines a function so ignore those
4242 if ($has_flow_statement && !$has_arg_concat) {
4243 my $herectx = $here . "\n";
4244 my $cnt = statement_rawlines($ctx);
4246 for (my $n = 0; $n < $cnt; $n++) {
4247 $herectx .= raw_line($linenr, $n) . "\n";
4249 WARN("MACRO_WITH_FLOW_CONTROL",
4250 "Macros with flow control statements should be avoided\n" . "$herectx");
4253 # check for line continuations outside of #defines, preprocessor #, and asm
4256 if ($prevline !~ /^..*\\$/ &&
4257 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4258 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4259 $line =~ /^\+.*\\$/) {
4260 WARN("LINE_CONTINUATIONS",
4261 "Avoid unnecessary line continuations\n" . $herecurr);
4265 # do {} while (0) macro tests:
4266 # single-statement macros do not need to be enclosed in do while (0) loop,
4267 # macro should not end with a semicolon
4268 if ($^V && $^V ge 5.10.0 &&
4269 $realfile !~ m@/vmlinux.lds.h$@ &&
4270 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4273 my ($off, $dstat, $dcond, $rest);
4275 ($dstat, $dcond, $ln, $cnt, $off) =
4276 ctx_statement_block($linenr, $realcnt, 0);
4279 $dstat =~ s/\\\n.//g;
4281 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4286 my $cnt = statement_rawlines($ctx);
4287 my $herectx = $here . "\n";
4289 for (my $n = 0; $n < $cnt; $n++) {
4290 $herectx .= raw_line($linenr, $n) . "\n";
4293 if (($stmts =~ tr/;/;/) == 1 &&
4294 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4295 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4296 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4298 if (defined $semis && $semis ne "") {
4299 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4300 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4302 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4304 my $cnt = statement_rawlines($ctx);
4305 my $herectx = $here . "\n";
4307 for (my $n = 0; $n < $cnt; $n++) {
4308 $herectx .= raw_line($linenr, $n) . "\n";
4311 WARN("TRAILING_SEMICOLON",
4312 "macros should not use a trailing semicolon\n" . "$herectx");
4316 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4317 # all assignments may have only one of the following with an assignment:
4320 # VMLINUX_SYMBOL(...)
4321 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4322 WARN("MISSING_VMLINUX_SYMBOL",
4323 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4326 # check for redundant bracing round if etc
4327 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4328 my ($level, $endln, @chunks) =
4329 ctx_statement_full($linenr, $realcnt, 1);
4330 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4331 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4332 if ($#chunks > 0 && $level == 0) {
4336 my $herectx = $here . "\n";
4337 my $ln = $linenr - 1;
4338 for my $chunk (@chunks) {
4339 my ($cond, $block) = @{$chunk};
4341 # If the condition carries leading newlines, then count those as offsets.
4342 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4343 my $offset = statement_rawlines($whitespace) - 1;
4345 $allowed[$allow] = 0;
4346 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4348 # We have looked at and allowed this specific line.
4349 $suppress_ifbraces{$ln + $offset} = 1;
4351 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4352 $ln += statement_rawlines($block) - 1;
4354 substr($block, 0, length($cond), '');
4356 $seen++ if ($block =~ /^\s*{/);
4358 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4359 if (statement_lines($cond) > 1) {
4360 #print "APW: ALLOWED: cond<$cond>\n";
4361 $allowed[$allow] = 1;
4363 if ($block =~/\b(?:if|for|while)\b/) {
4364 #print "APW: ALLOWED: block<$block>\n";
4365 $allowed[$allow] = 1;
4367 if (statement_block_size($block) > 1) {
4368 #print "APW: ALLOWED: lines block<$block>\n";
4369 $allowed[$allow] = 1;
4374 my $sum_allowed = 0;
4375 foreach (@allowed) {
4378 if ($sum_allowed == 0) {
4380 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4381 } elsif ($sum_allowed != $allow &&
4384 "braces {} should be used on all arms of this statement\n" . $herectx);
4389 if (!defined $suppress_ifbraces{$linenr - 1} &&
4390 $line =~ /\b(if|while|for|else)\b/) {
4393 # Check the pre-context.
4394 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4395 #print "APW: ALLOWED: pre<$1>\n";
4399 my ($level, $endln, @chunks) =
4400 ctx_statement_full($linenr, $realcnt, $-[0]);
4402 # Check the condition.
4403 my ($cond, $block) = @{$chunks[0]};
4404 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4405 if (defined $cond) {
4406 substr($block, 0, length($cond), '');
4408 if (statement_lines($cond) > 1) {
4409 #print "APW: ALLOWED: cond<$cond>\n";
4412 if ($block =~/\b(?:if|for|while)\b/) {
4413 #print "APW: ALLOWED: block<$block>\n";
4416 if (statement_block_size($block) > 1) {
4417 #print "APW: ALLOWED: lines block<$block>\n";
4420 # Check the post-context.
4421 if (defined $chunks[1]) {
4422 my ($cond, $block) = @{$chunks[1]};
4423 if (defined $cond) {
4424 substr($block, 0, length($cond), '');
4426 if ($block =~ /^\s*\{/) {
4427 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4431 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4432 my $herectx = $here . "\n";
4433 my $cnt = statement_rawlines($block);
4435 for (my $n = 0; $n < $cnt; $n++) {
4436 $herectx .= raw_line($linenr, $n) . "\n";
4440 "braces {} are not necessary for single statement blocks\n" . $herectx);
4444 # check for unnecessary blank lines around braces
4445 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4447 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
4449 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4451 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
4454 # no volatiles please
4455 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4456 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4458 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4461 # concatenated string without spaces between elements
4462 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4463 CHK("CONCATENATED_STRING",
4464 "Concatenated strings should use spaces between elements\n" . $herecurr);
4468 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4469 CHK("REDUNDANT_CODE",
4470 "if this code is redundant consider removing it\n" .
4474 # check for needless "if (<foo>) fn(<foo>)" uses
4475 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4476 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4477 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4479 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4483 # check for unnecessary "Out of Memory" messages
4484 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4485 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4486 (defined $1 || defined $3) &&
4489 my $testline = $lines[$linenr - 3];
4491 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4492 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4494 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4496 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4500 # check for logging functions with KERN_<LEVEL>
4501 if ($line !~ /printk\s*\(/ &&
4502 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4504 if (WARN("UNNECESSARY_KERN_LEVEL",
4505 "Possible unnecessary $level\n" . $herecurr) &&
4507 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4511 # check for mask then right shift without a parentheses
4512 if ($^V && $^V ge 5.10.0 &&
4513 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4514 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4515 WARN("MASK_THEN_SHIFT",
4516 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4519 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4520 if ($line =~ /(\b$InitAttribute\b)/) {
4522 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4525 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4526 ERROR("MISPLACED_INIT",
4527 "$attr should be placed after $var\n" . $herecurr)) ||
4528 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4529 WARN("MISPLACED_INIT",
4530 "$attr should be placed after $var\n" . $herecurr))) &&
4532 $fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
4537 # check for $InitAttributeData (ie: __initdata) with const
4538 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4540 $attr =~ /($InitAttributePrefix)(.*)/;
4541 my $attr_prefix = $1;
4543 if (ERROR("INIT_ATTRIBUTE",
4544 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4546 $fixed[$fixlinenr] =~
4547 s/$InitAttributeData/${attr_prefix}initconst/;
4551 # check for $InitAttributeConst (ie: __initconst) without const
4552 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4554 if (ERROR("INIT_ATTRIBUTE",
4555 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4557 my $lead = $fixed[$fixlinenr] =~
4558 /(^\+\s*(?:static\s+))/;
4560 $lead = "$lead " if ($lead !~ /^\+$/);
4561 $lead = "${lead}const ";
4562 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4566 # don't use __constant_<foo> functions outside of include/uapi/
4567 if ($realfile !~ m@^include/uapi/@ &&
4568 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4569 my $constant_func = $1;
4570 my $func = $constant_func;
4571 $func =~ s/^__constant_//;
4572 if (WARN("CONSTANT_CONVERSION",
4573 "$constant_func should be $func\n" . $herecurr) &&
4575 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4579 # prefer usleep_range over udelay
4580 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4582 # ignore udelay's < 10, however
4583 if (! ($delay < 10) ) {
4585 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4587 if ($delay > 2000) {
4589 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4593 # warn about unexpectedly long msleep's
4594 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4597 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4601 # check for comparisons of jiffies
4602 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4603 WARN("JIFFIES_COMPARISON",
4604 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4607 # check for comparisons of get_jiffies_64()
4608 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4609 WARN("JIFFIES_COMPARISON",
4610 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4613 # warn about #ifdefs in C files
4614 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4615 # print "#ifdef in C files should be avoided\n";
4616 # print "$herecurr";
4620 # warn about spacing in #ifdefs
4621 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4622 if (ERROR("SPACING",
4623 "exactly one space required after that #$1\n" . $herecurr) &&
4625 $fixed[$fixlinenr] =~
4626 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4631 # check for spinlock_t definitions without a comment.
4632 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4633 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4635 if (!ctx_has_comment($first_line, $linenr)) {
4636 CHK("UNCOMMENTED_DEFINITION",
4637 "$1 definition without comment\n" . $herecurr);
4640 # check for memory barriers without a comment.
4641 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4642 if (!ctx_has_comment($first_line, $linenr)) {
4643 WARN("MEMORY_BARRIER",
4644 "memory barrier without comment\n" . $herecurr);
4647 # check of hardware specific defines
4648 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4650 "architecture specific defines should be avoided\n" . $herecurr);
4653 # Check that the storage class is at the beginning of a declaration
4654 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4655 WARN("STORAGE_CLASS",
4656 "storage class should be at the beginning of the declaration\n" . $herecurr)
4659 # check the location of the inline attribute, that it is between
4660 # storage class and type.
4661 if ($line =~ /\b$Type\s+$Inline\b/ ||
4662 $line =~ /\b$Inline\s+$Storage\b/) {
4663 ERROR("INLINE_LOCATION",
4664 "inline keyword should sit between storage class and type\n" . $herecurr);
4667 # Check for __inline__ and __inline, prefer inline
4668 if ($realfile !~ m@\binclude/uapi/@ &&
4669 $line =~ /\b(__inline__|__inline)\b/) {
4671 "plain inline is preferred over $1\n" . $herecurr) &&
4673 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4678 # Check for __attribute__ packed, prefer __packed
4679 if ($realfile !~ m@\binclude/uapi/@ &&
4680 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4681 WARN("PREFER_PACKED",
4682 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4685 # Check for __attribute__ aligned, prefer __aligned
4686 if ($realfile !~ m@\binclude/uapi/@ &&
4687 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4688 WARN("PREFER_ALIGNED",
4689 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4692 # Check for __attribute__ format(printf, prefer __printf
4693 if ($realfile !~ m@\binclude/uapi/@ &&
4694 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4695 if (WARN("PREFER_PRINTF",
4696 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4698 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4703 # Check for __attribute__ format(scanf, prefer __scanf
4704 if ($realfile !~ m@\binclude/uapi/@ &&
4705 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4706 if (WARN("PREFER_SCANF",
4707 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4709 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4713 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4714 if ($^V && $^V ge 5.10.0 &&
4715 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4716 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4717 $line =~ /\b__weak\b/)) {
4718 ERROR("WEAK_DECLARATION",
4719 "Using weak declarations can have unintended link defects\n" . $herecurr);
4722 # check for sizeof(&)
4723 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4724 WARN("SIZEOF_ADDRESS",
4725 "sizeof(& should be avoided\n" . $herecurr);
4728 # check for sizeof without parenthesis
4729 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4730 if (WARN("SIZEOF_PARENTHESIS",
4731 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4733 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4737 # check for line continuations in quoted strings with odd counts of "
4738 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4739 WARN("LINE_CONTINUATIONS",
4740 "Avoid line continuations in quoted strings\n" . $herecurr);
4743 # check for struct spinlock declarations
4744 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4745 WARN("USE_SPINLOCK_T",
4746 "struct spinlock should be spinlock_t\n" . $herecurr);
4749 # check for seq_printf uses that could be seq_puts
4750 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4751 my $fmt = get_quoted_string($line, $rawline);
4752 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4753 if (WARN("PREFER_SEQ_PUTS",
4754 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4756 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4761 # Check for misused memsets
4762 if ($^V && $^V ge 5.10.0 &&
4764 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4770 if ($ms_size =~ /^(0x|)0$/i) {
4772 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4773 } elsif ($ms_size =~ /^(0x|)1$/i) {
4775 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4779 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4780 if ($^V && $^V ge 5.10.0 &&
4781 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4782 if (WARN("PREFER_ETHER_ADDR_COPY",
4783 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4785 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4789 # typecasts on min/max could be min_t/max_t
4790 if ($^V && $^V ge 5.10.0 &&
4792 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4793 if (defined $2 || defined $7) {
4795 my $cast1 = deparenthesize($2);
4797 my $cast2 = deparenthesize($7);
4801 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4802 $cast = "$cast1 or $cast2";
4803 } elsif ($cast1 ne "") {
4809 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4813 # check usleep_range arguments
4814 if ($^V && $^V ge 5.10.0 &&
4816 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4820 WARN("USLEEP_RANGE",
4821 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4822 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4824 WARN("USLEEP_RANGE",
4825 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4829 # check for naked sscanf
4830 if ($^V && $^V ge 5.10.0 &&
4832 $line =~ /\bsscanf\b/ &&
4833 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4834 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4835 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4836 my $lc = $stat =~ tr@\n@@;
4837 $lc = $lc + $linenr;
4838 my $stat_real = raw_line($linenr, 0);
4839 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4840 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4842 WARN("NAKED_SSCANF",
4843 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4846 # check for simple sscanf that should be kstrto<foo>
4847 if ($^V && $^V ge 5.10.0 &&
4849 $line =~ /\bsscanf\b/) {
4850 my $lc = $stat =~ tr@\n@@;
4851 $lc = $lc + $linenr;
4852 my $stat_real = raw_line($linenr, 0);
4853 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4854 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4856 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4858 my $count = $format =~ tr@%@%@;
4860 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4861 WARN("SSCANF_TO_KSTRTO",
4862 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4867 # check for new externs in .h files.
4868 if ($realfile =~ /\.h$/ &&
4869 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4870 if (CHK("AVOID_EXTERNS",
4871 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4873 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4877 # check for new externs in .c files.
4878 if ($realfile =~ /\.c$/ && defined $stat &&
4879 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4881 my $function_name = $1;
4882 my $paren_space = $2;
4885 if (defined $cond) {
4886 substr($s, 0, length($cond), '');
4888 if ($s =~ /^\s*;/ &&
4889 $function_name ne 'uninitialized_var')
4891 WARN("AVOID_EXTERNS",
4892 "externs should be avoided in .c files\n" . $herecurr);
4895 if ($paren_space =~ /\n/) {
4896 WARN("FUNCTION_ARGUMENTS",
4897 "arguments for function declarations should follow identifier\n" . $herecurr);
4900 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4901 $stat =~ /^.\s*extern\s+/)
4903 WARN("AVOID_EXTERNS",
4904 "externs should be avoided in .c files\n" . $herecurr);
4907 # checks for new __setup's
4908 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4911 if (!grep(/$name/, @setup_docs)) {
4912 CHK("UNDOCUMENTED_SETUP",
4913 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4917 # check for pointless casting of kmalloc return
4918 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4919 WARN("UNNECESSARY_CASTS",
4920 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4924 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4925 if ($^V && $^V ge 5.10.0 &&
4926 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4927 CHK("ALLOC_SIZEOF_STRUCT",
4928 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4931 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
4932 if ($^V && $^V ge 5.10.0 &&
4933 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
4937 my $newfunc = "kmalloc_array";
4938 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
4941 if ($a1 =~ /^sizeof\s*\S/) {
4945 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
4946 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
4947 if (WARN("ALLOC_WITH_MULTIPLY",
4948 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
4950 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
4956 # check for krealloc arg reuse
4957 if ($^V && $^V ge 5.10.0 &&
4958 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
4959 WARN("KREALLOC_ARG_REUSE",
4960 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
4963 # check for alloc argument mismatch
4964 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
4965 WARN("ALLOC_ARRAY_ARGS",
4966 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
4969 # check for multiple semicolons
4970 if ($line =~ /;\s*;\s*$/) {
4971 if (WARN("ONE_SEMICOLON",
4972 "Statements terminations use 1 semicolon\n" . $herecurr) &&
4974 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
4978 # check for #defines like: 1 << <digit> that could be BIT(digit)
4979 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
4981 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
4982 if (CHK("BIT_MACRO",
4983 "Prefer using the BIT$ull macro\n" . $herecurr) &&
4985 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
4989 # check for case / default statements not preceded by break/fallthrough/switch
4990 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
4992 my $has_statement = 0;
4994 my $prevline = $linenr;
4995 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
4997 my $rline = $rawlines[$prevline - 1];
4998 my $fline = $lines[$prevline - 1];
4999 last if ($fline =~ /^\@\@/);
5000 next if ($fline =~ /^\-/);
5001 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5002 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5003 next if ($fline =~ /^.[\s$;]*$/);
5006 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5008 if (!$has_break && $has_statement) {
5009 WARN("MISSING_BREAK",
5010 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5014 # check for switch/default statements without a break;
5015 if ($^V && $^V ge 5.10.0 &&
5017 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5019 my $herectx = $here . "\n";
5020 my $cnt = statement_rawlines($stat);
5021 for (my $n = 0; $n < $cnt; $n++) {
5022 $herectx .= raw_line($linenr, $n) . "\n";
5024 WARN("DEFAULT_NO_BREAK",
5025 "switch default: should use break\n" . $herectx);
5028 # check for gcc specific __FUNCTION__
5029 if ($line =~ /\b__FUNCTION__\b/) {
5030 if (WARN("USE_FUNC",
5031 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5033 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5037 # check for use of yield()
5038 if ($line =~ /\byield\s*\(\s*\)/) {
5040 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5043 # check for comparisons against true and false
5044 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5052 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5054 my $type = lc($otype);
5055 if ($type =~ /^(?:true|false)$/) {
5056 if (("$test" eq "==" && "$type" eq "true") ||
5057 ("$test" eq "!=" && "$type" eq "false")) {
5061 CHK("BOOL_COMPARISON",
5062 "Using comparison to $otype is error prone\n" . $herecurr);
5064 ## maybe suggesting a correct construct would better
5065 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5070 # check for semaphores initialized locked
5071 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5072 WARN("CONSIDER_COMPLETION",
5073 "consider using a completion\n" . $herecurr);
5076 # recommend kstrto* over simple_strto* and strict_strto*
5077 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5078 WARN("CONSIDER_KSTRTO",
5079 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5082 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5083 if ($line =~ /^.\s*__initcall\s*\(/) {
5084 WARN("USE_DEVICE_INITCALL",
5085 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5088 # check for various ops structs, ensure they are const.
5089 my $struct_ops = qr{acpi_dock_ops|
5090 address_space_operations|
5092 block_device_operations|
5097 file_lock_operations|
5107 lock_manager_operations|
5113 pipe_buf_operations|
5114 platform_hibernation_ops|
5115 platform_suspend_ops|
5120 soc_pcmcia_socket_ops|
5126 if ($line !~ /\bconst\b/ &&
5127 $line =~ /\bstruct\s+($struct_ops)\b/) {
5128 WARN("CONST_STRUCT",
5129 "struct $1 should normally be const\n" .
5133 # use of NR_CPUS is usually wrong
5134 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5135 if ($line =~ /\bNR_CPUS\b/ &&
5136 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5137 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5138 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5139 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5140 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5143 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5146 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5147 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5148 ERROR("DEFINE_ARCH_HAS",
5149 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5152 # check for %L{u,d,i} in strings
5154 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5155 $string = substr($rawline, $-[1], $+[1] - $-[1]);
5156 $string =~ s/%%/__/g;
5157 if ($string =~ /(?<!%)%L[udi]/) {
5159 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
5164 # whine mightly about in_atomic
5165 if ($line =~ /\bin_atomic\s*\(/) {
5166 if ($realfile =~ m@^drivers/@) {
5168 "do not use in_atomic in drivers\n" . $herecurr);
5169 } elsif ($realfile !~ m@^kernel/@) {
5171 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5175 # check for lockdep_set_novalidate_class
5176 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5177 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5178 if ($realfile !~ m@^kernel/lockdep@ &&
5179 $realfile !~ m@^include/linux/lockdep@ &&
5180 $realfile !~ m@^drivers/base/core@) {
5182 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5186 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5187 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5188 WARN("EXPORTED_WORLD_WRITABLE",
5189 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5192 # Mode permission misuses where it seems decimal should be octal
5193 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5194 if ($^V && $^V ge 5.10.0 &&
5195 $line =~ /$mode_perms_search/) {
5196 foreach my $entry (@mode_permission_funcs) {
5197 my $func = $entry->[0];
5198 my $arg_pos = $entry->[1];
5203 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5205 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5206 if ($line =~ /$test/) {
5208 $val = $6 if ($skip_args ne "");
5210 if ($val !~ /^0$/ &&
5211 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5212 length($val) ne 4)) {
5213 ERROR("NON_OCTAL_PERMISSIONS",
5214 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5221 # If we have no input at all, then there is nothing to report on
5222 # so just keep quiet.
5223 if ($#rawlines == -1) {
5227 # In mailback mode only produce a report in the negative, for
5228 # things that appear to be patches.
5229 if ($mailback && ($clean == 1 || !$is_patch)) {
5233 # This is not a patch, and we are are in 'no-patch' mode so
5235 if (!$chk_patch && !$is_patch) {
5240 ERROR("NOT_UNIFIED_DIFF",
5241 "Does not appear to be a unified-diff format patch\n");
5243 if ($is_patch && $chk_signoff && $signoff == 0) {
5244 ERROR("MISSING_SIGN_OFF",
5245 "Missing Signed-off-by: line(s)\n");
5248 print report_dump();
5249 if ($summary && !($clean == 1 && $quiet == 1)) {
5250 print "$filename " if ($summary_file);
5251 print "total: $cnt_error errors, $cnt_warn warnings, " .
5252 (($check)? "$cnt_chk checks, " : "") .
5253 "$cnt_lines lines checked\n";
5254 print "\n" if ($quiet == 0);
5259 if ($^V lt 5.10.0) {
5260 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5261 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5264 # If there were whitespace errors which cleanpatch can fix
5265 # then suggest that.
5266 if ($rpt_cleaners) {
5267 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5268 print " scripts/cleanfile\n\n";
5273 hash_show_words(\%use_type, "Used");
5274 hash_show_words(\%ignore_type, "Ignored");
5276 if ($clean == 0 && $fix &&
5277 ("@rawlines" ne "@fixed" ||
5278 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5279 my $newfile = $filename;
5280 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5284 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5286 open($f, '>', $newfile)
5287 or die "$P: Can't open $newfile for write\n";
5288 foreach my $fixed_line (@fixed) {
5291 if ($linecount > 3) {
5292 $fixed_line =~ s/^\+//;
5293 print $f $fixed_line . "\n";
5296 print $f $fixed_line . "\n";
5303 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5305 Do _NOT_ trust the results written to this file.
5306 Do _NOT_ submit these changes without inspecting them for correctness.
5308 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5309 No warranties, expressed or implied...
5315 if ($clean == 1 && $quiet == 0) {
5316 print "$vname has no obvious style problems and is ready for submission.\n"
5318 if ($clean == 0 && $quiet == 0) {
5320 $vname has style problems, please review.
5322 If any of these errors are false positives, please report
5323 them to the maintainer, see CHECKPATCH in MAINTAINERS.