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
287 ____cacheline_aligned|
288 ____cacheline_aligned_in_smp|
289 ____cacheline_internodealigned_in_smp|
293 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
294 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
295 our $Lval = qr{$Ident(?:$Member)*};
297 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
298 our $Binary = qr{(?i)0b[01]+$Int_type?};
299 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
300 our $Int = qr{[0-9]+$Int_type?};
301 our $Octal = qr{0[0-7]+$Int_type?};
302 our $String = qr{"[X\t]*"};
303 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
304 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
305 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
306 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
307 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
308 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
309 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
310 our $Arithmetic = qr{\+|-|\*|\/|%};
314 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
317 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
320 our $NonptrTypeMisordered;
321 our $NonptrTypeWithAttr;
325 our $DeclareMisordered;
327 our $NON_ASCII_UTF8 = qr{
328 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
329 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
330 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
331 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
332 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
333 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
334 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
338 [\x09\x0A\x0D\x20-\x7E] # ASCII
342 our $typeTypedefs = qr{(?x:
343 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
347 our $logFunctions = qr{(?x:
348 printk(?:_ratelimited|_once|)|
349 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
350 WARN(?:_RATELIMIT|_ONCE|)|
353 seq_vprintf|seq_printf|seq_puts
356 our $signature_tags = qr{(?xi:
367 our @typeListMisordered = (
368 qr{char\s+(?:un)?signed},
369 qr{int\s+(?:(?:un)?signed\s+)?short\s},
370 qr{int\s+short(?:\s+(?:un)?signed)},
371 qr{short\s+int(?:\s+(?:un)?signed)},
372 qr{(?:un)?signed\s+int\s+short},
373 qr{short\s+(?:un)?signed},
374 qr{long\s+int\s+(?:un)?signed},
375 qr{int\s+long\s+(?:un)?signed},
376 qr{long\s+(?:un)?signed\s+int},
377 qr{int\s+(?:un)?signed\s+long},
378 qr{int\s+(?:un)?signed},
379 qr{int\s+long\s+long\s+(?:un)?signed},
380 qr{long\s+long\s+int\s+(?:un)?signed},
381 qr{long\s+long\s+(?:un)?signed\s+int},
382 qr{long\s+long\s+(?:un)?signed},
383 qr{long\s+(?:un)?signed},
388 qr{(?:(?:un)?signed\s+)?char},
389 qr{(?:(?:un)?signed\s+)?short\s+int},
390 qr{(?:(?:un)?signed\s+)?short},
391 qr{(?:(?:un)?signed\s+)?int},
392 qr{(?:(?:un)?signed\s+)?long\s+int},
393 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
394 qr{(?:(?:un)?signed\s+)?long\s+long},
395 qr{(?:(?:un)?signed\s+)?long},
404 qr{${Ident}_handler},
405 qr{${Ident}_handler_fn},
408 our @typeListWithAttr = (
410 qr{struct\s+$InitAttribute\s+$Ident},
411 qr{union\s+$InitAttribute\s+$Ident},
414 our @modifierList = (
418 our @mode_permission_funcs = (
420 ["module_param_(?:array|named|string)", 4],
421 ["module_param_array_named", 5],
422 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
423 ["proc_create(?:_data|)", 2],
424 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
427 #Create a search pattern for all these functions to speed up a loop below
428 our $mode_perms_search = "";
429 foreach my $entry (@mode_permission_funcs) {
430 $mode_perms_search .= '|' if ($mode_perms_search ne "");
431 $mode_perms_search .= $entry->[0];
434 our $allowed_asm_includes = qr{(?x:
440 # memory.h: ARM has a custom one
442 # Load common spelling mistakes and build regular expression list.
446 if (open(my $spelling, '<', $spelling_file)) {
448 while (<$spelling>) {
451 $line =~ s/\s*\n?$//g;
454 next if ($line =~ m/^\s*#/);
455 next if ($line =~ m/^\s*$/);
457 my ($suspect, $fix) = split(/\|\|/, $line);
459 push(@spelling_list, $suspect);
460 $spelling_fix{$suspect} = $fix;
463 $misspellings = join("|", @spelling_list);
465 warn "No typos will be found - file '$spelling_file': $!\n";
469 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
470 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
471 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
472 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
473 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
475 (?:$Modifier\s+|const\s+)*
477 (?:typeof|__typeof__)\s*\([^\)]*\)|
481 (?:\s+$Modifier|\s+const)*
483 $NonptrTypeMisordered = qr{
484 (?:$Modifier\s+|const\s+)*
488 (?:\s+$Modifier|\s+const)*
490 $NonptrTypeWithAttr = qr{
491 (?:$Modifier\s+|const\s+)*
493 (?:typeof|__typeof__)\s*\([^\)]*\)|
497 (?:\s+$Modifier|\s+const)*
501 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
502 (?:\s+$Inline|\s+$Modifier)*
504 $TypeMisordered = qr{
505 $NonptrTypeMisordered
506 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
507 (?:\s+$Inline|\s+$Modifier)*
509 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
510 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
514 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
516 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
517 # requires at least perl version v5.10.0
518 # Any use must be runtime checked with $^V
520 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
521 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
522 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
524 our $declaration_macros = qr{(?x:
525 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
526 (?:$Storage\s+)?LIST_HEAD\s*\(|
527 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
532 return "" if (!defined($string));
534 while ($string =~ /^\s*\(.*\)\s*$/) {
535 $string =~ s@^\s*\(\s*@@;
536 $string =~ s@\s*\)\s*$@@;
539 $string =~ s@\s+@ @g;
544 sub seed_camelcase_file {
547 return if (!(-f $file));
551 open(my $include_file, '<', "$file")
552 or warn "$P: Can't read '$file' $!\n";
553 my $text = <$include_file>;
554 close($include_file);
556 my @lines = split('\n', $text);
558 foreach my $line (@lines) {
559 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
560 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
562 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
564 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
570 my $camelcase_seeded = 0;
571 sub seed_camelcase_includes {
572 return if ($camelcase_seeded);
575 my $camelcase_cache = "";
576 my @include_files = ();
578 $camelcase_seeded = 1;
581 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
582 chomp $git_last_include_commit;
583 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
585 my $last_mod_date = 0;
586 $files = `find $root/include -name "*.h"`;
587 @include_files = split('\n', $files);
588 foreach my $file (@include_files) {
589 my $date = POSIX::strftime("%Y%m%d%H%M",
590 localtime((stat $file)[9]));
591 $last_mod_date = $date if ($last_mod_date < $date);
593 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
596 if ($camelcase_cache ne "" && -f $camelcase_cache) {
597 open(my $camelcase_file, '<', "$camelcase_cache")
598 or warn "$P: Can't read '$camelcase_cache' $!\n";
599 while (<$camelcase_file>) {
603 close($camelcase_file);
609 $files = `git ls-files "include/*.h"`;
610 @include_files = split('\n', $files);
613 foreach my $file (@include_files) {
614 seed_camelcase_file($file);
617 if ($camelcase_cache ne "") {
618 unlink glob ".checkpatch-camelcase.*";
619 open(my $camelcase_file, '>', "$camelcase_cache")
620 or warn "$P: Can't write '$camelcase_cache' $!\n";
621 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
622 print $camelcase_file ("$_\n");
624 close($camelcase_file);
628 sub git_commit_info {
629 my ($commit, $id, $desc) = @_;
631 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
633 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
634 $output =~ s/^\s*//gm;
635 my @lines = split("\n", $output);
637 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
638 # Maybe one day convert this block of bash into something that returns
639 # all matching commit ids, but it's very slow...
641 # echo "checking commits $1..."
642 # git rev-list --remotes | grep -i "^$1" |
643 # while read line ; do
644 # git log --format='%H %s' -1 $line |
645 # echo "commit $(cut -c 1-12,41-)"
647 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
649 $id = substr($lines[0], 0, 12);
650 $desc = substr($lines[0], 41);
656 $chk_signoff = 0 if ($file);
661 my @fixed_inserted = ();
662 my @fixed_deleted = ();
666 for my $filename (@ARGV) {
669 open($FILE, '-|', "diff -u /dev/null $filename") ||
670 die "$P: $filename: diff failed - $!\n";
671 } elsif ($filename eq '-') {
672 open($FILE, '<&STDIN');
674 open($FILE, '<', "$filename") ||
675 die "$P: $filename: open failed - $!\n";
677 if ($filename eq '-') {
678 $vname = 'Your patch';
687 if (!process($filename)) {
693 @fixed_inserted = ();
700 sub top_of_kernel_tree {
704 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
705 "README", "Documentation", "arch", "include", "drivers",
706 "fs", "init", "ipc", "kernel", "lib", "scripts",
709 foreach my $check (@tree_check) {
710 if (! -e $root . '/' . $check) {
718 my ($formatted_email) = @_;
724 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
727 $comment = $3 if defined $3;
728 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
730 $comment = $2 if defined $2;
731 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
733 $comment = $2 if defined $2;
734 $formatted_email =~ s/$address.*$//;
735 $name = $formatted_email;
737 $name =~ s/^\"|\"$//g;
738 # If there's a name left after stripping spaces and
739 # leading quotes, and the address doesn't have both
740 # leading and trailing angle brackets, the address
742 # "joe smith joe@smith.com" bad
743 # "joe smith <joe@smith.com" bad
744 if ($name ne "" && $address !~ /^<[^>]+>$/) {
752 $name =~ s/^\"|\"$//g;
753 $address = trim($address);
754 $address =~ s/^\<|\>$//g;
756 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
757 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
761 return ($name, $address, $comment);
765 my ($name, $address) = @_;
770 $name =~ s/^\"|\"$//g;
771 $address = trim($address);
773 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
774 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
779 $formatted_email = "$address";
781 $formatted_email = "$name <$address>";
784 return $formatted_email;
790 foreach my $path (split(/:/, $ENV{PATH})) {
791 if (-e "$path/$bin") {
802 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
803 if (-e "$path/$conf") {
804 return "$path/$conf";
816 for my $c (split(//, $str)) {
820 for (; ($n % 8) != 0; $n++) {
832 (my $res = shift) =~ tr/\t/ /c;
839 # Drop the diff line leader and expand tabs
841 $line = expand_tabs($line);
843 # Pick the indent from the front of the line.
844 my ($white) = ($line =~ /^(\s*)/);
846 return (length($line), length($white));
849 my $sanitise_quote = '';
851 sub sanitise_line_reset {
852 my ($in_comment) = @_;
855 $sanitise_quote = '*/';
857 $sanitise_quote = '';
870 # Always copy over the diff marker.
871 $res = substr($line, 0, 1);
873 for ($off = 1; $off < length($line); $off++) {
874 $c = substr($line, $off, 1);
876 # Comments we are wacking completly including the begin
877 # and end, all to $;.
878 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
879 $sanitise_quote = '*/';
881 substr($res, $off, 2, "$;$;");
885 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
886 $sanitise_quote = '';
887 substr($res, $off, 2, "$;$;");
891 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
892 $sanitise_quote = '//';
894 substr($res, $off, 2, $sanitise_quote);
899 # A \ in a string means ignore the next character.
900 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
902 substr($res, $off, 2, 'XX');
907 if ($c eq "'" || $c eq '"') {
908 if ($sanitise_quote eq '') {
909 $sanitise_quote = $c;
911 substr($res, $off, 1, $c);
913 } elsif ($sanitise_quote eq $c) {
914 $sanitise_quote = '';
918 #print "c<$c> SQ<$sanitise_quote>\n";
919 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
920 substr($res, $off, 1, $;);
921 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
922 substr($res, $off, 1, $;);
923 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
924 substr($res, $off, 1, 'X');
926 substr($res, $off, 1, $c);
930 if ($sanitise_quote eq '//') {
931 $sanitise_quote = '';
934 # The pathname on a #include may be surrounded by '<' and '>'.
935 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
936 my $clean = 'X' x length($1);
937 $res =~ s@\<.*\>@<$clean>@;
939 # The whole of a #error is a string.
940 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
941 my $clean = 'X' x length($1);
942 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
948 sub get_quoted_string {
949 my ($line, $rawline) = @_;
951 return "" if ($line !~ m/(\"[X\t]+\")/g);
952 return substr($rawline, $-[0], $+[0] - $-[0]);
955 sub ctx_statement_block {
956 my ($linenr, $remain, $off) = @_;
957 my $line = $linenr - 1;
974 @stack = (['', 0]) if ($#stack == -1);
976 #warn "CSB: blk<$blk> remain<$remain>\n";
977 # If we are about to drop off the end, pull in more
980 for (; $remain > 0; $line++) {
981 last if (!defined $lines[$line]);
982 next if ($lines[$line] =~ /^-/);
985 $blk .= $lines[$line] . "\n";
990 # Bail if there is no further context.
991 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
995 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1001 $c = substr($blk, $off, 1);
1002 $remainder = substr($blk, $off);
1004 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1006 # Handle nested #if/#else.
1007 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1008 push(@stack, [ $type, $level ]);
1009 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1010 ($type, $level) = @{$stack[$#stack - 1]};
1011 } elsif ($remainder =~ /^#\s*endif\b/) {
1012 ($type, $level) = @{pop(@stack)};
1015 # Statement ends at the ';' or a close '}' at the
1017 if ($level == 0 && $c eq ';') {
1021 # An else is really a conditional as long as its not else if
1022 if ($level == 0 && $coff_set == 0 &&
1023 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1024 $remainder =~ /^(else)(?:\s|{)/ &&
1025 $remainder !~ /^else\s+if\b/) {
1026 $coff = $off + length($1) - 1;
1028 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1029 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1032 if (($type eq '' || $type eq '(') && $c eq '(') {
1036 if ($type eq '(' && $c eq ')') {
1038 $type = ($level != 0)? '(' : '';
1040 if ($level == 0 && $coff < $soff) {
1043 #warn "CSB: mark coff<$coff>\n";
1046 if (($type eq '' || $type eq '{') && $c eq '{') {
1050 if ($type eq '{' && $c eq '}') {
1052 $type = ($level != 0)? '{' : '';
1055 if (substr($blk, $off + 1, 1) eq ';') {
1061 # Preprocessor commands end at the newline unless escaped.
1062 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1070 # We are truly at the end, so shuffle to the next line.
1077 my $statement = substr($blk, $soff, $off - $soff + 1);
1078 my $condition = substr($blk, $soff, $coff - $soff + 1);
1080 #warn "STATEMENT<$statement>\n";
1081 #warn "CONDITION<$condition>\n";
1083 #print "coff<$coff> soff<$off> loff<$loff>\n";
1085 return ($statement, $condition,
1086 $line, $remain + 1, $off - $loff + 1, $level);
1089 sub statement_lines {
1092 # Strip the diff line prefixes and rip blank lines at start and end.
1093 $stmt =~ s/(^|\n)./$1/g;
1097 my @stmt_lines = ($stmt =~ /\n/g);
1099 return $#stmt_lines + 2;
1102 sub statement_rawlines {
1105 my @stmt_lines = ($stmt =~ /\n/g);
1107 return $#stmt_lines + 2;
1110 sub statement_block_size {
1113 $stmt =~ s/(^|\n)./$1/g;
1119 my @stmt_lines = ($stmt =~ /\n/g);
1120 my @stmt_statements = ($stmt =~ /;/g);
1122 my $stmt_lines = $#stmt_lines + 2;
1123 my $stmt_statements = $#stmt_statements + 1;
1125 if ($stmt_lines > $stmt_statements) {
1128 return $stmt_statements;
1132 sub ctx_statement_full {
1133 my ($linenr, $remain, $off) = @_;
1134 my ($statement, $condition, $level);
1138 # Grab the first conditional/block pair.
1139 ($statement, $condition, $linenr, $remain, $off, $level) =
1140 ctx_statement_block($linenr, $remain, $off);
1141 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1142 push(@chunks, [ $condition, $statement ]);
1143 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1144 return ($level, $linenr, @chunks);
1147 # Pull in the following conditional/block pairs and see if they
1148 # could continue the statement.
1150 ($statement, $condition, $linenr, $remain, $off, $level) =
1151 ctx_statement_block($linenr, $remain, $off);
1152 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1153 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1155 push(@chunks, [ $condition, $statement ]);
1158 return ($level, $linenr, @chunks);
1162 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1164 my $start = $linenr - 1;
1171 my @stack = ($level);
1172 for ($line = $start; $remain > 0; $line++) {
1173 next if ($rawlines[$line] =~ /^-/);
1176 $blk .= $rawlines[$line];
1178 # Handle nested #if/#else.
1179 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1180 push(@stack, $level);
1181 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1182 $level = $stack[$#stack - 1];
1183 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1184 $level = pop(@stack);
1187 foreach my $c (split(//, $lines[$line])) {
1188 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1194 if ($c eq $close && $level > 0) {
1196 last if ($level == 0);
1197 } elsif ($c eq $open) {
1202 if (!$outer || $level <= 1) {
1203 push(@res, $rawlines[$line]);
1206 last if ($level == 0);
1209 return ($level, @res);
1211 sub ctx_block_outer {
1212 my ($linenr, $remain) = @_;
1214 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1218 my ($linenr, $remain) = @_;
1220 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1224 my ($linenr, $remain, $off) = @_;
1226 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1229 sub ctx_block_level {
1230 my ($linenr, $remain) = @_;
1232 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1234 sub ctx_statement_level {
1235 my ($linenr, $remain, $off) = @_;
1237 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1240 sub ctx_locate_comment {
1241 my ($first_line, $end_line) = @_;
1243 # Catch a comment on the end of the line itself.
1244 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1245 return $current_comment if (defined $current_comment);
1247 # Look through the context and try and figure out if there is a
1250 $current_comment = '';
1251 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1252 my $line = $rawlines[$linenr - 1];
1254 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1257 if ($line =~ m@/\*@) {
1260 if (!$in_comment && $current_comment ne '') {
1261 $current_comment = '';
1263 $current_comment .= $line . "\n" if ($in_comment);
1264 if ($line =~ m@\*/@) {
1269 chomp($current_comment);
1270 return($current_comment);
1272 sub ctx_has_comment {
1273 my ($first_line, $end_line) = @_;
1274 my $cmt = ctx_locate_comment($first_line, $end_line);
1276 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1277 ##print "CMMT: $cmt\n";
1279 return ($cmt ne '');
1283 my ($linenr, $cnt) = @_;
1285 my $offset = $linenr - 1;
1290 $line = $rawlines[$offset++];
1291 next if (defined($line) && $line =~ /^-/);
1303 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1306 $coded = sprintf("^%c", unpack('C', $2) + 64);
1315 my $av_preprocessor = 0;
1320 sub annotate_reset {
1321 $av_preprocessor = 0;
1323 @av_paren_type = ('E');
1324 $av_pend_colon = 'O';
1327 sub annotate_values {
1328 my ($stream, $type) = @_;
1331 my $var = '_' x length($stream);
1334 print "$stream\n" if ($dbg_values > 1);
1336 while (length($cur)) {
1337 @av_paren_type = ('E') if ($#av_paren_type < 0);
1338 print " <" . join('', @av_paren_type) .
1339 "> <$type> <$av_pending>" if ($dbg_values > 1);
1340 if ($cur =~ /^(\s+)/o) {
1341 print "WS($1)\n" if ($dbg_values > 1);
1342 if ($1 =~ /\n/ && $av_preprocessor) {
1343 $type = pop(@av_paren_type);
1344 $av_preprocessor = 0;
1347 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1348 print "CAST($1)\n" if ($dbg_values > 1);
1349 push(@av_paren_type, $type);
1352 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1353 print "DECLARE($1)\n" if ($dbg_values > 1);
1356 } elsif ($cur =~ /^($Modifier)\s*/) {
1357 print "MODIFIER($1)\n" if ($dbg_values > 1);
1360 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1361 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1362 $av_preprocessor = 1;
1363 push(@av_paren_type, $type);
1369 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1370 print "UNDEF($1)\n" if ($dbg_values > 1);
1371 $av_preprocessor = 1;
1372 push(@av_paren_type, $type);
1374 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1375 print "PRE_START($1)\n" if ($dbg_values > 1);
1376 $av_preprocessor = 1;
1378 push(@av_paren_type, $type);
1379 push(@av_paren_type, $type);
1382 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1383 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1384 $av_preprocessor = 1;
1386 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1390 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1391 print "PRE_END($1)\n" if ($dbg_values > 1);
1393 $av_preprocessor = 1;
1395 # Assume all arms of the conditional end as this
1396 # one does, and continue as if the #endif was not here.
1397 pop(@av_paren_type);
1398 push(@av_paren_type, $type);
1401 } elsif ($cur =~ /^(\\\n)/o) {
1402 print "PRECONT($1)\n" if ($dbg_values > 1);
1404 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1405 print "ATTR($1)\n" if ($dbg_values > 1);
1406 $av_pending = $type;
1409 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1410 print "SIZEOF($1)\n" if ($dbg_values > 1);
1416 } elsif ($cur =~ /^(if|while|for)\b/o) {
1417 print "COND($1)\n" if ($dbg_values > 1);
1421 } elsif ($cur =~/^(case)/o) {
1422 print "CASE($1)\n" if ($dbg_values > 1);
1423 $av_pend_colon = 'C';
1426 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1427 print "KEYWORD($1)\n" if ($dbg_values > 1);
1430 } elsif ($cur =~ /^(\()/o) {
1431 print "PAREN('$1')\n" if ($dbg_values > 1);
1432 push(@av_paren_type, $av_pending);
1436 } elsif ($cur =~ /^(\))/o) {
1437 my $new_type = pop(@av_paren_type);
1438 if ($new_type ne '_') {
1440 print "PAREN('$1') -> $type\n"
1441 if ($dbg_values > 1);
1443 print "PAREN('$1')\n" if ($dbg_values > 1);
1446 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1447 print "FUNC($1)\n" if ($dbg_values > 1);
1451 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1452 if (defined $2 && $type eq 'C' || $type eq 'T') {
1453 $av_pend_colon = 'B';
1454 } elsif ($type eq 'E') {
1455 $av_pend_colon = 'L';
1457 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1460 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1461 print "IDENT($1)\n" if ($dbg_values > 1);
1464 } elsif ($cur =~ /^($Assignment)/o) {
1465 print "ASSIGN($1)\n" if ($dbg_values > 1);
1468 } elsif ($cur =~/^(;|{|})/) {
1469 print "END($1)\n" if ($dbg_values > 1);
1471 $av_pend_colon = 'O';
1473 } elsif ($cur =~/^(,)/) {
1474 print "COMMA($1)\n" if ($dbg_values > 1);
1477 } elsif ($cur =~ /^(\?)/o) {
1478 print "QUESTION($1)\n" if ($dbg_values > 1);
1481 } elsif ($cur =~ /^(:)/o) {
1482 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1484 substr($var, length($res), 1, $av_pend_colon);
1485 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1490 $av_pend_colon = 'O';
1492 } elsif ($cur =~ /^(\[)/o) {
1493 print "CLOSE($1)\n" if ($dbg_values > 1);
1496 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1499 print "OPV($1)\n" if ($dbg_values > 1);
1506 substr($var, length($res), 1, $variant);
1509 } elsif ($cur =~ /^($Operators)/o) {
1510 print "OP($1)\n" if ($dbg_values > 1);
1511 if ($1 ne '++' && $1 ne '--') {
1515 } elsif ($cur =~ /(^.)/o) {
1516 print "C($1)\n" if ($dbg_values > 1);
1519 $cur = substr($cur, length($1));
1520 $res .= $type x length($1);
1524 return ($res, $var);
1528 my ($possible, $line) = @_;
1529 my $notPermitted = qr{(?:
1546 ^(?:typedef|struct|enum)\b
1548 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1549 if ($possible !~ $notPermitted) {
1550 # Check for modifiers.
1551 $possible =~ s/\s*$Storage\s*//g;
1552 $possible =~ s/\s*$Sparse\s*//g;
1553 if ($possible =~ /^\s*$/) {
1555 } elsif ($possible =~ /\s/) {
1556 $possible =~ s/\s*$Type\s*//g;
1557 for my $modifier (split(' ', $possible)) {
1558 if ($modifier !~ $notPermitted) {
1559 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1560 push(@modifierList, $modifier);
1565 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1566 push(@typeList, $possible);
1570 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1579 return defined $use_type{$type} if (scalar keys %use_type > 0);
1581 return !defined $ignore_type{$type};
1585 my ($level, $type, $msg) = @_;
1587 if (!show_type($type) ||
1588 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1593 $line = "$prefix$level:$type: $msg\n";
1595 $line = "$prefix$level: $msg\n";
1597 $line = (split('\n', $line))[0] . "\n" if ($terse);
1599 push(our @report, $line);
1608 sub fixup_current_range {
1609 my ($lineRef, $offset, $length) = @_;
1611 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1614 my $no = $o + $offset;
1615 my $nl = $l + $length;
1616 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1620 sub fix_inserted_deleted_lines {
1621 my ($linesRef, $insertedRef, $deletedRef) = @_;
1623 my $range_last_linenr = 0;
1624 my $delta_offset = 0;
1629 my $next_insert = 0;
1630 my $next_delete = 0;
1634 my $inserted = @{$insertedRef}[$next_insert++];
1635 my $deleted = @{$deletedRef}[$next_delete++];
1637 foreach my $old_line (@{$linesRef}) {
1639 my $line = $old_line; #don't modify the array
1640 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1642 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1643 $range_last_linenr = $new_linenr;
1644 fixup_current_range(\$line, $delta_offset, 0);
1647 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1648 $deleted = @{$deletedRef}[$next_delete++];
1650 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1653 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1654 push(@lines, ${$inserted}{'LINE'});
1655 $inserted = @{$insertedRef}[$next_insert++];
1657 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1661 push(@lines, $line);
1671 sub fix_insert_line {
1672 my ($linenr, $line) = @_;
1678 push(@fixed_inserted, $inserted);
1681 sub fix_delete_line {
1682 my ($linenr, $line) = @_;
1689 push(@fixed_deleted, $deleted);
1693 my ($type, $msg) = @_;
1695 if (report("ERROR", $type, $msg)) {
1703 my ($type, $msg) = @_;
1705 if (report("WARNING", $type, $msg)) {
1713 my ($type, $msg) = @_;
1715 if ($check && report("CHECK", $type, $msg)) {
1723 sub check_absolute_file {
1724 my ($absolute, $herecurr) = @_;
1725 my $file = $absolute;
1727 ##print "absolute<$absolute>\n";
1729 # See if any suffix of this path is a path within the tree.
1730 while ($file =~ s@^[^/]*/@@) {
1731 if (-f "$root/$file") {
1732 ##print "file<$file>\n";
1740 # It is, so see if the prefix is acceptable.
1741 my $prefix = $absolute;
1742 substr($prefix, -length($file)) = '';
1744 ##print "prefix<$prefix>\n";
1745 if ($prefix ne ".../") {
1746 WARN("USE_RELATIVE_PATH",
1747 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1754 $string =~ s/^\s+|\s+$//g;
1762 $string =~ s/^\s+//;
1770 $string =~ s/\s+$//;
1775 sub string_find_replace {
1776 my ($string, $find, $replace) = @_;
1778 $string =~ s/$find/$replace/g;
1786 my $source_indent = 8;
1787 my $max_spaces_before_tab = $source_indent - 1;
1788 my $spaces_to_tab = " " x $source_indent;
1790 #convert leading spaces to tabs
1791 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1792 #Remove spaces before a tab
1793 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1798 sub pos_last_openparen {
1803 my $opens = $line =~ tr/\(/\(/;
1804 my $closes = $line =~ tr/\)/\)/;
1806 my $last_openparen = 0;
1808 if (($opens == 0) || ($closes >= $opens)) {
1812 my $len = length($line);
1814 for ($pos = 0; $pos < $len; $pos++) {
1815 my $string = substr($line, $pos);
1816 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1817 $pos += length($1) - 1;
1818 } elsif (substr($line, $pos, 1) eq '(') {
1819 $last_openparen = $pos;
1820 } elsif (index($string, '(') == -1) {
1825 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1829 my $filename = shift;
1835 my $stashrawline="";
1846 my $in_header_lines = $file ? 0 : 1;
1847 my $in_commit_log = 0; #Scanning lines before patch
1848 my $reported_maintainer_file = 0;
1849 my $non_utf8_charset = 0;
1851 my $last_blank_line = 0;
1852 my $last_coalesced_string_linenr = -1;
1860 # Trace the real file/line as we go.
1866 my $comment_edge = 0;
1870 my $prev_values = 'E';
1873 my %suppress_ifbraces;
1874 my %suppress_whiletrailers;
1875 my %suppress_export;
1876 my $suppress_statement = 0;
1878 my %signatures = ();
1880 # Pre-scan the patch sanitizing the lines.
1881 # Pre-scan the patch looking for any __setup documentation.
1883 my @setup_docs = ();
1886 my $camelcase_file_seeded = 0;
1888 sanitise_line_reset();
1890 foreach my $rawline (@rawlines) {
1894 push(@fixed, $rawline) if ($fix);
1896 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1898 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1903 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1912 # Guestimate if this is a continuing comment. Run
1913 # the context looking for a comment "edge". If this
1914 # edge is a close comment then we must be in a comment
1918 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1919 next if (defined $rawlines[$ln - 1] &&
1920 $rawlines[$ln - 1] =~ /^-/);
1922 #print "RAW<$rawlines[$ln - 1]>\n";
1923 last if (!defined $rawlines[$ln - 1]);
1924 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1925 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1930 if (defined $edge && $edge eq '*/') {
1934 # Guestimate if this is a continuing comment. If this
1935 # is the start of a diff block and this line starts
1936 # ' *' then it is very likely a comment.
1937 if (!defined $edge &&
1938 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1943 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1944 sanitise_line_reset($in_comment);
1946 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1947 # Standardise the strings and chars within the input to
1948 # simplify matching -- only bother with positive lines.
1949 $line = sanitise_line($rawline);
1951 push(@lines, $line);
1954 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1959 #print "==>$rawline\n";
1960 #print "-->$line\n";
1962 if ($setup_docs && $line =~ /^\+/) {
1963 push(@setup_docs, $line);
1972 foreach my $line (@lines) {
1975 my $sline = $line; #copy of $line
1976 $sline =~ s/$;/ /g; #with comments as spaces
1978 my $rawline = $rawlines[$linenr - 1];
1980 #extract the line range in the file after the patch is applied
1981 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1983 $first_line = $linenr + 1;
1993 %suppress_ifbraces = ();
1994 %suppress_whiletrailers = ();
1995 %suppress_export = ();
1996 $suppress_statement = 0;
1999 # track the line number as we move through the hunk, note that
2000 # new versions of GNU diff omit the leading space on completely
2001 # blank context lines so we need to count that too.
2002 } elsif ($line =~ /^( |\+|$)/) {
2004 $realcnt-- if ($realcnt != 0);
2006 # Measure the line length and indent.
2007 ($length, $indent) = line_stats($rawline);
2009 # Track the previous line.
2010 ($prevline, $stashline) = ($stashline, $line);
2011 ($previndent, $stashindent) = ($stashindent, $indent);
2012 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2014 #warn "line<$line>\n";
2016 } elsif ($realcnt == 1) {
2020 my $hunk_line = ($realcnt != 0);
2022 #make up the handle for any error we report on this line
2023 $prefix = "$filename:$realline: " if ($emacs && $file);
2024 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2026 $here = "#$linenr: " if (!$file);
2027 $here = "#$realline: " if ($file);
2030 # extract the filename as it passes
2031 if ($line =~ /^diff --git.*?(\S+)$/) {
2033 $realfile =~ s@^([^/]*)/@@ if (!$file);
2036 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2038 $realfile =~ s@^([^/]*)/@@ if (!$file);
2042 if (!$file && $tree && $p1_prefix ne '' &&
2043 -e "$root/$p1_prefix") {
2044 WARN("PATCH_PREFIX",
2045 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2048 if ($realfile =~ m@^include/asm/@) {
2049 ERROR("MODIFIED_INCLUDE_ASM",
2050 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2056 if ($realfile =~ m@^(drivers/net/|net/)@) {
2059 $check = $check_orig;
2064 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2066 my $hereline = "$here\n$rawline\n";
2067 my $herecurr = "$here\n$rawline\n";
2068 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2070 $cnt_lines++ if ($realcnt != 0);
2072 # Check for incorrect file permissions
2073 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2074 my $permhere = $here . "FILE: $realfile\n";
2075 if ($realfile !~ m@scripts/@ &&
2076 $realfile !~ /\.(py|pl|awk|sh)$/) {
2077 ERROR("EXECUTE_PERMISSIONS",
2078 "do not set execute permissions for source files\n" . $permhere);
2082 # Check the patch for a signoff:
2083 if ($line =~ /^\s*signed-off-by:/i) {
2088 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2089 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2090 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2091 $reported_maintainer_file = 1;
2094 # Check signature styles
2095 if (!$in_header_lines &&
2096 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2097 my $space_before = $1;
2099 my $space_after = $3;
2101 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2103 if ($sign_off !~ /$signature_tags/) {
2104 WARN("BAD_SIGN_OFF",
2105 "Non-standard signature: $sign_off\n" . $herecurr);
2107 if (defined $space_before && $space_before ne "") {
2108 if (WARN("BAD_SIGN_OFF",
2109 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2111 $fixed[$fixlinenr] =
2112 "$ucfirst_sign_off $email";
2115 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2116 if (WARN("BAD_SIGN_OFF",
2117 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2119 $fixed[$fixlinenr] =
2120 "$ucfirst_sign_off $email";
2124 if (!defined $space_after || $space_after ne " ") {
2125 if (WARN("BAD_SIGN_OFF",
2126 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2128 $fixed[$fixlinenr] =
2129 "$ucfirst_sign_off $email";
2133 my ($email_name, $email_address, $comment) = parse_email($email);
2134 my $suggested_email = format_email(($email_name, $email_address));
2135 if ($suggested_email eq "") {
2136 ERROR("BAD_SIGN_OFF",
2137 "Unrecognized email address: '$email'\n" . $herecurr);
2139 my $dequoted = $suggested_email;
2140 $dequoted =~ s/^"//;
2141 $dequoted =~ s/" </ </;
2142 # Don't force email to have quotes
2143 # Allow just an angle bracketed address
2144 if ("$dequoted$comment" ne $email &&
2145 "<$email_address>$comment" ne $email &&
2146 "$suggested_email$comment" ne $email) {
2147 WARN("BAD_SIGN_OFF",
2148 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2152 # Check for duplicate signatures
2153 my $sig_nospace = $line;
2154 $sig_nospace =~ s/\s//g;
2155 $sig_nospace = lc($sig_nospace);
2156 if (defined $signatures{$sig_nospace}) {
2157 WARN("BAD_SIGN_OFF",
2158 "Duplicate signature\n" . $herecurr);
2160 $signatures{$sig_nospace} = 1;
2164 # Check for old stable address
2165 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2166 ERROR("STABLE_ADDRESS",
2167 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2170 # Check for unwanted Gerrit info
2171 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2172 ERROR("GERRIT_CHANGE_ID",
2173 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2176 # Check for improperly formed commit descriptions
2177 if ($in_commit_log &&
2178 $line =~ /\bcommit\s+[0-9a-f]{5,}/i &&
2179 !($line =~ /\b[Cc]ommit [0-9a-f]{12,40} \("/ ||
2180 ($line =~ /\b[Cc]ommit [0-9a-f]{12,40}\s*$/ &&
2181 defined $rawlines[$linenr] &&
2182 $rawlines[$linenr] =~ /^\s*\("/))) {
2183 $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i;
2185 my $orig_commit = lc($2);
2186 my $id = '01234567890ab';
2187 my $desc = 'commit description';
2188 ($id, $desc) = git_commit_info($orig_commit, $id, $desc);
2189 ERROR("GIT_COMMIT_ID",
2190 "Please use 12 or more chars for the git commit ID like: '${init_char}ommit $id (\"$desc\")'\n" . $herecurr);
2193 # Check for added, moved or deleted files
2194 if (!$reported_maintainer_file && !$in_commit_log &&
2195 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2196 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2197 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2198 (defined($1) || defined($2))))) {
2199 $reported_maintainer_file = 1;
2200 WARN("FILE_PATH_CHANGES",
2201 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2204 # Check for wrappage within a valid hunk of the file
2205 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2206 ERROR("CORRUPTED_PATCH",
2207 "patch seems to be corrupt (line wrapped?)\n" .
2208 $herecurr) if (!$emitted_corrupt++);
2211 # Check for absolute kernel paths.
2213 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2216 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2217 check_absolute_file($1, $herecurr)) {
2220 check_absolute_file($file, $herecurr);
2225 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2226 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2227 $rawline !~ m/^$UTF8*$/) {
2228 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2230 my $blank = copy_spacing($rawline);
2231 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2232 my $hereptr = "$hereline$ptr\n";
2235 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2238 # Check if it's the start of a commit log
2239 # (not a header line and we haven't seen the patch filename)
2240 if ($in_header_lines && $realfile =~ /^$/ &&
2241 !($rawline =~ /^\s+\S/ ||
2242 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2243 $in_header_lines = 0;
2247 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2248 # declined it, i.e defined some charset where it is missing.
2249 if ($in_header_lines &&
2250 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2252 $non_utf8_charset = 1;
2255 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2256 $rawline =~ /$NON_ASCII_UTF8/) {
2257 WARN("UTF8_BEFORE_PATCH",
2258 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2261 # Check for various typo / spelling mistakes
2262 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2263 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2265 my $typo_fix = $spelling_fix{lc($typo)};
2266 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2267 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2268 my $msg_type = \&WARN;
2269 $msg_type = \&CHK if ($file);
2270 if (&{$msg_type}("TYPO_SPELLING",
2271 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2273 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2278 # ignore non-hunk lines and lines being removed
2279 next if (!$hunk_line || $line =~ /^-/);
2281 #trailing whitespace
2282 if ($line =~ /^\+.*\015/) {
2283 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2284 if (ERROR("DOS_LINE_ENDINGS",
2285 "DOS line endings\n" . $herevet) &&
2287 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2289 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2290 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2291 if (ERROR("TRAILING_WHITESPACE",
2292 "trailing whitespace\n" . $herevet) &&
2294 $fixed[$fixlinenr] =~ s/\s+$//;
2300 # Check for FSF mailing addresses.
2301 if ($rawline =~ /\bwrite to the Free/i ||
2302 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2303 $rawline =~ /\b51\s+Franklin\s+St/i) {
2304 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2305 my $msg_type = \&ERROR;
2306 $msg_type = \&CHK if ($file);
2307 &{$msg_type}("FSF_MAILING_ADDRESS",
2308 "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)
2311 # check for Kconfig help text having a real description
2312 # Only applies when adding the entry originally, after that we do not have
2313 # sufficient context to determine whether it is indeed long enough.
2314 if ($realfile =~ /Kconfig/ &&
2315 $line =~ /^\+\s*config\s+/) {
2318 my $ln = $linenr + 1;
2322 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2323 $f = $lines[$ln - 1];
2324 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2325 $is_end = $lines[$ln - 1] =~ /^\+/;
2327 next if ($f =~ /^-/);
2328 last if (!$file && $f =~ /^\@\@/);
2330 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2332 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2339 next if ($f =~ /^$/);
2340 if ($f =~ /^\s*config\s/) {
2346 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2347 WARN("CONFIG_DESCRIPTION",
2348 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2350 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2353 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2354 if ($realfile =~ /Kconfig/ &&
2355 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2356 WARN("CONFIG_EXPERIMENTAL",
2357 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2360 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2361 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2364 'EXTRA_AFLAGS' => 'asflags-y',
2365 'EXTRA_CFLAGS' => 'ccflags-y',
2366 'EXTRA_CPPFLAGS' => 'cppflags-y',
2367 'EXTRA_LDFLAGS' => 'ldflags-y',
2370 WARN("DEPRECATED_VARIABLE",
2371 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2374 # check for DT compatible documentation
2375 if (defined $root &&
2376 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2377 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2379 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2381 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2382 my $vp_file = $dt_path . "vendor-prefixes.txt";
2384 foreach my $compat (@compats) {
2385 my $compat2 = $compat;
2386 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2387 my $compat3 = $compat;
2388 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2389 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2391 WARN("UNDOCUMENTED_DT_STRING",
2392 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2395 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2397 `grep -Eq "^$vendor\\b" $vp_file`;
2399 WARN("UNDOCUMENTED_DT_STRING",
2400 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2405 # check we are in a valid source file if not then ignore this hunk
2406 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2409 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2410 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2411 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2412 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2413 $length > $max_line_length)
2416 "line over $max_line_length characters\n" . $herecurr);
2419 # check for adding lines without a newline.
2420 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2421 WARN("MISSING_EOF_NEWLINE",
2422 "adding a line without newline at end of file\n" . $herecurr);
2425 # Blackfin: use hi/lo macros
2426 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2427 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2428 my $herevet = "$here\n" . cat_vet($line) . "\n";
2430 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2432 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2433 my $herevet = "$here\n" . cat_vet($line) . "\n";
2435 "use the HI() macro, not (... >> 16)\n" . $herevet);
2439 # check we are in a valid source file C or perl if not then ignore this hunk
2440 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2442 # at the beginning of a line any tabs must come first and anything
2443 # more than 8 must use tabs.
2444 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2445 $rawline =~ /^\+\s* \s*/) {
2446 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2448 if (ERROR("CODE_INDENT",
2449 "code indent should use tabs where possible\n" . $herevet) &&
2451 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2455 # check for space before tabs.
2456 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2457 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2458 if (WARN("SPACE_BEFORE_TAB",
2459 "please, no space before tabs\n" . $herevet) &&
2461 while ($fixed[$fixlinenr] =~
2462 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2463 while ($fixed[$fixlinenr] =~
2464 s/(^\+.*) +\t/$1\t/) {}
2468 # check for && or || at the start of a line
2469 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2470 CHK("LOGICAL_CONTINUATIONS",
2471 "Logical continuations should be on the previous line\n" . $hereprev);
2474 # check multi-line statement indentation matches previous line
2475 if ($^V && $^V ge 5.10.0 &&
2476 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2477 $prevline =~ /^\+(\t*)(.*)$/;
2481 my $pos = pos_last_openparen($rest);
2483 $line =~ /^(\+| )([ \t]*)/;
2486 my $goodtabindent = $oldindent .
2489 my $goodspaceindent = $oldindent . " " x $pos;
2491 if ($newindent ne $goodtabindent &&
2492 $newindent ne $goodspaceindent) {
2494 if (CHK("PARENTHESIS_ALIGNMENT",
2495 "Alignment should match open parenthesis\n" . $hereprev) &&
2496 $fix && $line =~ /^\+/) {
2497 $fixed[$fixlinenr] =~
2498 s/^\+[ \t]*/\+$goodtabindent/;
2504 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;\({\[\<\>])/ &&
2505 (!defined($1) || $1 !~ /sizeof\s*/)) {
2507 "No space is necessary after a cast\n" . $herecurr) &&
2509 $fixed[$fixlinenr] =~
2510 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2514 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2515 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2516 $rawline =~ /^\+[ \t]*\*/ &&
2518 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2519 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2522 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2523 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2524 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2525 $rawline =~ /^\+/ && #line is new
2526 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2527 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2528 "networking block comments start with * on subsequent lines\n" . $hereprev);
2531 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2532 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2533 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2534 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2535 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2536 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2537 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2540 # check for missing blank lines after struct/union declarations
2541 # with exceptions for various attributes and macros
2542 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2544 !($line =~ /^\+\s*$/ ||
2545 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2546 $line =~ /^\+\s*MODULE_/i ||
2547 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2548 $line =~ /^\+[a-z_]*init/ ||
2549 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2550 $line =~ /^\+\s*DECLARE/ ||
2551 $line =~ /^\+\s*__setup/)) {
2552 if (CHK("LINE_SPACING",
2553 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2555 fix_insert_line($fixlinenr, "\+");
2559 # check for multiple consecutive blank lines
2560 if ($prevline =~ /^[\+ ]\s*$/ &&
2561 $line =~ /^\+\s*$/ &&
2562 $last_blank_line != ($linenr - 1)) {
2563 if (CHK("LINE_SPACING",
2564 "Please don't use multiple blank lines\n" . $hereprev) &&
2566 fix_delete_line($fixlinenr, $rawline);
2569 $last_blank_line = $linenr;
2572 # check for missing blank lines after declarations
2573 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2574 # actual declarations
2575 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2576 # function pointer declarations
2577 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2578 # foo bar; where foo is some local typedef or #define
2579 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2580 # known declaration macros
2581 $prevline =~ /^\+\s+$declaration_macros/) &&
2582 # for "else if" which can look like "$Ident $Ident"
2583 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2584 # other possible extensions of declaration lines
2585 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2586 # not starting a section or a macro "\" extended line
2587 $prevline =~ /(?:\{\s*|\\)$/) &&
2588 # looks like a declaration
2589 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2590 # function pointer declarations
2591 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2592 # foo bar; where foo is some local typedef or #define
2593 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2594 # known declaration macros
2595 $sline =~ /^\+\s+$declaration_macros/ ||
2596 # start of struct or union or enum
2597 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2598 # start or end of block or continuation of declaration
2599 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2600 # bitfield continuation
2601 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2602 # other possible extensions of declaration lines
2603 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2604 # indentation of previous and current line are the same
2605 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2606 if (WARN("LINE_SPACING",
2607 "Missing a blank line after declarations\n" . $hereprev) &&
2609 fix_insert_line($fixlinenr, "\+");
2613 # check for spaces at the beginning of a line.
2615 # 1) within comments
2616 # 2) indented preprocessor commands
2618 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2619 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2620 if (WARN("LEADING_SPACE",
2621 "please, no spaces at the start of a line\n" . $herevet) &&
2623 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2627 # check we are in a valid C source file if not then ignore this hunk
2628 next if ($realfile !~ /\.(h|c)$/);
2630 # check indentation of any line with a bare else
2631 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2632 # if the previous line is a break or return and is indented 1 tab more...
2633 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2634 my $tabs = length($1) + 1;
2635 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2636 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2637 defined $lines[$linenr] &&
2638 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2639 WARN("UNNECESSARY_ELSE",
2640 "else is not generally useful after a break or return\n" . $hereprev);
2644 # check indentation of a line with a break;
2645 # if the previous line is a goto or return and is indented the same # of tabs
2646 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2648 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2649 WARN("UNNECESSARY_BREAK",
2650 "break is not useful after a goto or return\n" . $hereprev);
2654 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2655 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2656 WARN("CONFIG_EXPERIMENTAL",
2657 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2660 # check for RCS/CVS revision markers
2661 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2663 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2666 # Blackfin: don't use __builtin_bfin_[cs]sync
2667 if ($line =~ /__builtin_bfin_csync/) {
2668 my $herevet = "$here\n" . cat_vet($line) . "\n";
2670 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2672 if ($line =~ /__builtin_bfin_ssync/) {
2673 my $herevet = "$here\n" . cat_vet($line) . "\n";
2675 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2678 # check for old HOTPLUG __dev<foo> section markings
2679 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2680 WARN("HOTPLUG_SECTION",
2681 "Using $1 is unnecessary\n" . $herecurr);
2684 # Check for potential 'bare' types
2685 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2687 #print "LINE<$line>\n";
2688 if ($linenr >= $suppress_statement &&
2689 $realcnt && $sline =~ /.\s*\S/) {
2690 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2691 ctx_statement_block($linenr, $realcnt, 0);
2692 $stat =~ s/\n./\n /g;
2693 $cond =~ s/\n./\n /g;
2695 #print "linenr<$linenr> <$stat>\n";
2696 # If this statement has no statement boundaries within
2697 # it there is no point in retrying a statement scan
2698 # until we hit end of it.
2699 my $frag = $stat; $frag =~ s/;+\s*$//;
2700 if ($frag !~ /(?:{|;)/) {
2701 #print "skip<$line_nr_next>\n";
2702 $suppress_statement = $line_nr_next;
2705 # Find the real next line.
2706 $realline_next = $line_nr_next;
2707 if (defined $realline_next &&
2708 (!defined $lines[$realline_next - 1] ||
2709 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2716 # Ignore goto labels.
2717 if ($s =~ /$Ident:\*$/s) {
2719 # Ignore functions being called
2720 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2722 } elsif ($s =~ /^.\s*else\b/s) {
2724 # declarations always start with types
2725 } 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) {
2728 possible($type, "A:" . $s);
2730 # definitions in global scope can only start with types
2731 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2732 possible($1, "B:" . $s);
2735 # any (foo ... *) is a pointer cast, and foo is a type
2736 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2737 possible($1, "C:" . $s);
2740 # Check for any sort of function declaration.
2741 # int foo(something bar, other baz);
2742 # void (*store_gdt)(x86_descr_ptr *);
2743 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2744 my ($name_len) = length($1);
2747 substr($ctx, 0, $name_len + 1, '');
2748 $ctx =~ s/\)[^\)]*$//;
2750 for my $arg (split(/\s*,\s*/, $ctx)) {
2751 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2753 possible($1, "D:" . $s);
2761 # Checks which may be anchored in the context.
2764 # Check for switch () and associated case and default
2765 # statements should be at the same indent.
2766 if ($line=~/\bswitch\s*\(.*\)/) {
2769 my @ctx = ctx_block_outer($linenr, $realcnt);
2771 for my $ctx (@ctx) {
2772 my ($clen, $cindent) = line_stats($ctx);
2773 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2774 $indent != $cindent) {
2775 $err .= "$sep$ctx\n";
2782 ERROR("SWITCH_CASE_INDENT_LEVEL",
2783 "switch and case should be at the same indent\n$hereline$err");
2787 # if/while/etc brace do not go on next line, unless defining a do while loop,
2788 # or if that brace on the next line is for something else
2789 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2790 my $pre_ctx = "$1$2";
2792 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2794 if ($line =~ /^\+\t{6,}/) {
2795 WARN("DEEP_INDENTATION",
2796 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2799 my $ctx_cnt = $realcnt - $#ctx - 1;
2800 my $ctx = join("\n", @ctx);
2802 my $ctx_ln = $linenr;
2803 my $ctx_skip = $realcnt;
2805 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2806 defined $lines[$ctx_ln - 1] &&
2807 $lines[$ctx_ln - 1] =~ /^-/)) {
2808 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2809 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2813 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2814 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2816 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2818 "that open brace { should be on the previous line\n" .
2819 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2821 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2822 $ctx =~ /\)\s*\;\s*$/ &&
2823 defined $lines[$ctx_ln - 1])
2825 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2826 if ($nindent > $indent) {
2827 WARN("TRAILING_SEMICOLON",
2828 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2829 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2834 # Check relative indent for conditionals and blocks.
2835 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2836 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2837 ctx_statement_block($linenr, $realcnt, 0)
2838 if (!defined $stat);
2839 my ($s, $c) = ($stat, $cond);
2841 substr($s, 0, length($c), '');
2843 # Make sure we remove the line prefixes as we have
2844 # none on the first line, and are going to readd them
2848 # Find out how long the conditional actually is.
2849 my @newlines = ($c =~ /\n/gs);
2850 my $cond_lines = 1 + $#newlines;
2852 # We want to check the first line inside the block
2853 # starting at the end of the conditional, so remove:
2854 # 1) any blank line termination
2855 # 2) any opening brace { on end of the line
2857 my $continuation = 0;
2859 $s =~ s/^.*\bdo\b//;
2861 if ($s =~ s/^\s*\\//) {
2864 if ($s =~ s/^\s*?\n//) {
2869 # Also ignore a loop construct at the end of a
2870 # preprocessor statement.
2871 if (($prevline =~ /^.\s*#\s*define\s/ ||
2872 $prevline =~ /\\\s*$/) && $continuation == 0) {
2878 while ($cond_ptr != $cond_lines) {
2879 $cond_ptr = $cond_lines;
2881 # If we see an #else/#elif then the code
2883 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2888 # 1) blank lines, they should be at 0,
2889 # 2) preprocessor lines, and
2891 if ($continuation ||
2893 $s =~ /^\s*#\s*?/ ||
2894 $s =~ /^\s*$Ident\s*:/) {
2895 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2896 if ($s =~ s/^.*?\n//) {
2902 my (undef, $sindent) = line_stats("+" . $s);
2903 my $stat_real = raw_line($linenr, $cond_lines);
2905 # Check if either of these lines are modified, else
2906 # this is not this patch's fault.
2907 if (!defined($stat_real) ||
2908 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2911 if (defined($stat_real) && $cond_lines > 1) {
2912 $stat_real = "[...]\n$stat_real";
2915 #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";
2917 if ($check && (($sindent % 8) != 0 ||
2918 ($sindent <= $indent && $s ne ''))) {
2919 WARN("SUSPECT_CODE_INDENT",
2920 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2924 # Track the 'values' across context and added lines.
2925 my $opline = $line; $opline =~ s/^./ /;
2926 my ($curr_values, $curr_vars) =
2927 annotate_values($opline . "\n", $prev_values);
2928 $curr_values = $prev_values . $curr_values;
2930 my $outline = $opline; $outline =~ s/\t/ /g;
2931 print "$linenr > .$outline\n";
2932 print "$linenr > $curr_values\n";
2933 print "$linenr > $curr_vars\n";
2935 $prev_values = substr($curr_values, -1);
2937 #ignore lines not being added
2938 next if ($line =~ /^[^\+]/);
2940 # TEST: allow direct testing of the type matcher.
2942 if ($line =~ /^.\s*$Declare\s*$/) {
2944 "TEST: is type\n" . $herecurr);
2945 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2946 ERROR("TEST_NOT_TYPE",
2947 "TEST: is not type ($1 is)\n". $herecurr);
2951 # TEST: allow direct testing of the attribute matcher.
2953 if ($line =~ /^.\s*$Modifier\s*$/) {
2955 "TEST: is attr\n" . $herecurr);
2956 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2957 ERROR("TEST_NOT_ATTR",
2958 "TEST: is not attr ($1 is)\n". $herecurr);
2963 # check for initialisation to aggregates open brace on the next line
2964 if ($line =~ /^.\s*{/ &&
2965 $prevline =~ /(?:^|[^=])=\s*$/) {
2966 if (ERROR("OPEN_BRACE",
2967 "that open brace { should be on the previous line\n" . $hereprev) &&
2968 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
2969 fix_delete_line($fixlinenr - 1, $prevrawline);
2970 fix_delete_line($fixlinenr, $rawline);
2971 my $fixedline = $prevrawline;
2972 $fixedline =~ s/\s*=\s*$/ = {/;
2973 fix_insert_line($fixlinenr, $fixedline);
2975 $fixedline =~ s/^(.\s*){\s*/$1/;
2976 fix_insert_line($fixlinenr, $fixedline);
2981 # Checks which are anchored on the added line.
2984 # check for malformed paths in #include statements (uses RAW line)
2985 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2987 if ($path =~ m{//}) {
2988 ERROR("MALFORMED_INCLUDE",
2989 "malformed #include filename\n" . $herecurr);
2991 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2992 ERROR("UAPI_INCLUDE",
2993 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2997 # no C99 // comments
2998 if ($line =~ m{//}) {
2999 if (ERROR("C99_COMMENTS",
3000 "do not use C99 // comments\n" . $herecurr) &&
3002 my $line = $fixed[$fixlinenr];
3003 if ($line =~ /\/\/(.*)$/) {
3004 my $comment = trim($1);
3005 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3009 # Remove C99 comments.
3011 $opline =~ s@//.*@@;
3013 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3014 # the whole statement.
3015 #print "APW <$lines[$realline_next - 1]>\n";
3016 if (defined $realline_next &&
3017 exists $lines[$realline_next - 1] &&
3018 !defined $suppress_export{$realline_next} &&
3019 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3020 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3021 # Handle definitions which produce identifiers with
3024 # EXPORT_SYMBOL(something_foo);
3026 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3027 $name =~ /^${Ident}_$2/) {
3028 #print "FOO C name<$name>\n";
3029 $suppress_export{$realline_next} = 1;
3031 } elsif ($stat !~ /(?:
3033 ^.DEFINE_$Ident\(\Q$name\E\)|
3034 ^.DECLARE_$Ident\(\Q$name\E\)|
3035 ^.LIST_HEAD\(\Q$name\E\)|
3036 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3037 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3039 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3040 $suppress_export{$realline_next} = 2;
3042 $suppress_export{$realline_next} = 1;
3045 if (!defined $suppress_export{$linenr} &&
3046 $prevline =~ /^.\s*$/ &&
3047 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3048 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3049 #print "FOO B <$lines[$linenr - 1]>\n";
3050 $suppress_export{$linenr} = 2;
3052 if (defined $suppress_export{$linenr} &&
3053 $suppress_export{$linenr} == 2) {
3054 WARN("EXPORT_SYMBOL",
3055 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3058 # check for global initialisers.
3059 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3060 if (ERROR("GLOBAL_INITIALISERS",
3061 "do not initialise globals to 0 or NULL\n" .
3064 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3067 # check for static initialisers.
3068 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3069 if (ERROR("INITIALISED_STATIC",
3070 "do not initialise statics to 0 or NULL\n" .
3073 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3077 # check for misordered declarations of char/short/int/long with signed/unsigned
3078 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3080 WARN("MISORDERED_TYPE",
3081 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3084 # check for static const char * arrays.
3085 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3086 WARN("STATIC_CONST_CHAR_ARRAY",
3087 "static const char * array should probably be static const char * const\n" .
3091 # check for static char foo[] = "bar" declarations.
3092 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3093 WARN("STATIC_CONST_CHAR_ARRAY",
3094 "static char array declaration should probably be static const char\n" .
3098 # check for non-global char *foo[] = {"bar", ...} declarations.
3099 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3100 WARN("STATIC_CONST_CHAR_ARRAY",
3101 "char * array declaration might be better as static const\n" .
3105 # check for function declarations without arguments like "int foo()"
3106 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3107 if (ERROR("FUNCTION_WITHOUT_ARGS",
3108 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3110 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3114 # check for uses of DEFINE_PCI_DEVICE_TABLE
3115 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3116 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3117 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3119 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3123 # check for new typedefs, only function parameters and sparse annotations
3125 if ($line =~ /\btypedef\s/ &&
3126 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3127 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3128 $line !~ /\b$typeTypedefs\b/ &&
3129 $line !~ /\b__bitwise(?:__|)\b/) {
3130 WARN("NEW_TYPEDEFS",
3131 "do not add new typedefs\n" . $herecurr);
3134 # * goes on variable not on type
3136 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3138 my ($ident, $from, $to) = ($1, $2, $2);
3140 # Should start with a space.
3141 $to =~ s/^(\S)/ $1/;
3142 # Should not end with a space.
3144 # '*'s should not have spaces between.
3145 while ($to =~ s/\*\s+\*/\*\*/) {
3148 ## print "1: from<$from> to<$to> ident<$ident>\n";
3150 if (ERROR("POINTER_LOCATION",
3151 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3153 my $sub_from = $ident;
3154 my $sub_to = $ident;
3155 $sub_to =~ s/\Q$from\E/$to/;
3156 $fixed[$fixlinenr] =~
3157 s@\Q$sub_from\E@$sub_to@;
3161 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3163 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3165 # Should start with a space.
3166 $to =~ s/^(\S)/ $1/;
3167 # Should not end with a space.
3169 # '*'s should not have spaces between.
3170 while ($to =~ s/\*\s+\*/\*\*/) {
3172 # Modifiers should have spaces.
3173 $to =~ s/(\b$Modifier$)/$1 /;
3175 ## print "2: from<$from> to<$to> ident<$ident>\n";
3176 if ($from ne $to && $ident !~ /^$Modifier$/) {
3177 if (ERROR("POINTER_LOCATION",
3178 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3181 my $sub_from = $match;
3182 my $sub_to = $match;
3183 $sub_to =~ s/\Q$from\E/$to/;
3184 $fixed[$fixlinenr] =~
3185 s@\Q$sub_from\E@$sub_to@;
3190 # # no BUG() or BUG_ON()
3191 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3192 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3193 # print "$herecurr";
3197 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3198 WARN("LINUX_VERSION_CODE",
3199 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3202 # check for uses of printk_ratelimit
3203 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3204 WARN("PRINTK_RATELIMITED",
3205 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3208 # printk should use KERN_* levels. Note that follow on printk's on the
3209 # same line do not need a level, so we use the current block context
3210 # to try and find and validate the current printk. In summary the current
3211 # printk includes all preceding printk's which have no newline on the end.
3212 # we assume the first bad printk is the one to report.
3213 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3215 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3216 #print "CHECK<$lines[$ln - 1]\n";
3217 # we have a preceding printk if it ends
3218 # with "\n" ignore it, else it is to blame
3219 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3220 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3227 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3228 "printk() should include KERN_ facility level\n" . $herecurr);
3232 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3234 my $level = lc($orig);
3235 $level = "warn" if ($level eq "warning");
3236 my $level2 = $level;
3237 $level2 = "dbg" if ($level eq "debug");
3238 WARN("PREFER_PR_LEVEL",
3239 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3242 if ($line =~ /\bpr_warning\s*\(/) {
3243 if (WARN("PREFER_PR_LEVEL",
3244 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3246 $fixed[$fixlinenr] =~
3247 s/\bpr_warning\b/pr_warn/;
3251 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3253 my $level = lc($orig);
3254 $level = "warn" if ($level eq "warning");
3255 $level = "dbg" if ($level eq "debug");
3256 WARN("PREFER_DEV_LEVEL",
3257 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3260 # function brace can't be on same line, except for #defines of do while,
3261 # or if closed on same line
3262 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3263 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3264 if (ERROR("OPEN_BRACE",
3265 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3267 fix_delete_line($fixlinenr, $rawline);
3268 my $fixed_line = $rawline;
3269 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3272 fix_insert_line($fixlinenr, ltrim($line1));
3273 fix_insert_line($fixlinenr, "\+{");
3274 if ($line2 !~ /^\s*$/) {
3275 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3280 # open braces for enum, union and struct go on the same line.
3281 if ($line =~ /^.\s*{/ &&
3282 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3283 if (ERROR("OPEN_BRACE",
3284 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3285 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3286 fix_delete_line($fixlinenr - 1, $prevrawline);
3287 fix_delete_line($fixlinenr, $rawline);
3288 my $fixedline = rtrim($prevrawline) . " {";
3289 fix_insert_line($fixlinenr, $fixedline);
3290 $fixedline = $rawline;
3291 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3292 if ($fixedline !~ /^\+\s*$/) {
3293 fix_insert_line($fixlinenr, $fixedline);
3298 # missing space after union, struct or enum definition
3299 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3301 "missing space after $1 definition\n" . $herecurr) &&
3303 $fixed[$fixlinenr] =~
3304 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3308 # Function pointer declarations
3309 # check spacing between type, funcptr, and args
3310 # canonical declaration is "type (*funcptr)(args...)"
3311 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3313 my $pre_pointer_space = $2;
3314 my $post_pointer_space = $3;
3316 my $post_funcname_space = $5;
3317 my $pre_args_space = $6;
3319 # the $Declare variable will capture all spaces after the type
3320 # so check it for a missing trailing missing space but pointer return types
3321 # don't need a space so don't warn for those.
3322 my $post_declare_space = "";
3323 if ($declare =~ /(\s+)$/) {
3324 $post_declare_space = $1;
3325 $declare = rtrim($declare);
3327 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3329 "missing space after return type\n" . $herecurr);
3330 $post_declare_space = " ";
3333 # unnecessary space "type (*funcptr)(args...)"
3334 # This test is not currently implemented because these declarations are
3336 # int foo(int bar, ...)
3337 # and this is form shouldn't/doesn't generate a checkpatch warning.
3339 # elsif ($declare =~ /\s{2,}$/) {
3341 # "Multiple spaces after return type\n" . $herecurr);
3344 # unnecessary space "type ( *funcptr)(args...)"
3345 if (defined $pre_pointer_space &&
3346 $pre_pointer_space =~ /^\s/) {
3348 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3351 # unnecessary space "type (* funcptr)(args...)"
3352 if (defined $post_pointer_space &&
3353 $post_pointer_space =~ /^\s/) {
3355 "Unnecessary space before function pointer name\n" . $herecurr);
3358 # unnecessary space "type (*funcptr )(args...)"
3359 if (defined $post_funcname_space &&
3360 $post_funcname_space =~ /^\s/) {
3362 "Unnecessary space after function pointer name\n" . $herecurr);
3365 # unnecessary space "type (*funcptr) (args...)"
3366 if (defined $pre_args_space &&
3367 $pre_args_space =~ /^\s/) {
3369 "Unnecessary space before function pointer arguments\n" . $herecurr);
3372 if (show_type("SPACING") && $fix) {
3373 $fixed[$fixlinenr] =~
3374 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3378 # check for spacing round square brackets; allowed:
3379 # 1. with a type on the left -- int [] a;
3380 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3381 # 3. inside a curly brace -- = { [0...10] = 5 }
3382 while ($line =~ /(.*?\s)\[/g) {
3383 my ($where, $prefix) = ($-[1], $1);
3384 if ($prefix !~ /$Type\s+$/ &&
3385 ($where != 0 || $prefix !~ /^.\s+$/) &&
3386 $prefix !~ /[{,]\s+$/) {
3387 if (ERROR("BRACKET_SPACE",
3388 "space prohibited before open square bracket '['\n" . $herecurr) &&
3390 $fixed[$fixlinenr] =~
3391 s/^(\+.*?)\s+\[/$1\[/;
3396 # check for spaces between functions and their parentheses.
3397 while ($line =~ /($Ident)\s+\(/g) {
3399 my $ctx_before = substr($line, 0, $-[1]);
3400 my $ctx = "$ctx_before$name";
3402 # Ignore those directives where spaces _are_ permitted.
3404 if|for|while|switch|return|case|
3405 volatile|__volatile__|
3406 __attribute__|format|__extension__|
3409 # cpp #define statements have non-optional spaces, ie
3410 # if there is a space between the name and the open
3411 # parenthesis it is simply not a parameter group.
3412 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3414 # cpp #elif statement condition may start with a (
3415 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3417 # If this whole things ends with a type its most
3418 # likely a typedef for a function.
3419 } elsif ($ctx =~ /$Type$/) {
3423 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3425 $fixed[$fixlinenr] =~
3426 s/\b$name\s+\(/$name\(/;
3431 # Check operator spacing.
3432 if (!($line=~/\#\s*include/)) {
3433 my $fixed_line = "";
3437 <<=|>>=|<=|>=|==|!=|
3438 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3439 =>|->|<<|>>|<|>|=|!|~|
3440 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3443 my @elements = split(/($ops|;)/, $opline);
3445 ## print("element count: <" . $#elements . ">\n");
3446 ## foreach my $el (@elements) {
3447 ## print("el: <$el>\n");
3450 my @fix_elements = ();
3453 foreach my $el (@elements) {
3454 push(@fix_elements, substr($rawline, $off, length($el)));
3455 $off += length($el);
3460 my $blank = copy_spacing($opline);
3461 my $last_after = -1;
3463 for (my $n = 0; $n < $#elements; $n += 2) {
3465 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3467 ## print("n: <$n> good: <$good>\n");
3469 $off += length($elements[$n]);
3471 # Pick up the preceding and succeeding characters.
3472 my $ca = substr($opline, 0, $off);
3474 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3475 $cc = substr($opline, $off + length($elements[$n + 1]));
3477 my $cb = "$ca$;$cc";
3480 $a = 'V' if ($elements[$n] ne '');
3481 $a = 'W' if ($elements[$n] =~ /\s$/);
3482 $a = 'C' if ($elements[$n] =~ /$;$/);
3483 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3484 $a = 'O' if ($elements[$n] eq '');
3485 $a = 'E' if ($ca =~ /^\s*$/);
3487 my $op = $elements[$n + 1];
3490 if (defined $elements[$n + 2]) {
3491 $c = 'V' if ($elements[$n + 2] ne '');
3492 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3493 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3494 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3495 $c = 'O' if ($elements[$n + 2] eq '');
3496 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3501 my $ctx = "${a}x${c}";
3503 my $at = "(ctx:$ctx)";
3505 my $ptr = substr($blank, 0, $off) . "^";
3506 my $hereptr = "$hereline$ptr\n";
3508 # Pull out the value of this operator.
3509 my $op_type = substr($curr_values, $off + 1, 1);
3511 # Get the full operator variant.
3512 my $opv = $op . substr($curr_vars, $off, 1);
3514 # Ignore operators passed as parameters.
3515 if ($op_type ne 'V' &&
3516 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3519 # } elsif ($op =~ /^$;+$/) {
3521 # ; should have either the end of line or a space or \ after it
3522 } elsif ($op eq ';') {
3523 if ($ctx !~ /.x[WEBC]/ &&
3524 $cc !~ /^\\/ && $cc !~ /^;/) {
3525 if (ERROR("SPACING",
3526 "space required after that '$op' $at\n" . $hereptr)) {
3527 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3533 } elsif ($op eq '//') {
3535 # : when part of a bitfield
3536 } elsif ($opv eq ':B') {
3537 # skip the bitfield test for now
3541 } elsif ($op eq '->') {
3542 if ($ctx =~ /Wx.|.xW/) {
3543 if (ERROR("SPACING",
3544 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3545 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3546 if (defined $fix_elements[$n + 2]) {
3547 $fix_elements[$n + 2] =~ s/^\s+//;
3553 # , must not have a space before and must have a space on the right.
3554 } elsif ($op eq ',') {
3555 my $rtrim_before = 0;
3556 my $space_after = 0;
3557 if ($ctx =~ /Wx./) {
3558 if (ERROR("SPACING",
3559 "space prohibited before that '$op' $at\n" . $hereptr)) {
3564 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3565 if (ERROR("SPACING",
3566 "space required after that '$op' $at\n" . $hereptr)) {
3572 if ($rtrim_before || $space_after) {
3573 if ($rtrim_before) {
3574 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3576 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3583 # '*' as part of a type definition -- reported already.
3584 } elsif ($opv eq '*_') {
3585 #warn "'*' is part of type\n";
3587 # unary operators should have a space before and
3588 # none after. May be left adjacent to another
3589 # unary operator, or a cast
3590 } elsif ($op eq '!' || $op eq '~' ||
3591 $opv eq '*U' || $opv eq '-U' ||
3592 $opv eq '&U' || $opv eq '&&U') {
3593 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3594 if (ERROR("SPACING",
3595 "space required before that '$op' $at\n" . $hereptr)) {
3596 if ($n != $last_after + 2) {
3597 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3602 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3603 # A unary '*' may be const
3605 } elsif ($ctx =~ /.xW/) {
3606 if (ERROR("SPACING",
3607 "space prohibited after that '$op' $at\n" . $hereptr)) {
3608 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3609 if (defined $fix_elements[$n + 2]) {
3610 $fix_elements[$n + 2] =~ s/^\s+//;
3616 # unary ++ and unary -- are allowed no space on one side.
3617 } elsif ($op eq '++' or $op eq '--') {
3618 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3619 if (ERROR("SPACING",
3620 "space required one side of that '$op' $at\n" . $hereptr)) {
3621 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3625 if ($ctx =~ /Wx[BE]/ ||
3626 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3627 if (ERROR("SPACING",
3628 "space prohibited before that '$op' $at\n" . $hereptr)) {
3629 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3633 if ($ctx =~ /ExW/) {
3634 if (ERROR("SPACING",
3635 "space prohibited after that '$op' $at\n" . $hereptr)) {
3636 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3637 if (defined $fix_elements[$n + 2]) {
3638 $fix_elements[$n + 2] =~ s/^\s+//;
3644 # << and >> may either have or not have spaces both sides
3645 } elsif ($op eq '<<' or $op eq '>>' or
3646 $op eq '&' or $op eq '^' or $op eq '|' or
3647 $op eq '+' or $op eq '-' or
3648 $op eq '*' or $op eq '/' or
3651 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3652 if (ERROR("SPACING",
3653 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3654 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3655 if (defined $fix_elements[$n + 2]) {
3656 $fix_elements[$n + 2] =~ s/^\s+//;
3662 # A colon needs no spaces before when it is
3663 # terminating a case value or a label.
3664 } elsif ($opv eq ':C' || $opv eq ':L') {
3665 if ($ctx =~ /Wx./) {
3666 if (ERROR("SPACING",
3667 "space prohibited before that '$op' $at\n" . $hereptr)) {
3668 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3673 # All the others need spaces both sides.
3674 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3677 # Ignore email addresses <foo@bar>
3679 $cc =~ /^\S+\@\S+>/) ||
3681 $ca =~ /<\S+\@\S+$/))
3686 # messages are ERROR, but ?: are CHK
3688 my $msg_type = \&ERROR;
3689 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3691 if (&{$msg_type}("SPACING",
3692 "spaces required around that '$op' $at\n" . $hereptr)) {
3693 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3694 if (defined $fix_elements[$n + 2]) {
3695 $fix_elements[$n + 2] =~ s/^\s+//;
3701 $off += length($elements[$n + 1]);
3703 ## print("n: <$n> GOOD: <$good>\n");
3705 $fixed_line = $fixed_line . $good;
3708 if (($#elements % 2) == 0) {
3709 $fixed_line = $fixed_line . $fix_elements[$#elements];
3712 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3713 $fixed[$fixlinenr] = $fixed_line;
3719 # check for whitespace before a non-naked semicolon
3720 if ($line =~ /^\+.*\S\s+;\s*$/) {
3722 "space prohibited before semicolon\n" . $herecurr) &&
3724 1 while $fixed[$fixlinenr] =~
3725 s/^(\+.*\S)\s+;/$1;/;
3729 # check for multiple assignments
3730 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3731 CHK("MULTIPLE_ASSIGNMENTS",
3732 "multiple assignments should be avoided\n" . $herecurr);
3735 ## # check for multiple declarations, allowing for a function declaration
3737 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3738 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3740 ## # Remove any bracketed sections to ensure we do not
3741 ## # falsly report the parameters of functions.
3743 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3745 ## if ($ln =~ /,/) {
3746 ## WARN("MULTIPLE_DECLARATION",
3747 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3751 #need space before brace following if, while, etc
3752 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3754 if (ERROR("SPACING",
3755 "space required before the open brace '{'\n" . $herecurr) &&
3757 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3761 ## # check for blank lines before declarations
3762 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3763 ## $prevrawline =~ /^.\s*$/) {
3765 ## "No blank lines before declarations\n" . $hereprev);
3769 # closing brace should have a space following it when it has anything
3771 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3772 if (ERROR("SPACING",
3773 "space required after that close brace '}'\n" . $herecurr) &&
3775 $fixed[$fixlinenr] =~
3776 s/}((?!(?:,|;|\)))\S)/} $1/;
3780 # check spacing on square brackets
3781 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3782 if (ERROR("SPACING",
3783 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3785 $fixed[$fixlinenr] =~
3789 if ($line =~ /\s\]/) {
3790 if (ERROR("SPACING",
3791 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3793 $fixed[$fixlinenr] =~
3798 # check spacing on parentheses
3799 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3800 $line !~ /for\s*\(\s+;/) {
3801 if (ERROR("SPACING",
3802 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3804 $fixed[$fixlinenr] =~
3808 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3809 $line !~ /for\s*\(.*;\s+\)/ &&
3810 $line !~ /:\s+\)/) {
3811 if (ERROR("SPACING",
3812 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3814 $fixed[$fixlinenr] =~
3819 # check unnecessary parentheses around addressof/dereference single $Lvals
3820 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3822 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3824 if (CHK("UNNECESSARY_PARENTHESES",
3825 "Unnecessary parentheses around $var\n" . $herecurr) &&
3827 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3831 # check for unnecessary parentheses around function pointer uses
3832 # ie: (foo->bar)(); should be foo->bar();
3833 # but not "if (foo->bar) (" to avoid some false positives
3834 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3836 if (CHK("UNNECESSARY_PARENTHESES",
3837 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3839 my $var2 = deparenthesize($var);
3841 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3845 #goto labels aren't indented, allow a single space however
3846 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3847 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3848 if (WARN("INDENTED_LABEL",
3849 "labels should not be indented\n" . $herecurr) &&
3851 $fixed[$fixlinenr] =~
3856 # return is not a function
3857 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3859 if ($^V && $^V ge 5.10.0 &&
3860 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3862 $value = deparenthesize($value);
3863 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3864 ERROR("RETURN_PARENTHESES",
3865 "return is not a function, parentheses are not required\n" . $herecurr);
3867 } elsif ($spacing !~ /\s+/) {
3869 "space required before the open parenthesis '('\n" . $herecurr);
3873 # unnecessary return in a void function
3874 # at end-of-function, with the previous line a single leading tab, then return;
3875 # and the line before that not a goto label target like "out:"
3876 if ($sline =~ /^[ \+]}\s*$/ &&
3877 $prevline =~ /^\+\treturn\s*;\s*$/ &&
3879 $lines[$linenr - 3] =~ /^[ +]/ &&
3880 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3882 "void function return statements are not generally useful\n" . $hereprev);
3885 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3886 if ($^V && $^V ge 5.10.0 &&
3887 $line =~ /\bif\s*((?:\(\s*){2,})/) {
3888 my $openparens = $1;
3889 my $count = $openparens =~ tr@\(@\(@;
3891 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3892 my $comp = $4; #Not $1 because of $LvalOrFunc
3893 $msg = " - maybe == should be = ?" if ($comp eq "==");
3894 WARN("UNNECESSARY_PARENTHESES",
3895 "Unnecessary parentheses$msg\n" . $herecurr);
3899 # Return of what appears to be an errno should normally be -'ve
3900 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3902 if ($name ne 'EOF' && $name ne 'ERROR') {
3903 WARN("USE_NEGATIVE_ERRNO",
3904 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3908 # Need a space before open parenthesis after if, while etc
3909 if ($line =~ /\b(if|while|for|switch)\(/) {
3910 if (ERROR("SPACING",
3911 "space required before the open parenthesis '('\n" . $herecurr) &&
3913 $fixed[$fixlinenr] =~
3914 s/\b(if|while|for|switch)\(/$1 \(/;
3918 # Check for illegal assignment in if conditional -- and check for trailing
3919 # statements after the conditional.
3920 if ($line =~ /do\s*(?!{)/) {
3921 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3922 ctx_statement_block($linenr, $realcnt, 0)
3923 if (!defined $stat);
3924 my ($stat_next) = ctx_statement_block($line_nr_next,
3925 $remain_next, $off_next);
3926 $stat_next =~ s/\n./\n /g;
3927 ##print "stat<$stat> stat_next<$stat_next>\n";
3929 if ($stat_next =~ /^\s*while\b/) {
3930 # If the statement carries leading newlines,
3931 # then count those as offsets.
3933 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3935 statement_rawlines($whitespace) - 1;
3937 $suppress_whiletrailers{$line_nr_next +
3941 if (!defined $suppress_whiletrailers{$linenr} &&
3942 defined($stat) && defined($cond) &&
3943 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3944 my ($s, $c) = ($stat, $cond);
3946 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3947 ERROR("ASSIGN_IN_IF",
3948 "do not use assignment in if condition\n" . $herecurr);
3951 # Find out what is on the end of the line after the
3953 substr($s, 0, length($c), '');
3955 $s =~ s/$;//g; # Remove any comments
3956 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3957 $c !~ /}\s*while\s*/)
3959 # Find out how long the conditional actually is.
3960 my @newlines = ($c =~ /\n/gs);
3961 my $cond_lines = 1 + $#newlines;
3964 $stat_real = raw_line($linenr, $cond_lines)
3965 . "\n" if ($cond_lines);
3966 if (defined($stat_real) && $cond_lines > 1) {
3967 $stat_real = "[...]\n$stat_real";
3970 ERROR("TRAILING_STATEMENTS",
3971 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3975 # Check for bitwise tests written as boolean
3987 WARN("HEXADECIMAL_BOOLEAN_TEST",
3988 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3991 # if and else should not have general statements after it
3992 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3994 $s =~ s/$;//g; # Remove any comments
3995 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3996 ERROR("TRAILING_STATEMENTS",
3997 "trailing statements should be on next line\n" . $herecurr);
4000 # if should not continue a brace
4001 if ($line =~ /}\s*if\b/) {
4002 ERROR("TRAILING_STATEMENTS",
4003 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4006 # case and default should not have general statements after them
4007 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4009 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4013 ERROR("TRAILING_STATEMENTS",
4014 "trailing statements should be on next line\n" . $herecurr);
4017 # Check for }<nl>else {, these must be at the same
4018 # indent level to be relevant to each other.
4019 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4020 $previndent == $indent) {
4021 if (ERROR("ELSE_AFTER_BRACE",
4022 "else should follow close brace '}'\n" . $hereprev) &&
4023 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4024 fix_delete_line($fixlinenr - 1, $prevrawline);
4025 fix_delete_line($fixlinenr, $rawline);
4026 my $fixedline = $prevrawline;
4027 $fixedline =~ s/}\s*$//;
4028 if ($fixedline !~ /^\+\s*$/) {
4029 fix_insert_line($fixlinenr, $fixedline);
4031 $fixedline = $rawline;
4032 $fixedline =~ s/^(.\s*)else/$1} else/;
4033 fix_insert_line($fixlinenr, $fixedline);
4037 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4038 $previndent == $indent) {
4039 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4041 # Find out what is on the end of the line after the
4043 substr($s, 0, length($c), '');
4046 if ($s =~ /^\s*;/) {
4047 if (ERROR("WHILE_AFTER_BRACE",
4048 "while should follow close brace '}'\n" . $hereprev) &&
4049 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4050 fix_delete_line($fixlinenr - 1, $prevrawline);
4051 fix_delete_line($fixlinenr, $rawline);
4052 my $fixedline = $prevrawline;
4053 my $trailing = $rawline;
4054 $trailing =~ s/^\+//;
4055 $trailing = trim($trailing);
4056 $fixedline =~ s/}\s*$/} $trailing/;
4057 fix_insert_line($fixlinenr, $fixedline);
4062 #Specific variable tests
4063 while ($line =~ m{($Constant|$Lval)}g) {
4066 #gcc binary extension
4067 if ($var =~ /^$Binary$/) {
4068 if (WARN("GCC_BINARY_CONSTANT",
4069 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4071 my $hexval = sprintf("0x%x", oct($var));
4072 $fixed[$fixlinenr] =~
4073 s/\b$var\b/$hexval/;
4078 if ($var !~ /^$Constant$/ &&
4079 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4080 #Ignore Page<foo> variants
4081 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4082 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4083 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4084 #Ignore some three character SI units explicitly, like MiB and KHz
4085 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4086 while ($var =~ m{($Ident)}g) {
4088 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4090 seed_camelcase_includes();
4091 if (!$file && !$camelcase_file_seeded) {
4092 seed_camelcase_file($realfile);
4093 $camelcase_file_seeded = 1;
4096 if (!defined $camelcase{$word}) {
4097 $camelcase{$word} = 1;
4099 "Avoid CamelCase: <$word>\n" . $herecurr);
4105 #no spaces allowed after \ in define
4106 if ($line =~ /\#\s*define.*\\\s+$/) {
4107 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4108 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4110 $fixed[$fixlinenr] =~ s/\s+$//;
4114 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4115 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4117 my $checkfile = "include/linux/$file";
4118 if (-f "$root/$checkfile" &&
4119 $realfile ne $checkfile &&
4120 $1 !~ /$allowed_asm_includes/)
4122 if ($realfile =~ m{^arch/}) {
4123 CHK("ARCH_INCLUDE_LINUX",
4124 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4126 WARN("INCLUDE_LINUX",
4127 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4132 # multi-statement macros should be enclosed in a do while loop, grab the
4133 # first statement and ensure its the whole macro if its not enclosed
4134 # in a known good container
4135 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4136 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4139 my ($off, $dstat, $dcond, $rest);
4141 my $has_flow_statement = 0;
4142 my $has_arg_concat = 0;
4143 ($dstat, $dcond, $ln, $cnt, $off) =
4144 ctx_statement_block($linenr, $realcnt, 0);
4146 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4147 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4149 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4150 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4152 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4154 $dstat =~ s/\\\n.//g;
4155 $dstat =~ s/^\s*//s;
4156 $dstat =~ s/\s*$//s;
4158 # Flatten any parentheses and braces
4159 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4160 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4161 $dstat =~ s/\[[^\[\]]*\]/1/)
4165 # Flatten any obvious string concatentation.
4166 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4167 $dstat =~ s/$Ident\s*("X*")/$1/)
4171 my $exceptions = qr{
4183 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4185 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4186 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4187 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4188 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4189 $dstat !~ /$exceptions/ &&
4190 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4191 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4192 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4193 $dstat !~ /^for\s*$Constant$/ && # for (...)
4194 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4195 $dstat !~ /^do\s*{/ && # do {...
4196 $dstat !~ /^\({/ && # ({...
4197 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4200 my $herectx = $here . "\n";
4201 my $cnt = statement_rawlines($ctx);
4203 for (my $n = 0; $n < $cnt; $n++) {
4204 $herectx .= raw_line($linenr, $n) . "\n";
4207 if ($dstat =~ /;/) {
4208 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4209 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4211 ERROR("COMPLEX_MACRO",
4212 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4216 # check for macros with flow control, but without ## concatenation
4217 # ## concatenation is commonly a macro that defines a function so ignore those
4218 if ($has_flow_statement && !$has_arg_concat) {
4219 my $herectx = $here . "\n";
4220 my $cnt = statement_rawlines($ctx);
4222 for (my $n = 0; $n < $cnt; $n++) {
4223 $herectx .= raw_line($linenr, $n) . "\n";
4225 WARN("MACRO_WITH_FLOW_CONTROL",
4226 "Macros with flow control statements should be avoided\n" . "$herectx");
4229 # check for line continuations outside of #defines, preprocessor #, and asm
4232 if ($prevline !~ /^..*\\$/ &&
4233 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4234 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4235 $line =~ /^\+.*\\$/) {
4236 WARN("LINE_CONTINUATIONS",
4237 "Avoid unnecessary line continuations\n" . $herecurr);
4241 # do {} while (0) macro tests:
4242 # single-statement macros do not need to be enclosed in do while (0) loop,
4243 # macro should not end with a semicolon
4244 if ($^V && $^V ge 5.10.0 &&
4245 $realfile !~ m@/vmlinux.lds.h$@ &&
4246 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4249 my ($off, $dstat, $dcond, $rest);
4251 ($dstat, $dcond, $ln, $cnt, $off) =
4252 ctx_statement_block($linenr, $realcnt, 0);
4255 $dstat =~ s/\\\n.//g;
4257 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4262 my $cnt = statement_rawlines($ctx);
4263 my $herectx = $here . "\n";
4265 for (my $n = 0; $n < $cnt; $n++) {
4266 $herectx .= raw_line($linenr, $n) . "\n";
4269 if (($stmts =~ tr/;/;/) == 1 &&
4270 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4271 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4272 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4274 if (defined $semis && $semis ne "") {
4275 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4276 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4278 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4280 my $cnt = statement_rawlines($ctx);
4281 my $herectx = $here . "\n";
4283 for (my $n = 0; $n < $cnt; $n++) {
4284 $herectx .= raw_line($linenr, $n) . "\n";
4287 WARN("TRAILING_SEMICOLON",
4288 "macros should not use a trailing semicolon\n" . "$herectx");
4292 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4293 # all assignments may have only one of the following with an assignment:
4296 # VMLINUX_SYMBOL(...)
4297 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4298 WARN("MISSING_VMLINUX_SYMBOL",
4299 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4302 # check for redundant bracing round if etc
4303 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4304 my ($level, $endln, @chunks) =
4305 ctx_statement_full($linenr, $realcnt, 1);
4306 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4307 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4308 if ($#chunks > 0 && $level == 0) {
4312 my $herectx = $here . "\n";
4313 my $ln = $linenr - 1;
4314 for my $chunk (@chunks) {
4315 my ($cond, $block) = @{$chunk};
4317 # If the condition carries leading newlines, then count those as offsets.
4318 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4319 my $offset = statement_rawlines($whitespace) - 1;
4321 $allowed[$allow] = 0;
4322 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4324 # We have looked at and allowed this specific line.
4325 $suppress_ifbraces{$ln + $offset} = 1;
4327 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4328 $ln += statement_rawlines($block) - 1;
4330 substr($block, 0, length($cond), '');
4332 $seen++ if ($block =~ /^\s*{/);
4334 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4335 if (statement_lines($cond) > 1) {
4336 #print "APW: ALLOWED: cond<$cond>\n";
4337 $allowed[$allow] = 1;
4339 if ($block =~/\b(?:if|for|while)\b/) {
4340 #print "APW: ALLOWED: block<$block>\n";
4341 $allowed[$allow] = 1;
4343 if (statement_block_size($block) > 1) {
4344 #print "APW: ALLOWED: lines block<$block>\n";
4345 $allowed[$allow] = 1;
4350 my $sum_allowed = 0;
4351 foreach (@allowed) {
4354 if ($sum_allowed == 0) {
4356 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4357 } elsif ($sum_allowed != $allow &&
4360 "braces {} should be used on all arms of this statement\n" . $herectx);
4365 if (!defined $suppress_ifbraces{$linenr - 1} &&
4366 $line =~ /\b(if|while|for|else)\b/) {
4369 # Check the pre-context.
4370 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4371 #print "APW: ALLOWED: pre<$1>\n";
4375 my ($level, $endln, @chunks) =
4376 ctx_statement_full($linenr, $realcnt, $-[0]);
4378 # Check the condition.
4379 my ($cond, $block) = @{$chunks[0]};
4380 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4381 if (defined $cond) {
4382 substr($block, 0, length($cond), '');
4384 if (statement_lines($cond) > 1) {
4385 #print "APW: ALLOWED: cond<$cond>\n";
4388 if ($block =~/\b(?:if|for|while)\b/) {
4389 #print "APW: ALLOWED: block<$block>\n";
4392 if (statement_block_size($block) > 1) {
4393 #print "APW: ALLOWED: lines block<$block>\n";
4396 # Check the post-context.
4397 if (defined $chunks[1]) {
4398 my ($cond, $block) = @{$chunks[1]};
4399 if (defined $cond) {
4400 substr($block, 0, length($cond), '');
4402 if ($block =~ /^\s*\{/) {
4403 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4407 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4408 my $herectx = $here . "\n";
4409 my $cnt = statement_rawlines($block);
4411 for (my $n = 0; $n < $cnt; $n++) {
4412 $herectx .= raw_line($linenr, $n) . "\n";
4416 "braces {} are not necessary for single statement blocks\n" . $herectx);
4420 # check for unnecessary blank lines around braces
4421 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4423 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
4425 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4427 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
4430 # no volatiles please
4431 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4432 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4434 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4437 # Check for user-visible strings broken across lines, which breaks the ability
4438 # to grep for the string. Make exceptions when the previous string ends in a
4439 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4440 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4441 if ($line =~ /^\+\s*"[X\t]*"/ &&
4442 $prevline =~ /"\s*$/ &&
4443 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4444 if (WARN("SPLIT_STRING",
4445 "quoted string split across lines\n" . $hereprev) &&
4447 $prevrawline =~ /^\+.*"\s*$/ &&
4448 $last_coalesced_string_linenr != $linenr - 1) {
4449 my $extracted_string = get_quoted_string($line, $rawline);
4450 my $comma_close = "";
4451 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4455 fix_delete_line($fixlinenr - 1, $prevrawline);
4456 fix_delete_line($fixlinenr, $rawline);
4457 my $fixedline = $prevrawline;
4458 $fixedline =~ s/"\s*$//;
4459 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4460 fix_insert_line($fixlinenr - 1, $fixedline);
4461 $fixedline = $rawline;
4462 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4463 if ($fixedline !~ /\+\s*$/) {
4464 fix_insert_line($fixlinenr, $fixedline);
4466 $last_coalesced_string_linenr = $linenr;
4470 # check for missing a space in a string concatenation
4471 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4472 WARN('MISSING_SPACE',
4473 "break quoted strings at a space character\n" . $hereprev);
4476 # check for spaces before a quoted newline
4477 if ($rawline =~ /^.*\".*\s\\n/) {
4478 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4479 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4481 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4486 # concatenated string without spaces between elements
4487 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4488 CHK("CONCATENATED_STRING",
4489 "Concatenated strings should use spaces between elements\n" . $herecurr);
4492 # uncoalesced string fragments
4493 if ($line =~ /"X*"\s*"/) {
4494 WARN("STRING_FRAGMENTS",
4495 "Consecutive strings are generally better as a single string\n" . $herecurr);
4498 # check for %L{u,d,i} in strings
4500 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4501 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4502 $string =~ s/%%/__/g;
4503 if ($string =~ /(?<!%)%L[udi]/) {
4505 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4510 # check for line continuations in quoted strings with odd counts of "
4511 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4512 WARN("LINE_CONTINUATIONS",
4513 "Avoid line continuations in quoted strings\n" . $herecurr);
4517 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4518 CHK("REDUNDANT_CODE",
4519 "if this code is redundant consider removing it\n" .
4523 # check for needless "if (<foo>) fn(<foo>)" uses
4524 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4525 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4526 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4528 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4532 # check for unnecessary "Out of Memory" messages
4533 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4534 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4535 (defined $1 || defined $3) &&
4538 my $testline = $lines[$linenr - 3];
4540 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4541 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4543 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4545 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4549 # check for logging functions with KERN_<LEVEL>
4550 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4551 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4553 if (WARN("UNNECESSARY_KERN_LEVEL",
4554 "Possible unnecessary $level\n" . $herecurr) &&
4556 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4560 # check for mask then right shift without a parentheses
4561 if ($^V && $^V ge 5.10.0 &&
4562 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4563 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4564 WARN("MASK_THEN_SHIFT",
4565 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4568 # check for pointer comparisons to NULL
4569 if ($^V && $^V ge 5.10.0) {
4570 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4573 $equal = "" if ($4 eq "!=");
4574 if (CHK("COMPARISON_TO_NULL",
4575 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4577 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4582 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4583 if ($line =~ /(\b$InitAttribute\b)/) {
4585 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4588 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4589 ERROR("MISPLACED_INIT",
4590 "$attr should be placed after $var\n" . $herecurr)) ||
4591 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4592 WARN("MISPLACED_INIT",
4593 "$attr should be placed after $var\n" . $herecurr))) &&
4595 $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;
4600 # check for $InitAttributeData (ie: __initdata) with const
4601 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4603 $attr =~ /($InitAttributePrefix)(.*)/;
4604 my $attr_prefix = $1;
4606 if (ERROR("INIT_ATTRIBUTE",
4607 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4609 $fixed[$fixlinenr] =~
4610 s/$InitAttributeData/${attr_prefix}initconst/;
4614 # check for $InitAttributeConst (ie: __initconst) without const
4615 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4617 if (ERROR("INIT_ATTRIBUTE",
4618 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4620 my $lead = $fixed[$fixlinenr] =~
4621 /(^\+\s*(?:static\s+))/;
4623 $lead = "$lead " if ($lead !~ /^\+$/);
4624 $lead = "${lead}const ";
4625 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4629 # don't use __constant_<foo> functions outside of include/uapi/
4630 if ($realfile !~ m@^include/uapi/@ &&
4631 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4632 my $constant_func = $1;
4633 my $func = $constant_func;
4634 $func =~ s/^__constant_//;
4635 if (WARN("CONSTANT_CONVERSION",
4636 "$constant_func should be $func\n" . $herecurr) &&
4638 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4642 # prefer usleep_range over udelay
4643 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4645 # ignore udelay's < 10, however
4646 if (! ($delay < 10) ) {
4648 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4650 if ($delay > 2000) {
4652 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4656 # warn about unexpectedly long msleep's
4657 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4660 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4664 # check for comparisons of jiffies
4665 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4666 WARN("JIFFIES_COMPARISON",
4667 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4670 # check for comparisons of get_jiffies_64()
4671 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4672 WARN("JIFFIES_COMPARISON",
4673 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4676 # warn about #ifdefs in C files
4677 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4678 # print "#ifdef in C files should be avoided\n";
4679 # print "$herecurr";
4683 # warn about spacing in #ifdefs
4684 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4685 if (ERROR("SPACING",
4686 "exactly one space required after that #$1\n" . $herecurr) &&
4688 $fixed[$fixlinenr] =~
4689 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4694 # check for spinlock_t definitions without a comment.
4695 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4696 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4698 if (!ctx_has_comment($first_line, $linenr)) {
4699 CHK("UNCOMMENTED_DEFINITION",
4700 "$1 definition without comment\n" . $herecurr);
4703 # check for memory barriers without a comment.
4704 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4705 if (!ctx_has_comment($first_line, $linenr)) {
4706 WARN("MEMORY_BARRIER",
4707 "memory barrier without comment\n" . $herecurr);
4710 # check of hardware specific defines
4711 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4713 "architecture specific defines should be avoided\n" . $herecurr);
4716 # Check that the storage class is at the beginning of a declaration
4717 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4718 WARN("STORAGE_CLASS",
4719 "storage class should be at the beginning of the declaration\n" . $herecurr)
4722 # check the location of the inline attribute, that it is between
4723 # storage class and type.
4724 if ($line =~ /\b$Type\s+$Inline\b/ ||
4725 $line =~ /\b$Inline\s+$Storage\b/) {
4726 ERROR("INLINE_LOCATION",
4727 "inline keyword should sit between storage class and type\n" . $herecurr);
4730 # Check for __inline__ and __inline, prefer inline
4731 if ($realfile !~ m@\binclude/uapi/@ &&
4732 $line =~ /\b(__inline__|__inline)\b/) {
4734 "plain inline is preferred over $1\n" . $herecurr) &&
4736 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4741 # Check for __attribute__ packed, prefer __packed
4742 if ($realfile !~ m@\binclude/uapi/@ &&
4743 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4744 WARN("PREFER_PACKED",
4745 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4748 # Check for __attribute__ aligned, prefer __aligned
4749 if ($realfile !~ m@\binclude/uapi/@ &&
4750 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4751 WARN("PREFER_ALIGNED",
4752 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4755 # Check for __attribute__ format(printf, prefer __printf
4756 if ($realfile !~ m@\binclude/uapi/@ &&
4757 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4758 if (WARN("PREFER_PRINTF",
4759 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4761 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4766 # Check for __attribute__ format(scanf, prefer __scanf
4767 if ($realfile !~ m@\binclude/uapi/@ &&
4768 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4769 if (WARN("PREFER_SCANF",
4770 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4772 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4776 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4777 if ($^V && $^V ge 5.10.0 &&
4778 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4779 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4780 $line =~ /\b__weak\b/)) {
4781 ERROR("WEAK_DECLARATION",
4782 "Using weak declarations can have unintended link defects\n" . $herecurr);
4785 # check for sizeof(&)
4786 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4787 WARN("SIZEOF_ADDRESS",
4788 "sizeof(& should be avoided\n" . $herecurr);
4791 # check for sizeof without parenthesis
4792 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4793 if (WARN("SIZEOF_PARENTHESIS",
4794 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4796 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4800 # check for struct spinlock declarations
4801 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4802 WARN("USE_SPINLOCK_T",
4803 "struct spinlock should be spinlock_t\n" . $herecurr);
4806 # check for seq_printf uses that could be seq_puts
4807 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4808 my $fmt = get_quoted_string($line, $rawline);
4809 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4810 if (WARN("PREFER_SEQ_PUTS",
4811 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4813 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4818 # Check for misused memsets
4819 if ($^V && $^V ge 5.10.0 &&
4821 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4827 if ($ms_size =~ /^(0x|)0$/i) {
4829 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4830 } elsif ($ms_size =~ /^(0x|)1$/i) {
4832 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4836 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4837 if ($^V && $^V ge 5.10.0 &&
4838 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4839 if (WARN("PREFER_ETHER_ADDR_COPY",
4840 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4842 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4846 # typecasts on min/max could be min_t/max_t
4847 if ($^V && $^V ge 5.10.0 &&
4849 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4850 if (defined $2 || defined $7) {
4852 my $cast1 = deparenthesize($2);
4854 my $cast2 = deparenthesize($7);
4858 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4859 $cast = "$cast1 or $cast2";
4860 } elsif ($cast1 ne "") {
4866 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4870 # check usleep_range arguments
4871 if ($^V && $^V ge 5.10.0 &&
4873 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4877 WARN("USLEEP_RANGE",
4878 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4879 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4881 WARN("USLEEP_RANGE",
4882 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4886 # check for naked sscanf
4887 if ($^V && $^V ge 5.10.0 &&
4889 $line =~ /\bsscanf\b/ &&
4890 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4891 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4892 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4893 my $lc = $stat =~ tr@\n@@;
4894 $lc = $lc + $linenr;
4895 my $stat_real = raw_line($linenr, 0);
4896 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4897 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4899 WARN("NAKED_SSCANF",
4900 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4903 # check for simple sscanf that should be kstrto<foo>
4904 if ($^V && $^V ge 5.10.0 &&
4906 $line =~ /\bsscanf\b/) {
4907 my $lc = $stat =~ tr@\n@@;
4908 $lc = $lc + $linenr;
4909 my $stat_real = raw_line($linenr, 0);
4910 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4911 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4913 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4915 my $count = $format =~ tr@%@%@;
4917 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4918 WARN("SSCANF_TO_KSTRTO",
4919 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4924 # check for new externs in .h files.
4925 if ($realfile =~ /\.h$/ &&
4926 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4927 if (CHK("AVOID_EXTERNS",
4928 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4930 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4934 # check for new externs in .c files.
4935 if ($realfile =~ /\.c$/ && defined $stat &&
4936 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4938 my $function_name = $1;
4939 my $paren_space = $2;
4942 if (defined $cond) {
4943 substr($s, 0, length($cond), '');
4945 if ($s =~ /^\s*;/ &&
4946 $function_name ne 'uninitialized_var')
4948 WARN("AVOID_EXTERNS",
4949 "externs should be avoided in .c files\n" . $herecurr);
4952 if ($paren_space =~ /\n/) {
4953 WARN("FUNCTION_ARGUMENTS",
4954 "arguments for function declarations should follow identifier\n" . $herecurr);
4957 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4958 $stat =~ /^.\s*extern\s+/)
4960 WARN("AVOID_EXTERNS",
4961 "externs should be avoided in .c files\n" . $herecurr);
4964 # checks for new __setup's
4965 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4968 if (!grep(/$name/, @setup_docs)) {
4969 CHK("UNDOCUMENTED_SETUP",
4970 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4974 # check for pointless casting of kmalloc return
4975 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4976 WARN("UNNECESSARY_CASTS",
4977 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4981 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4982 if ($^V && $^V ge 5.10.0 &&
4983 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4984 CHK("ALLOC_SIZEOF_STRUCT",
4985 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4988 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
4989 if ($^V && $^V ge 5.10.0 &&
4990 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
4994 my $newfunc = "kmalloc_array";
4995 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
4998 if ($a1 =~ /^sizeof\s*\S/) {
5002 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5003 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5004 if (WARN("ALLOC_WITH_MULTIPLY",
5005 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5007 $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;
5013 # check for krealloc arg reuse
5014 if ($^V && $^V ge 5.10.0 &&
5015 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5016 WARN("KREALLOC_ARG_REUSE",
5017 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5020 # check for alloc argument mismatch
5021 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5022 WARN("ALLOC_ARRAY_ARGS",
5023 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5026 # check for multiple semicolons
5027 if ($line =~ /;\s*;\s*$/) {
5028 if (WARN("ONE_SEMICOLON",
5029 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5031 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5035 # check for #defines like: 1 << <digit> that could be BIT(digit)
5036 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5038 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5039 if (CHK("BIT_MACRO",
5040 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5042 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5046 # check for case / default statements not preceded by break/fallthrough/switch
5047 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5049 my $has_statement = 0;
5051 my $prevline = $linenr;
5052 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5054 my $rline = $rawlines[$prevline - 1];
5055 my $fline = $lines[$prevline - 1];
5056 last if ($fline =~ /^\@\@/);
5057 next if ($fline =~ /^\-/);
5058 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5059 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5060 next if ($fline =~ /^.[\s$;]*$/);
5063 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5065 if (!$has_break && $has_statement) {
5066 WARN("MISSING_BREAK",
5067 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5071 # check for switch/default statements without a break;
5072 if ($^V && $^V ge 5.10.0 &&
5074 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5076 my $herectx = $here . "\n";
5077 my $cnt = statement_rawlines($stat);
5078 for (my $n = 0; $n < $cnt; $n++) {
5079 $herectx .= raw_line($linenr, $n) . "\n";
5081 WARN("DEFAULT_NO_BREAK",
5082 "switch default: should use break\n" . $herectx);
5085 # check for gcc specific __FUNCTION__
5086 if ($line =~ /\b__FUNCTION__\b/) {
5087 if (WARN("USE_FUNC",
5088 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5090 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5094 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5095 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5097 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5100 # check for use of yield()
5101 if ($line =~ /\byield\s*\(\s*\)/) {
5103 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5106 # check for comparisons against true and false
5107 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5115 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5117 my $type = lc($otype);
5118 if ($type =~ /^(?:true|false)$/) {
5119 if (("$test" eq "==" && "$type" eq "true") ||
5120 ("$test" eq "!=" && "$type" eq "false")) {
5124 CHK("BOOL_COMPARISON",
5125 "Using comparison to $otype is error prone\n" . $herecurr);
5127 ## maybe suggesting a correct construct would better
5128 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5133 # check for semaphores initialized locked
5134 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5135 WARN("CONSIDER_COMPLETION",
5136 "consider using a completion\n" . $herecurr);
5139 # recommend kstrto* over simple_strto* and strict_strto*
5140 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5141 WARN("CONSIDER_KSTRTO",
5142 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5145 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5146 if ($line =~ /^.\s*__initcall\s*\(/) {
5147 WARN("USE_DEVICE_INITCALL",
5148 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5151 # check for various ops structs, ensure they are const.
5152 my $struct_ops = qr{acpi_dock_ops|
5153 address_space_operations|
5155 block_device_operations|
5160 file_lock_operations|
5170 lock_manager_operations|
5176 pipe_buf_operations|
5177 platform_hibernation_ops|
5178 platform_suspend_ops|
5183 soc_pcmcia_socket_ops|
5189 if ($line !~ /\bconst\b/ &&
5190 $line =~ /\bstruct\s+($struct_ops)\b/) {
5191 WARN("CONST_STRUCT",
5192 "struct $1 should normally be const\n" .
5196 # use of NR_CPUS is usually wrong
5197 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5198 if ($line =~ /\bNR_CPUS\b/ &&
5199 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5200 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5201 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5202 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5203 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5206 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5209 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5210 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5211 ERROR("DEFINE_ARCH_HAS",
5212 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5215 # whine mightly about in_atomic
5216 if ($line =~ /\bin_atomic\s*\(/) {
5217 if ($realfile =~ m@^drivers/@) {
5219 "do not use in_atomic in drivers\n" . $herecurr);
5220 } elsif ($realfile !~ m@^kernel/@) {
5222 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5226 # check for lockdep_set_novalidate_class
5227 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5228 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5229 if ($realfile !~ m@^kernel/lockdep@ &&
5230 $realfile !~ m@^include/linux/lockdep@ &&
5231 $realfile !~ m@^drivers/base/core@) {
5233 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5237 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5238 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5239 WARN("EXPORTED_WORLD_WRITABLE",
5240 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5243 # Mode permission misuses where it seems decimal should be octal
5244 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5245 if ($^V && $^V ge 5.10.0 &&
5246 $line =~ /$mode_perms_search/) {
5247 foreach my $entry (@mode_permission_funcs) {
5248 my $func = $entry->[0];
5249 my $arg_pos = $entry->[1];
5254 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5256 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5257 if ($line =~ /$test/) {
5259 $val = $6 if ($skip_args ne "");
5261 if ($val !~ /^0$/ &&
5262 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5263 length($val) ne 4)) {
5264 ERROR("NON_OCTAL_PERMISSIONS",
5265 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5266 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5267 ERROR("EXPORTED_WORLD_WRITABLE",
5268 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5275 # If we have no input at all, then there is nothing to report on
5276 # so just keep quiet.
5277 if ($#rawlines == -1) {
5281 # In mailback mode only produce a report in the negative, for
5282 # things that appear to be patches.
5283 if ($mailback && ($clean == 1 || !$is_patch)) {
5287 # This is not a patch, and we are are in 'no-patch' mode so
5289 if (!$chk_patch && !$is_patch) {
5294 ERROR("NOT_UNIFIED_DIFF",
5295 "Does not appear to be a unified-diff format patch\n");
5297 if ($is_patch && $chk_signoff && $signoff == 0) {
5298 ERROR("MISSING_SIGN_OFF",
5299 "Missing Signed-off-by: line(s)\n");
5302 print report_dump();
5303 if ($summary && !($clean == 1 && $quiet == 1)) {
5304 print "$filename " if ($summary_file);
5305 print "total: $cnt_error errors, $cnt_warn warnings, " .
5306 (($check)? "$cnt_chk checks, " : "") .
5307 "$cnt_lines lines checked\n";
5308 print "\n" if ($quiet == 0);
5313 if ($^V lt 5.10.0) {
5314 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5315 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5318 # If there were whitespace errors which cleanpatch can fix
5319 # then suggest that.
5320 if ($rpt_cleaners) {
5321 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5322 print " scripts/cleanfile\n\n";
5327 hash_show_words(\%use_type, "Used");
5328 hash_show_words(\%ignore_type, "Ignored");
5330 if ($clean == 0 && $fix &&
5331 ("@rawlines" ne "@fixed" ||
5332 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5333 my $newfile = $filename;
5334 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5338 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5340 open($f, '>', $newfile)
5341 or die "$P: Can't open $newfile for write\n";
5342 foreach my $fixed_line (@fixed) {
5345 if ($linecount > 3) {
5346 $fixed_line =~ s/^\+//;
5347 print $f $fixed_line . "\n";
5350 print $f $fixed_line . "\n";
5357 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5359 Do _NOT_ trust the results written to this file.
5360 Do _NOT_ submit these changes without inspecting them for correctness.
5362 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5363 No warranties, expressed or implied...
5369 if ($clean == 1 && $quiet == 0) {
5370 print "$vname has no obvious style problems and is ready for submission.\n"
5372 if ($clean == 0 && $quiet == 0) {
5374 $vname has style problems, please review.
5376 If any of these errors are false positives, please report
5377 them to the maintainer, see CHECKPATCH in MAINTAINERS.