2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
14 my $D = dirname(abs_path($P));
18 use Getopt::Long qw(:config no_auto_abbrev);
44 my $configuration_file = ".checkpatch.conf";
45 my $max_line_length = 80;
46 my $ignore_perl_version = 0;
47 my $minimum_perl_version = 5.10.0;
48 my $min_conf_desc_length = 4;
49 my $spelling_file = "$D/spelling.txt";
55 Usage: $P [OPTION]... [FILE]...
60 --no-tree run without a kernel tree
61 --no-signoff do not check for 'Signed-off-by' line
62 --patch treat FILE as patchfile (default)
63 --emacs emacs compile window format
64 --terse one line per report
65 -f, --file treat FILE as regular source file
66 --subjective, --strict enable more subjective tests
67 --types TYPE(,TYPE2...) show only these comma separated message types
68 --ignore TYPE(,TYPE2...) ignore various comma separated message types
69 --max-line-length=n set the maximum line length, if exceeded, warn
70 --min-conf-desc-length=n set the min description length, if shorter, warn
71 --show-types show the message "types" in the output
72 --root=PATH PATH to the kernel tree root
73 --no-summary suppress the per-file summary
74 --mailback only produce a report in case of warnings/errors
75 --summary-file include the filename in summary
76 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
77 'values', 'possible', 'type', and 'attr' (default
79 --test-only=WORD report only warnings/errors containing WORD
81 --fix EXPERIMENTAL - may create horrible results
82 If correctable single-line errors exist, create
83 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84 with potential errors corrected to the preferred
86 --fix-inplace EXPERIMENTAL - may create horrible results
87 Is the same as --fix, but overwrites the input
88 file. It's your fault if there's no backup or git
89 --ignore-perl-version override checking of perl version. expect
91 -h, --help, --version display this help and exit
93 When FILE is - read standard input.
99 my $conf = which_conf($configuration_file);
102 open(my $conffile, '<', "$conf")
103 or warn "$P: Can't find a readable $configuration_file file $!\n";
105 while (<$conffile>) {
108 $line =~ s/\s*\n?$//g;
112 next if ($line =~ m/^\s*#/);
113 next if ($line =~ m/^\s*$/);
115 my @words = split(" ", $line);
116 foreach my $word (@words) {
117 last if ($word =~ m/^#/);
118 push (@conf_args, $word);
122 unshift(@ARGV, @conf_args) if @conf_args;
126 'q|quiet+' => \$quiet,
128 'signoff!' => \$chk_signoff,
129 'patch!' => \$chk_patch,
133 'subjective!' => \$check,
134 'strict!' => \$check,
135 'ignore=s' => \@ignore,
137 'show-types!' => \$show_types,
138 'max-line-length=i' => \$max_line_length,
139 'min-conf-desc-length=i' => \$min_conf_desc_length,
141 'summary!' => \$summary,
142 'mailback!' => \$mailback,
143 'summary-file!' => \$summary_file,
145 'fix-inplace!' => \$fix_inplace,
146 'ignore-perl-version!' => \$ignore_perl_version,
147 'debug=s' => \%debug,
148 'test-only=s' => \$tst_only,
155 $fix = 1 if ($fix_inplace);
156 $check_orig = $check;
160 if ($^V && $^V lt $minimum_perl_version) {
161 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
162 if (!$ignore_perl_version) {
168 print "$P: no input files\n";
172 sub hash_save_array_words {
173 my ($hashRef, $arrayRef) = @_;
175 my @array = split(/,/, join(',', @$arrayRef));
176 foreach my $word (@array) {
177 $word =~ s/\s*\n?$//g;
180 $word =~ tr/[a-z]/[A-Z]/;
182 next if ($word =~ m/^\s*#/);
183 next if ($word =~ m/^\s*$/);
189 sub hash_show_words {
190 my ($hashRef, $prefix) = @_;
192 if ($quiet == 0 && keys %$hashRef) {
193 print "NOTE: $prefix message types:";
194 foreach my $word (sort keys %$hashRef) {
201 hash_save_array_words(\%ignore_type, \@ignore);
202 hash_save_array_words(\%use_type, \@use);
205 my $dbg_possible = 0;
208 for my $key (keys %debug) {
210 eval "\${dbg_$key} = '$debug{$key}';";
214 my $rpt_cleaners = 0;
223 if (!top_of_kernel_tree($root)) {
224 die "$P: $root: --root does not point at a valid tree\n";
227 if (top_of_kernel_tree('.')) {
229 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
230 top_of_kernel_tree($1)) {
235 if (!defined $root) {
236 print "Must be run from the top-level dir. of a kernel tree\n";
241 my $emitted_corrupt = 0;
244 [A-Za-z_][A-Za-z\d_]*
245 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
247 our $Storage = qr{extern|static|asmlinkage};
259 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
260 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
261 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
262 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
263 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
265 # Notes to $Attribute:
266 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
286 ____cacheline_aligned|
287 ____cacheline_aligned_in_smp|
288 ____cacheline_internodealigned_in_smp|
292 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
293 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
294 our $Lval = qr{$Ident(?:$Member)*};
296 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
297 our $Binary = qr{(?i)0b[01]+$Int_type?};
298 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
299 our $Int = qr{[0-9]+$Int_type?};
300 our $Octal = qr{0[0-7]+$Int_type?};
301 our $String = qr{"[X\t]*"};
302 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
303 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
304 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
305 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
306 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
307 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
308 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
309 our $Arithmetic = qr{\+|-|\*|\/|%};
313 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
316 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
319 our $NonptrTypeMisordered;
320 our $NonptrTypeWithAttr;
324 our $DeclareMisordered;
326 our $NON_ASCII_UTF8 = qr{
327 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
328 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
329 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
330 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
331 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
332 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
333 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
337 [\x09\x0A\x0D\x20-\x7E] # ASCII
341 our $typeTypedefs = qr{(?x:
342 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
346 our $logFunctions = qr{(?x:
347 printk(?:_ratelimited|_once|)|
348 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
349 WARN(?:_RATELIMIT|_ONCE|)|
352 seq_vprintf|seq_printf|seq_puts
355 our $signature_tags = qr{(?xi:
366 our @typeListMisordered = (
367 qr{char\s+(?:un)?signed},
368 qr{int\s+(?:(?:un)?signed\s+)?short\s},
369 qr{int\s+short(?:\s+(?:un)?signed)},
370 qr{short\s+int(?:\s+(?:un)?signed)},
371 qr{(?:un)?signed\s+int\s+short},
372 qr{short\s+(?:un)?signed},
373 qr{long\s+int\s+(?:un)?signed},
374 qr{int\s+long\s+(?:un)?signed},
375 qr{long\s+(?:un)?signed\s+int},
376 qr{int\s+(?:un)?signed\s+long},
377 qr{int\s+(?:un)?signed},
378 qr{int\s+long\s+long\s+(?:un)?signed},
379 qr{long\s+long\s+int\s+(?:un)?signed},
380 qr{long\s+long\s+(?:un)?signed\s+int},
381 qr{long\s+long\s+(?:un)?signed},
382 qr{long\s+(?:un)?signed},
387 qr{(?:(?:un)?signed\s+)?char},
388 qr{(?:(?:un)?signed\s+)?short\s+int},
389 qr{(?:(?:un)?signed\s+)?short},
390 qr{(?:(?:un)?signed\s+)?int},
391 qr{(?:(?:un)?signed\s+)?long\s+int},
392 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
393 qr{(?:(?:un)?signed\s+)?long\s+long},
394 qr{(?:(?:un)?signed\s+)?long},
403 qr{${Ident}_handler},
404 qr{${Ident}_handler_fn},
407 our @typeListWithAttr = (
409 qr{struct\s+$InitAttribute\s+$Ident},
410 qr{union\s+$InitAttribute\s+$Ident},
413 our @modifierList = (
417 our @mode_permission_funcs = (
419 ["module_param_(?:array|named|string)", 4],
420 ["module_param_array_named", 5],
421 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
422 ["proc_create(?:_data|)", 2],
423 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
426 #Create a search pattern for all these functions to speed up a loop below
427 our $mode_perms_search = "";
428 foreach my $entry (@mode_permission_funcs) {
429 $mode_perms_search .= '|' if ($mode_perms_search ne "");
430 $mode_perms_search .= $entry->[0];
433 our $allowed_asm_includes = qr{(?x:
439 # memory.h: ARM has a custom one
441 # Load common spelling mistakes and build regular expression list.
445 if (open(my $spelling, '<', $spelling_file)) {
447 while (<$spelling>) {
450 $line =~ s/\s*\n?$//g;
453 next if ($line =~ m/^\s*#/);
454 next if ($line =~ m/^\s*$/);
456 my ($suspect, $fix) = split(/\|\|/, $line);
458 push(@spelling_list, $suspect);
459 $spelling_fix{$suspect} = $fix;
462 $misspellings = join("|", @spelling_list);
464 warn "No typos will be found - file '$spelling_file': $!\n";
468 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
469 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
470 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
471 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
472 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
474 (?:$Modifier\s+|const\s+)*
476 (?:typeof|__typeof__)\s*\([^\)]*\)|
480 (?:\s+$Modifier|\s+const)*
482 $NonptrTypeMisordered = qr{
483 (?:$Modifier\s+|const\s+)*
487 (?:\s+$Modifier|\s+const)*
489 $NonptrTypeWithAttr = qr{
490 (?:$Modifier\s+|const\s+)*
492 (?:typeof|__typeof__)\s*\([^\)]*\)|
496 (?:\s+$Modifier|\s+const)*
500 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
501 (?:\s+$Inline|\s+$Modifier)*
503 $TypeMisordered = qr{
504 $NonptrTypeMisordered
505 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
506 (?:\s+$Inline|\s+$Modifier)*
508 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
509 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
513 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
515 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
516 # requires at least perl version v5.10.0
517 # Any use must be runtime checked with $^V
519 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
520 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
521 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
523 our $declaration_macros = qr{(?x:
524 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
525 (?:$Storage\s+)?LIST_HEAD\s*\(|
526 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
531 return "" if (!defined($string));
533 while ($string =~ /^\s*\(.*\)\s*$/) {
534 $string =~ s@^\s*\(\s*@@;
535 $string =~ s@\s*\)\s*$@@;
538 $string =~ s@\s+@ @g;
543 sub seed_camelcase_file {
546 return if (!(-f $file));
550 open(my $include_file, '<', "$file")
551 or warn "$P: Can't read '$file' $!\n";
552 my $text = <$include_file>;
553 close($include_file);
555 my @lines = split('\n', $text);
557 foreach my $line (@lines) {
558 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
559 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
561 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
563 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
569 my $camelcase_seeded = 0;
570 sub seed_camelcase_includes {
571 return if ($camelcase_seeded);
574 my $camelcase_cache = "";
575 my @include_files = ();
577 $camelcase_seeded = 1;
580 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
581 chomp $git_last_include_commit;
582 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
584 my $last_mod_date = 0;
585 $files = `find $root/include -name "*.h"`;
586 @include_files = split('\n', $files);
587 foreach my $file (@include_files) {
588 my $date = POSIX::strftime("%Y%m%d%H%M",
589 localtime((stat $file)[9]));
590 $last_mod_date = $date if ($last_mod_date < $date);
592 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
595 if ($camelcase_cache ne "" && -f $camelcase_cache) {
596 open(my $camelcase_file, '<', "$camelcase_cache")
597 or warn "$P: Can't read '$camelcase_cache' $!\n";
598 while (<$camelcase_file>) {
602 close($camelcase_file);
608 $files = `git ls-files "include/*.h"`;
609 @include_files = split('\n', $files);
612 foreach my $file (@include_files) {
613 seed_camelcase_file($file);
616 if ($camelcase_cache ne "") {
617 unlink glob ".checkpatch-camelcase.*";
618 open(my $camelcase_file, '>', "$camelcase_cache")
619 or warn "$P: Can't write '$camelcase_cache' $!\n";
620 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
621 print $camelcase_file ("$_\n");
623 close($camelcase_file);
627 sub git_commit_info {
628 my ($commit, $id, $desc) = @_;
630 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
632 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
633 $output =~ s/^\s*//gm;
634 my @lines = split("\n", $output);
636 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
637 # Maybe one day convert this block of bash into something that returns
638 # all matching commit ids, but it's very slow...
640 # echo "checking commits $1..."
641 # git rev-list --remotes | grep -i "^$1" |
642 # while read line ; do
643 # git log --format='%H %s' -1 $line |
644 # echo "commit $(cut -c 1-12,41-)"
646 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
648 $id = substr($lines[0], 0, 12);
649 $desc = substr($lines[0], 41);
655 $chk_signoff = 0 if ($file);
660 my @fixed_inserted = ();
661 my @fixed_deleted = ();
665 for my $filename (@ARGV) {
668 open($FILE, '-|', "diff -u /dev/null $filename") ||
669 die "$P: $filename: diff failed - $!\n";
670 } elsif ($filename eq '-') {
671 open($FILE, '<&STDIN');
673 open($FILE, '<', "$filename") ||
674 die "$P: $filename: open failed - $!\n";
676 if ($filename eq '-') {
677 $vname = 'Your patch';
686 if (!process($filename)) {
692 @fixed_inserted = ();
699 sub top_of_kernel_tree {
703 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
704 "README", "Documentation", "arch", "include", "drivers",
705 "fs", "init", "ipc", "kernel", "lib", "scripts",
708 foreach my $check (@tree_check) {
709 if (! -e $root . '/' . $check) {
717 my ($formatted_email) = @_;
723 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
726 $comment = $3 if defined $3;
727 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
729 $comment = $2 if defined $2;
730 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
732 $comment = $2 if defined $2;
733 $formatted_email =~ s/$address.*$//;
734 $name = $formatted_email;
736 $name =~ s/^\"|\"$//g;
737 # If there's a name left after stripping spaces and
738 # leading quotes, and the address doesn't have both
739 # leading and trailing angle brackets, the address
741 # "joe smith joe@smith.com" bad
742 # "joe smith <joe@smith.com" bad
743 if ($name ne "" && $address !~ /^<[^>]+>$/) {
751 $name =~ s/^\"|\"$//g;
752 $address = trim($address);
753 $address =~ s/^\<|\>$//g;
755 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
756 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
760 return ($name, $address, $comment);
764 my ($name, $address) = @_;
769 $name =~ s/^\"|\"$//g;
770 $address = trim($address);
772 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
773 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
778 $formatted_email = "$address";
780 $formatted_email = "$name <$address>";
783 return $formatted_email;
789 foreach my $path (split(/:/, $ENV{PATH})) {
790 if (-e "$path/$bin") {
801 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
802 if (-e "$path/$conf") {
803 return "$path/$conf";
815 for my $c (split(//, $str)) {
819 for (; ($n % 8) != 0; $n++) {
831 (my $res = shift) =~ tr/\t/ /c;
838 # Drop the diff line leader and expand tabs
840 $line = expand_tabs($line);
842 # Pick the indent from the front of the line.
843 my ($white) = ($line =~ /^(\s*)/);
845 return (length($line), length($white));
848 my $sanitise_quote = '';
850 sub sanitise_line_reset {
851 my ($in_comment) = @_;
854 $sanitise_quote = '*/';
856 $sanitise_quote = '';
869 # Always copy over the diff marker.
870 $res = substr($line, 0, 1);
872 for ($off = 1; $off < length($line); $off++) {
873 $c = substr($line, $off, 1);
875 # Comments we are wacking completly including the begin
876 # and end, all to $;.
877 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
878 $sanitise_quote = '*/';
880 substr($res, $off, 2, "$;$;");
884 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
885 $sanitise_quote = '';
886 substr($res, $off, 2, "$;$;");
890 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
891 $sanitise_quote = '//';
893 substr($res, $off, 2, $sanitise_quote);
898 # A \ in a string means ignore the next character.
899 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
901 substr($res, $off, 2, 'XX');
906 if ($c eq "'" || $c eq '"') {
907 if ($sanitise_quote eq '') {
908 $sanitise_quote = $c;
910 substr($res, $off, 1, $c);
912 } elsif ($sanitise_quote eq $c) {
913 $sanitise_quote = '';
917 #print "c<$c> SQ<$sanitise_quote>\n";
918 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
919 substr($res, $off, 1, $;);
920 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
921 substr($res, $off, 1, $;);
922 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
923 substr($res, $off, 1, 'X');
925 substr($res, $off, 1, $c);
929 if ($sanitise_quote eq '//') {
930 $sanitise_quote = '';
933 # The pathname on a #include may be surrounded by '<' and '>'.
934 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
935 my $clean = 'X' x length($1);
936 $res =~ s@\<.*\>@<$clean>@;
938 # The whole of a #error is a string.
939 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
940 my $clean = 'X' x length($1);
941 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
947 sub get_quoted_string {
948 my ($line, $rawline) = @_;
950 return "" if ($line !~ m/(\"[X\t]+\")/g);
951 return substr($rawline, $-[0], $+[0] - $-[0]);
954 sub ctx_statement_block {
955 my ($linenr, $remain, $off) = @_;
956 my $line = $linenr - 1;
973 @stack = (['', 0]) if ($#stack == -1);
975 #warn "CSB: blk<$blk> remain<$remain>\n";
976 # If we are about to drop off the end, pull in more
979 for (; $remain > 0; $line++) {
980 last if (!defined $lines[$line]);
981 next if ($lines[$line] =~ /^-/);
984 $blk .= $lines[$line] . "\n";
989 # Bail if there is no further context.
990 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
994 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1000 $c = substr($blk, $off, 1);
1001 $remainder = substr($blk, $off);
1003 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1005 # Handle nested #if/#else.
1006 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1007 push(@stack, [ $type, $level ]);
1008 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1009 ($type, $level) = @{$stack[$#stack - 1]};
1010 } elsif ($remainder =~ /^#\s*endif\b/) {
1011 ($type, $level) = @{pop(@stack)};
1014 # Statement ends at the ';' or a close '}' at the
1016 if ($level == 0 && $c eq ';') {
1020 # An else is really a conditional as long as its not else if
1021 if ($level == 0 && $coff_set == 0 &&
1022 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1023 $remainder =~ /^(else)(?:\s|{)/ &&
1024 $remainder !~ /^else\s+if\b/) {
1025 $coff = $off + length($1) - 1;
1027 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1028 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1031 if (($type eq '' || $type eq '(') && $c eq '(') {
1035 if ($type eq '(' && $c eq ')') {
1037 $type = ($level != 0)? '(' : '';
1039 if ($level == 0 && $coff < $soff) {
1042 #warn "CSB: mark coff<$coff>\n";
1045 if (($type eq '' || $type eq '{') && $c eq '{') {
1049 if ($type eq '{' && $c eq '}') {
1051 $type = ($level != 0)? '{' : '';
1054 if (substr($blk, $off + 1, 1) eq ';') {
1060 # Preprocessor commands end at the newline unless escaped.
1061 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1069 # We are truly at the end, so shuffle to the next line.
1076 my $statement = substr($blk, $soff, $off - $soff + 1);
1077 my $condition = substr($blk, $soff, $coff - $soff + 1);
1079 #warn "STATEMENT<$statement>\n";
1080 #warn "CONDITION<$condition>\n";
1082 #print "coff<$coff> soff<$off> loff<$loff>\n";
1084 return ($statement, $condition,
1085 $line, $remain + 1, $off - $loff + 1, $level);
1088 sub statement_lines {
1091 # Strip the diff line prefixes and rip blank lines at start and end.
1092 $stmt =~ s/(^|\n)./$1/g;
1096 my @stmt_lines = ($stmt =~ /\n/g);
1098 return $#stmt_lines + 2;
1101 sub statement_rawlines {
1104 my @stmt_lines = ($stmt =~ /\n/g);
1106 return $#stmt_lines + 2;
1109 sub statement_block_size {
1112 $stmt =~ s/(^|\n)./$1/g;
1118 my @stmt_lines = ($stmt =~ /\n/g);
1119 my @stmt_statements = ($stmt =~ /;/g);
1121 my $stmt_lines = $#stmt_lines + 2;
1122 my $stmt_statements = $#stmt_statements + 1;
1124 if ($stmt_lines > $stmt_statements) {
1127 return $stmt_statements;
1131 sub ctx_statement_full {
1132 my ($linenr, $remain, $off) = @_;
1133 my ($statement, $condition, $level);
1137 # Grab the first conditional/block pair.
1138 ($statement, $condition, $linenr, $remain, $off, $level) =
1139 ctx_statement_block($linenr, $remain, $off);
1140 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1141 push(@chunks, [ $condition, $statement ]);
1142 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1143 return ($level, $linenr, @chunks);
1146 # Pull in the following conditional/block pairs and see if they
1147 # could continue the statement.
1149 ($statement, $condition, $linenr, $remain, $off, $level) =
1150 ctx_statement_block($linenr, $remain, $off);
1151 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1152 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1154 push(@chunks, [ $condition, $statement ]);
1157 return ($level, $linenr, @chunks);
1161 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1163 my $start = $linenr - 1;
1170 my @stack = ($level);
1171 for ($line = $start; $remain > 0; $line++) {
1172 next if ($rawlines[$line] =~ /^-/);
1175 $blk .= $rawlines[$line];
1177 # Handle nested #if/#else.
1178 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1179 push(@stack, $level);
1180 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1181 $level = $stack[$#stack - 1];
1182 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1183 $level = pop(@stack);
1186 foreach my $c (split(//, $lines[$line])) {
1187 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1193 if ($c eq $close && $level > 0) {
1195 last if ($level == 0);
1196 } elsif ($c eq $open) {
1201 if (!$outer || $level <= 1) {
1202 push(@res, $rawlines[$line]);
1205 last if ($level == 0);
1208 return ($level, @res);
1210 sub ctx_block_outer {
1211 my ($linenr, $remain) = @_;
1213 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1217 my ($linenr, $remain) = @_;
1219 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1223 my ($linenr, $remain, $off) = @_;
1225 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1228 sub ctx_block_level {
1229 my ($linenr, $remain) = @_;
1231 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1233 sub ctx_statement_level {
1234 my ($linenr, $remain, $off) = @_;
1236 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1239 sub ctx_locate_comment {
1240 my ($first_line, $end_line) = @_;
1242 # Catch a comment on the end of the line itself.
1243 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1244 return $current_comment if (defined $current_comment);
1246 # Look through the context and try and figure out if there is a
1249 $current_comment = '';
1250 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1251 my $line = $rawlines[$linenr - 1];
1253 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1256 if ($line =~ m@/\*@) {
1259 if (!$in_comment && $current_comment ne '') {
1260 $current_comment = '';
1262 $current_comment .= $line . "\n" if ($in_comment);
1263 if ($line =~ m@\*/@) {
1268 chomp($current_comment);
1269 return($current_comment);
1271 sub ctx_has_comment {
1272 my ($first_line, $end_line) = @_;
1273 my $cmt = ctx_locate_comment($first_line, $end_line);
1275 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1276 ##print "CMMT: $cmt\n";
1278 return ($cmt ne '');
1282 my ($linenr, $cnt) = @_;
1284 my $offset = $linenr - 1;
1289 $line = $rawlines[$offset++];
1290 next if (defined($line) && $line =~ /^-/);
1302 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1305 $coded = sprintf("^%c", unpack('C', $2) + 64);
1314 my $av_preprocessor = 0;
1319 sub annotate_reset {
1320 $av_preprocessor = 0;
1322 @av_paren_type = ('E');
1323 $av_pend_colon = 'O';
1326 sub annotate_values {
1327 my ($stream, $type) = @_;
1330 my $var = '_' x length($stream);
1333 print "$stream\n" if ($dbg_values > 1);
1335 while (length($cur)) {
1336 @av_paren_type = ('E') if ($#av_paren_type < 0);
1337 print " <" . join('', @av_paren_type) .
1338 "> <$type> <$av_pending>" if ($dbg_values > 1);
1339 if ($cur =~ /^(\s+)/o) {
1340 print "WS($1)\n" if ($dbg_values > 1);
1341 if ($1 =~ /\n/ && $av_preprocessor) {
1342 $type = pop(@av_paren_type);
1343 $av_preprocessor = 0;
1346 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1347 print "CAST($1)\n" if ($dbg_values > 1);
1348 push(@av_paren_type, $type);
1351 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1352 print "DECLARE($1)\n" if ($dbg_values > 1);
1355 } elsif ($cur =~ /^($Modifier)\s*/) {
1356 print "MODIFIER($1)\n" if ($dbg_values > 1);
1359 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1360 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1361 $av_preprocessor = 1;
1362 push(@av_paren_type, $type);
1368 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1369 print "UNDEF($1)\n" if ($dbg_values > 1);
1370 $av_preprocessor = 1;
1371 push(@av_paren_type, $type);
1373 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1374 print "PRE_START($1)\n" if ($dbg_values > 1);
1375 $av_preprocessor = 1;
1377 push(@av_paren_type, $type);
1378 push(@av_paren_type, $type);
1381 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1382 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1383 $av_preprocessor = 1;
1385 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1389 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1390 print "PRE_END($1)\n" if ($dbg_values > 1);
1392 $av_preprocessor = 1;
1394 # Assume all arms of the conditional end as this
1395 # one does, and continue as if the #endif was not here.
1396 pop(@av_paren_type);
1397 push(@av_paren_type, $type);
1400 } elsif ($cur =~ /^(\\\n)/o) {
1401 print "PRECONT($1)\n" if ($dbg_values > 1);
1403 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1404 print "ATTR($1)\n" if ($dbg_values > 1);
1405 $av_pending = $type;
1408 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1409 print "SIZEOF($1)\n" if ($dbg_values > 1);
1415 } elsif ($cur =~ /^(if|while|for)\b/o) {
1416 print "COND($1)\n" if ($dbg_values > 1);
1420 } elsif ($cur =~/^(case)/o) {
1421 print "CASE($1)\n" if ($dbg_values > 1);
1422 $av_pend_colon = 'C';
1425 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1426 print "KEYWORD($1)\n" if ($dbg_values > 1);
1429 } elsif ($cur =~ /^(\()/o) {
1430 print "PAREN('$1')\n" if ($dbg_values > 1);
1431 push(@av_paren_type, $av_pending);
1435 } elsif ($cur =~ /^(\))/o) {
1436 my $new_type = pop(@av_paren_type);
1437 if ($new_type ne '_') {
1439 print "PAREN('$1') -> $type\n"
1440 if ($dbg_values > 1);
1442 print "PAREN('$1')\n" if ($dbg_values > 1);
1445 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1446 print "FUNC($1)\n" if ($dbg_values > 1);
1450 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1451 if (defined $2 && $type eq 'C' || $type eq 'T') {
1452 $av_pend_colon = 'B';
1453 } elsif ($type eq 'E') {
1454 $av_pend_colon = 'L';
1456 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1459 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1460 print "IDENT($1)\n" if ($dbg_values > 1);
1463 } elsif ($cur =~ /^($Assignment)/o) {
1464 print "ASSIGN($1)\n" if ($dbg_values > 1);
1467 } elsif ($cur =~/^(;|{|})/) {
1468 print "END($1)\n" if ($dbg_values > 1);
1470 $av_pend_colon = 'O';
1472 } elsif ($cur =~/^(,)/) {
1473 print "COMMA($1)\n" if ($dbg_values > 1);
1476 } elsif ($cur =~ /^(\?)/o) {
1477 print "QUESTION($1)\n" if ($dbg_values > 1);
1480 } elsif ($cur =~ /^(:)/o) {
1481 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1483 substr($var, length($res), 1, $av_pend_colon);
1484 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1489 $av_pend_colon = 'O';
1491 } elsif ($cur =~ /^(\[)/o) {
1492 print "CLOSE($1)\n" if ($dbg_values > 1);
1495 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1498 print "OPV($1)\n" if ($dbg_values > 1);
1505 substr($var, length($res), 1, $variant);
1508 } elsif ($cur =~ /^($Operators)/o) {
1509 print "OP($1)\n" if ($dbg_values > 1);
1510 if ($1 ne '++' && $1 ne '--') {
1514 } elsif ($cur =~ /(^.)/o) {
1515 print "C($1)\n" if ($dbg_values > 1);
1518 $cur = substr($cur, length($1));
1519 $res .= $type x length($1);
1523 return ($res, $var);
1527 my ($possible, $line) = @_;
1528 my $notPermitted = qr{(?:
1545 ^(?:typedef|struct|enum)\b
1547 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1548 if ($possible !~ $notPermitted) {
1549 # Check for modifiers.
1550 $possible =~ s/\s*$Storage\s*//g;
1551 $possible =~ s/\s*$Sparse\s*//g;
1552 if ($possible =~ /^\s*$/) {
1554 } elsif ($possible =~ /\s/) {
1555 $possible =~ s/\s*$Type\s*//g;
1556 for my $modifier (split(' ', $possible)) {
1557 if ($modifier !~ $notPermitted) {
1558 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1559 push(@modifierList, $modifier);
1564 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1565 push(@typeList, $possible);
1569 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1578 return defined $use_type{$type} if (scalar keys %use_type > 0);
1580 return !defined $ignore_type{$type};
1584 my ($level, $type, $msg) = @_;
1586 if (!show_type($type) ||
1587 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1592 $line = "$prefix$level:$type: $msg\n";
1594 $line = "$prefix$level: $msg\n";
1596 $line = (split('\n', $line))[0] . "\n" if ($terse);
1598 push(our @report, $line);
1607 sub fixup_current_range {
1608 my ($lineRef, $offset, $length) = @_;
1610 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1613 my $no = $o + $offset;
1614 my $nl = $l + $length;
1615 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1619 sub fix_inserted_deleted_lines {
1620 my ($linesRef, $insertedRef, $deletedRef) = @_;
1622 my $range_last_linenr = 0;
1623 my $delta_offset = 0;
1628 my $next_insert = 0;
1629 my $next_delete = 0;
1633 my $inserted = @{$insertedRef}[$next_insert++];
1634 my $deleted = @{$deletedRef}[$next_delete++];
1636 foreach my $old_line (@{$linesRef}) {
1638 my $line = $old_line; #don't modify the array
1639 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1641 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1642 $range_last_linenr = $new_linenr;
1643 fixup_current_range(\$line, $delta_offset, 0);
1646 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1647 $deleted = @{$deletedRef}[$next_delete++];
1649 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1652 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1653 push(@lines, ${$inserted}{'LINE'});
1654 $inserted = @{$insertedRef}[$next_insert++];
1656 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1660 push(@lines, $line);
1670 sub fix_insert_line {
1671 my ($linenr, $line) = @_;
1677 push(@fixed_inserted, $inserted);
1680 sub fix_delete_line {
1681 my ($linenr, $line) = @_;
1688 push(@fixed_deleted, $deleted);
1692 my ($type, $msg) = @_;
1694 if (report("ERROR", $type, $msg)) {
1702 my ($type, $msg) = @_;
1704 if (report("WARNING", $type, $msg)) {
1712 my ($type, $msg) = @_;
1714 if ($check && report("CHECK", $type, $msg)) {
1722 sub check_absolute_file {
1723 my ($absolute, $herecurr) = @_;
1724 my $file = $absolute;
1726 ##print "absolute<$absolute>\n";
1728 # See if any suffix of this path is a path within the tree.
1729 while ($file =~ s@^[^/]*/@@) {
1730 if (-f "$root/$file") {
1731 ##print "file<$file>\n";
1739 # It is, so see if the prefix is acceptable.
1740 my $prefix = $absolute;
1741 substr($prefix, -length($file)) = '';
1743 ##print "prefix<$prefix>\n";
1744 if ($prefix ne ".../") {
1745 WARN("USE_RELATIVE_PATH",
1746 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1753 $string =~ s/^\s+|\s+$//g;
1761 $string =~ s/^\s+//;
1769 $string =~ s/\s+$//;
1774 sub string_find_replace {
1775 my ($string, $find, $replace) = @_;
1777 $string =~ s/$find/$replace/g;
1785 my $source_indent = 8;
1786 my $max_spaces_before_tab = $source_indent - 1;
1787 my $spaces_to_tab = " " x $source_indent;
1789 #convert leading spaces to tabs
1790 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1791 #Remove spaces before a tab
1792 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1797 sub pos_last_openparen {
1802 my $opens = $line =~ tr/\(/\(/;
1803 my $closes = $line =~ tr/\)/\)/;
1805 my $last_openparen = 0;
1807 if (($opens == 0) || ($closes >= $opens)) {
1811 my $len = length($line);
1813 for ($pos = 0; $pos < $len; $pos++) {
1814 my $string = substr($line, $pos);
1815 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1816 $pos += length($1) - 1;
1817 } elsif (substr($line, $pos, 1) eq '(') {
1818 $last_openparen = $pos;
1819 } elsif (index($string, '(') == -1) {
1824 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1828 my $filename = shift;
1834 my $stashrawline="";
1845 my $in_header_lines = $file ? 0 : 1;
1846 my $in_commit_log = 0; #Scanning lines before patch
1847 my $reported_maintainer_file = 0;
1848 my $non_utf8_charset = 0;
1850 my $last_blank_line = 0;
1851 my $last_coalesced_string_linenr = -1;
1859 # Trace the real file/line as we go.
1865 my $comment_edge = 0;
1869 my $prev_values = 'E';
1872 my %suppress_ifbraces;
1873 my %suppress_whiletrailers;
1874 my %suppress_export;
1875 my $suppress_statement = 0;
1877 my %signatures = ();
1879 # Pre-scan the patch sanitizing the lines.
1880 # Pre-scan the patch looking for any __setup documentation.
1882 my @setup_docs = ();
1885 my $camelcase_file_seeded = 0;
1887 sanitise_line_reset();
1889 foreach my $rawline (@rawlines) {
1893 push(@fixed, $rawline) if ($fix);
1895 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1897 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1902 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1911 # Guestimate if this is a continuing comment. Run
1912 # the context looking for a comment "edge". If this
1913 # edge is a close comment then we must be in a comment
1917 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1918 next if (defined $rawlines[$ln - 1] &&
1919 $rawlines[$ln - 1] =~ /^-/);
1921 #print "RAW<$rawlines[$ln - 1]>\n";
1922 last if (!defined $rawlines[$ln - 1]);
1923 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1924 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1929 if (defined $edge && $edge eq '*/') {
1933 # Guestimate if this is a continuing comment. If this
1934 # is the start of a diff block and this line starts
1935 # ' *' then it is very likely a comment.
1936 if (!defined $edge &&
1937 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1942 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1943 sanitise_line_reset($in_comment);
1945 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1946 # Standardise the strings and chars within the input to
1947 # simplify matching -- only bother with positive lines.
1948 $line = sanitise_line($rawline);
1950 push(@lines, $line);
1953 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1958 #print "==>$rawline\n";
1959 #print "-->$line\n";
1961 if ($setup_docs && $line =~ /^\+/) {
1962 push(@setup_docs, $line);
1971 foreach my $line (@lines) {
1974 my $sline = $line; #copy of $line
1975 $sline =~ s/$;/ /g; #with comments as spaces
1977 my $rawline = $rawlines[$linenr - 1];
1979 #extract the line range in the file after the patch is applied
1980 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1982 $first_line = $linenr + 1;
1992 %suppress_ifbraces = ();
1993 %suppress_whiletrailers = ();
1994 %suppress_export = ();
1995 $suppress_statement = 0;
1998 # track the line number as we move through the hunk, note that
1999 # new versions of GNU diff omit the leading space on completely
2000 # blank context lines so we need to count that too.
2001 } elsif ($line =~ /^( |\+|$)/) {
2003 $realcnt-- if ($realcnt != 0);
2005 # Measure the line length and indent.
2006 ($length, $indent) = line_stats($rawline);
2008 # Track the previous line.
2009 ($prevline, $stashline) = ($stashline, $line);
2010 ($previndent, $stashindent) = ($stashindent, $indent);
2011 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2013 #warn "line<$line>\n";
2015 } elsif ($realcnt == 1) {
2019 my $hunk_line = ($realcnt != 0);
2021 #make up the handle for any error we report on this line
2022 $prefix = "$filename:$realline: " if ($emacs && $file);
2023 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2025 $here = "#$linenr: " if (!$file);
2026 $here = "#$realline: " if ($file);
2029 # extract the filename as it passes
2030 if ($line =~ /^diff --git.*?(\S+)$/) {
2032 $realfile =~ s@^([^/]*)/@@ if (!$file);
2035 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2037 $realfile =~ s@^([^/]*)/@@ if (!$file);
2041 if (!$file && $tree && $p1_prefix ne '' &&
2042 -e "$root/$p1_prefix") {
2043 WARN("PATCH_PREFIX",
2044 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2047 if ($realfile =~ m@^include/asm/@) {
2048 ERROR("MODIFIED_INCLUDE_ASM",
2049 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2055 if ($realfile =~ m@^(drivers/net/|net/)@) {
2058 $check = $check_orig;
2063 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2065 my $hereline = "$here\n$rawline\n";
2066 my $herecurr = "$here\n$rawline\n";
2067 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2069 $cnt_lines++ if ($realcnt != 0);
2071 # Check for incorrect file permissions
2072 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2073 my $permhere = $here . "FILE: $realfile\n";
2074 if ($realfile !~ m@scripts/@ &&
2075 $realfile !~ /\.(py|pl|awk|sh)$/) {
2076 ERROR("EXECUTE_PERMISSIONS",
2077 "do not set execute permissions for source files\n" . $permhere);
2081 # Check the patch for a signoff:
2082 if ($line =~ /^\s*signed-off-by:/i) {
2087 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2088 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2089 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2090 $reported_maintainer_file = 1;
2093 # Check signature styles
2094 if (!$in_header_lines &&
2095 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2096 my $space_before = $1;
2098 my $space_after = $3;
2100 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2102 if ($sign_off !~ /$signature_tags/) {
2103 WARN("BAD_SIGN_OFF",
2104 "Non-standard signature: $sign_off\n" . $herecurr);
2106 if (defined $space_before && $space_before ne "") {
2107 if (WARN("BAD_SIGN_OFF",
2108 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2110 $fixed[$fixlinenr] =
2111 "$ucfirst_sign_off $email";
2114 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2115 if (WARN("BAD_SIGN_OFF",
2116 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2118 $fixed[$fixlinenr] =
2119 "$ucfirst_sign_off $email";
2123 if (!defined $space_after || $space_after ne " ") {
2124 if (WARN("BAD_SIGN_OFF",
2125 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2127 $fixed[$fixlinenr] =
2128 "$ucfirst_sign_off $email";
2132 my ($email_name, $email_address, $comment) = parse_email($email);
2133 my $suggested_email = format_email(($email_name, $email_address));
2134 if ($suggested_email eq "") {
2135 ERROR("BAD_SIGN_OFF",
2136 "Unrecognized email address: '$email'\n" . $herecurr);
2138 my $dequoted = $suggested_email;
2139 $dequoted =~ s/^"//;
2140 $dequoted =~ s/" </ </;
2141 # Don't force email to have quotes
2142 # Allow just an angle bracketed address
2143 if ("$dequoted$comment" ne $email &&
2144 "<$email_address>$comment" ne $email &&
2145 "$suggested_email$comment" ne $email) {
2146 WARN("BAD_SIGN_OFF",
2147 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2151 # Check for duplicate signatures
2152 my $sig_nospace = $line;
2153 $sig_nospace =~ s/\s//g;
2154 $sig_nospace = lc($sig_nospace);
2155 if (defined $signatures{$sig_nospace}) {
2156 WARN("BAD_SIGN_OFF",
2157 "Duplicate signature\n" . $herecurr);
2159 $signatures{$sig_nospace} = 1;
2163 # Check for old stable address
2164 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2165 ERROR("STABLE_ADDRESS",
2166 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2169 # Check for unwanted Gerrit info
2170 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2171 ERROR("GERRIT_CHANGE_ID",
2172 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2175 # Check for improperly formed commit descriptions
2176 if ($in_commit_log &&
2177 $line =~ /\bcommit\s+[0-9a-f]{5,}/i &&
2178 !($line =~ /\b[Cc]ommit [0-9a-f]{12,40} \("/ ||
2179 ($line =~ /\b[Cc]ommit [0-9a-f]{12,40}\s*$/ &&
2180 defined $rawlines[$linenr] &&
2181 $rawlines[$linenr] =~ /^\s*\("/))) {
2182 $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i;
2184 my $orig_commit = lc($2);
2185 my $id = '01234567890ab';
2186 my $desc = 'commit description';
2187 ($id, $desc) = git_commit_info($orig_commit, $id, $desc);
2188 ERROR("GIT_COMMIT_ID",
2189 "Please use 12 or more chars for the git commit ID like: '${init_char}ommit $id (\"$desc\")'\n" . $herecurr);
2192 # Check for added, moved or deleted files
2193 if (!$reported_maintainer_file && !$in_commit_log &&
2194 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2195 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2196 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2197 (defined($1) || defined($2))))) {
2198 $reported_maintainer_file = 1;
2199 WARN("FILE_PATH_CHANGES",
2200 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2203 # Check for wrappage within a valid hunk of the file
2204 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2205 ERROR("CORRUPTED_PATCH",
2206 "patch seems to be corrupt (line wrapped?)\n" .
2207 $herecurr) if (!$emitted_corrupt++);
2210 # Check for absolute kernel paths.
2212 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2215 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2216 check_absolute_file($1, $herecurr)) {
2219 check_absolute_file($file, $herecurr);
2224 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2225 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2226 $rawline !~ m/^$UTF8*$/) {
2227 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2229 my $blank = copy_spacing($rawline);
2230 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2231 my $hereptr = "$hereline$ptr\n";
2234 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2237 # Check if it's the start of a commit log
2238 # (not a header line and we haven't seen the patch filename)
2239 if ($in_header_lines && $realfile =~ /^$/ &&
2240 !($rawline =~ /^\s+\S/ ||
2241 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2242 $in_header_lines = 0;
2246 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2247 # declined it, i.e defined some charset where it is missing.
2248 if ($in_header_lines &&
2249 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2251 $non_utf8_charset = 1;
2254 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2255 $rawline =~ /$NON_ASCII_UTF8/) {
2256 WARN("UTF8_BEFORE_PATCH",
2257 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2260 # Check for various typo / spelling mistakes
2261 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2262 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2264 my $typo_fix = $spelling_fix{lc($typo)};
2265 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2266 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2267 my $msg_type = \&WARN;
2268 $msg_type = \&CHK if ($file);
2269 if (&{$msg_type}("TYPO_SPELLING",
2270 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2272 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2277 # ignore non-hunk lines and lines being removed
2278 next if (!$hunk_line || $line =~ /^-/);
2280 #trailing whitespace
2281 if ($line =~ /^\+.*\015/) {
2282 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2283 if (ERROR("DOS_LINE_ENDINGS",
2284 "DOS line endings\n" . $herevet) &&
2286 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2288 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2289 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2290 if (ERROR("TRAILING_WHITESPACE",
2291 "trailing whitespace\n" . $herevet) &&
2293 $fixed[$fixlinenr] =~ s/\s+$//;
2299 # Check for FSF mailing addresses.
2300 if ($rawline =~ /\bwrite to the Free/i ||
2301 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2302 $rawline =~ /\b51\s+Franklin\s+St/i) {
2303 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2304 my $msg_type = \&ERROR;
2305 $msg_type = \&CHK if ($file);
2306 &{$msg_type}("FSF_MAILING_ADDRESS",
2307 "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)
2310 # check for Kconfig help text having a real description
2311 # Only applies when adding the entry originally, after that we do not have
2312 # sufficient context to determine whether it is indeed long enough.
2313 if ($realfile =~ /Kconfig/ &&
2314 $line =~ /^\+\s*config\s+/) {
2317 my $ln = $linenr + 1;
2321 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2322 $f = $lines[$ln - 1];
2323 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2324 $is_end = $lines[$ln - 1] =~ /^\+/;
2326 next if ($f =~ /^-/);
2327 last if (!$file && $f =~ /^\@\@/);
2329 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2331 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2338 next if ($f =~ /^$/);
2339 if ($f =~ /^\s*config\s/) {
2345 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2346 WARN("CONFIG_DESCRIPTION",
2347 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2349 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2352 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2353 if ($realfile =~ /Kconfig/ &&
2354 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2355 WARN("CONFIG_EXPERIMENTAL",
2356 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2359 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2360 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2363 'EXTRA_AFLAGS' => 'asflags-y',
2364 'EXTRA_CFLAGS' => 'ccflags-y',
2365 'EXTRA_CPPFLAGS' => 'cppflags-y',
2366 'EXTRA_LDFLAGS' => 'ldflags-y',
2369 WARN("DEPRECATED_VARIABLE",
2370 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2373 # check for DT compatible documentation
2374 if (defined $root &&
2375 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2376 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2378 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2380 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2381 my $vp_file = $dt_path . "vendor-prefixes.txt";
2383 foreach my $compat (@compats) {
2384 my $compat2 = $compat;
2385 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2386 my $compat3 = $compat;
2387 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2388 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2390 WARN("UNDOCUMENTED_DT_STRING",
2391 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2394 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2396 `grep -Eq "^$vendor\\b" $vp_file`;
2398 WARN("UNDOCUMENTED_DT_STRING",
2399 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2404 # check we are in a valid source file if not then ignore this hunk
2405 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2408 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2409 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2410 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2411 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2412 $length > $max_line_length)
2415 "line over $max_line_length characters\n" . $herecurr);
2418 # check for adding lines without a newline.
2419 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2420 WARN("MISSING_EOF_NEWLINE",
2421 "adding a line without newline at end of file\n" . $herecurr);
2424 # Blackfin: use hi/lo macros
2425 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2426 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2427 my $herevet = "$here\n" . cat_vet($line) . "\n";
2429 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2431 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2432 my $herevet = "$here\n" . cat_vet($line) . "\n";
2434 "use the HI() macro, not (... >> 16)\n" . $herevet);
2438 # check we are in a valid source file C or perl if not then ignore this hunk
2439 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2441 # at the beginning of a line any tabs must come first and anything
2442 # more than 8 must use tabs.
2443 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2444 $rawline =~ /^\+\s* \s*/) {
2445 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2447 if (ERROR("CODE_INDENT",
2448 "code indent should use tabs where possible\n" . $herevet) &&
2450 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2454 # check for space before tabs.
2455 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2456 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2457 if (WARN("SPACE_BEFORE_TAB",
2458 "please, no space before tabs\n" . $herevet) &&
2460 while ($fixed[$fixlinenr] =~
2461 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2462 while ($fixed[$fixlinenr] =~
2463 s/(^\+.*) +\t/$1\t/) {}
2467 # check for && or || at the start of a line
2468 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2469 CHK("LOGICAL_CONTINUATIONS",
2470 "Logical continuations should be on the previous line\n" . $hereprev);
2473 # check multi-line statement indentation matches previous line
2474 if ($^V && $^V ge 5.10.0 &&
2475 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2476 $prevline =~ /^\+(\t*)(.*)$/;
2480 my $pos = pos_last_openparen($rest);
2482 $line =~ /^(\+| )([ \t]*)/;
2485 my $goodtabindent = $oldindent .
2488 my $goodspaceindent = $oldindent . " " x $pos;
2490 if ($newindent ne $goodtabindent &&
2491 $newindent ne $goodspaceindent) {
2493 if (CHK("PARENTHESIS_ALIGNMENT",
2494 "Alignment should match open parenthesis\n" . $hereprev) &&
2495 $fix && $line =~ /^\+/) {
2496 $fixed[$fixlinenr] =~
2497 s/^\+[ \t]*/\+$goodtabindent/;
2503 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;\({\[\<\>])/ &&
2504 (!defined($1) || $1 !~ /sizeof\s*/)) {
2506 "No space is necessary after a cast\n" . $herecurr) &&
2508 $fixed[$fixlinenr] =~
2509 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2513 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2514 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2515 $rawline =~ /^\+[ \t]*\*/ &&
2517 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2518 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2521 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2522 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2523 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2524 $rawline =~ /^\+/ && #line is new
2525 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2526 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2527 "networking block comments start with * on subsequent lines\n" . $hereprev);
2530 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2531 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2532 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2533 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2534 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2535 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2536 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2539 # check for missing blank lines after struct/union declarations
2540 # with exceptions for various attributes and macros
2541 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2543 !($line =~ /^\+\s*$/ ||
2544 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2545 $line =~ /^\+\s*MODULE_/i ||
2546 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2547 $line =~ /^\+[a-z_]*init/ ||
2548 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2549 $line =~ /^\+\s*DECLARE/ ||
2550 $line =~ /^\+\s*__setup/)) {
2551 if (CHK("LINE_SPACING",
2552 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2554 fix_insert_line($fixlinenr, "\+");
2558 # check for multiple consecutive blank lines
2559 if ($prevline =~ /^[\+ ]\s*$/ &&
2560 $line =~ /^\+\s*$/ &&
2561 $last_blank_line != ($linenr - 1)) {
2562 if (CHK("LINE_SPACING",
2563 "Please don't use multiple blank lines\n" . $hereprev) &&
2565 fix_delete_line($fixlinenr, $rawline);
2568 $last_blank_line = $linenr;
2571 # check for missing blank lines after declarations
2572 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2573 # actual declarations
2574 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2575 # function pointer declarations
2576 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2577 # foo bar; where foo is some local typedef or #define
2578 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2579 # known declaration macros
2580 $prevline =~ /^\+\s+$declaration_macros/) &&
2581 # for "else if" which can look like "$Ident $Ident"
2582 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2583 # other possible extensions of declaration lines
2584 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2585 # not starting a section or a macro "\" extended line
2586 $prevline =~ /(?:\{\s*|\\)$/) &&
2587 # looks like a declaration
2588 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2589 # function pointer declarations
2590 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2591 # foo bar; where foo is some local typedef or #define
2592 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2593 # known declaration macros
2594 $sline =~ /^\+\s+$declaration_macros/ ||
2595 # start of struct or union or enum
2596 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2597 # start or end of block or continuation of declaration
2598 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2599 # bitfield continuation
2600 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2601 # other possible extensions of declaration lines
2602 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2603 # indentation of previous and current line are the same
2604 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2605 if (WARN("LINE_SPACING",
2606 "Missing a blank line after declarations\n" . $hereprev) &&
2608 fix_insert_line($fixlinenr, "\+");
2612 # check for spaces at the beginning of a line.
2614 # 1) within comments
2615 # 2) indented preprocessor commands
2617 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2618 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2619 if (WARN("LEADING_SPACE",
2620 "please, no spaces at the start of a line\n" . $herevet) &&
2622 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2626 # check we are in a valid C source file if not then ignore this hunk
2627 next if ($realfile !~ /\.(h|c)$/);
2629 # check indentation of any line with a bare else
2630 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2631 # if the previous line is a break or return and is indented 1 tab more...
2632 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2633 my $tabs = length($1) + 1;
2634 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2635 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2636 defined $lines[$linenr] &&
2637 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2638 WARN("UNNECESSARY_ELSE",
2639 "else is not generally useful after a break or return\n" . $hereprev);
2643 # check indentation of a line with a break;
2644 # if the previous line is a goto or return and is indented the same # of tabs
2645 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2647 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2648 WARN("UNNECESSARY_BREAK",
2649 "break is not useful after a goto or return\n" . $hereprev);
2653 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2654 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2655 WARN("CONFIG_EXPERIMENTAL",
2656 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2659 # check for RCS/CVS revision markers
2660 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2662 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2665 # Blackfin: don't use __builtin_bfin_[cs]sync
2666 if ($line =~ /__builtin_bfin_csync/) {
2667 my $herevet = "$here\n" . cat_vet($line) . "\n";
2669 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2671 if ($line =~ /__builtin_bfin_ssync/) {
2672 my $herevet = "$here\n" . cat_vet($line) . "\n";
2674 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2677 # check for old HOTPLUG __dev<foo> section markings
2678 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2679 WARN("HOTPLUG_SECTION",
2680 "Using $1 is unnecessary\n" . $herecurr);
2683 # Check for potential 'bare' types
2684 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2686 #print "LINE<$line>\n";
2687 if ($linenr >= $suppress_statement &&
2688 $realcnt && $sline =~ /.\s*\S/) {
2689 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2690 ctx_statement_block($linenr, $realcnt, 0);
2691 $stat =~ s/\n./\n /g;
2692 $cond =~ s/\n./\n /g;
2694 #print "linenr<$linenr> <$stat>\n";
2695 # If this statement has no statement boundaries within
2696 # it there is no point in retrying a statement scan
2697 # until we hit end of it.
2698 my $frag = $stat; $frag =~ s/;+\s*$//;
2699 if ($frag !~ /(?:{|;)/) {
2700 #print "skip<$line_nr_next>\n";
2701 $suppress_statement = $line_nr_next;
2704 # Find the real next line.
2705 $realline_next = $line_nr_next;
2706 if (defined $realline_next &&
2707 (!defined $lines[$realline_next - 1] ||
2708 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2715 # Ignore goto labels.
2716 if ($s =~ /$Ident:\*$/s) {
2718 # Ignore functions being called
2719 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2721 } elsif ($s =~ /^.\s*else\b/s) {
2723 # declarations always start with types
2724 } 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) {
2727 possible($type, "A:" . $s);
2729 # definitions in global scope can only start with types
2730 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2731 possible($1, "B:" . $s);
2734 # any (foo ... *) is a pointer cast, and foo is a type
2735 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2736 possible($1, "C:" . $s);
2739 # Check for any sort of function declaration.
2740 # int foo(something bar, other baz);
2741 # void (*store_gdt)(x86_descr_ptr *);
2742 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2743 my ($name_len) = length($1);
2746 substr($ctx, 0, $name_len + 1, '');
2747 $ctx =~ s/\)[^\)]*$//;
2749 for my $arg (split(/\s*,\s*/, $ctx)) {
2750 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2752 possible($1, "D:" . $s);
2760 # Checks which may be anchored in the context.
2763 # Check for switch () and associated case and default
2764 # statements should be at the same indent.
2765 if ($line=~/\bswitch\s*\(.*\)/) {
2768 my @ctx = ctx_block_outer($linenr, $realcnt);
2770 for my $ctx (@ctx) {
2771 my ($clen, $cindent) = line_stats($ctx);
2772 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2773 $indent != $cindent) {
2774 $err .= "$sep$ctx\n";
2781 ERROR("SWITCH_CASE_INDENT_LEVEL",
2782 "switch and case should be at the same indent\n$hereline$err");
2786 # if/while/etc brace do not go on next line, unless defining a do while loop,
2787 # or if that brace on the next line is for something else
2788 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2789 my $pre_ctx = "$1$2";
2791 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2793 if ($line =~ /^\+\t{6,}/) {
2794 WARN("DEEP_INDENTATION",
2795 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2798 my $ctx_cnt = $realcnt - $#ctx - 1;
2799 my $ctx = join("\n", @ctx);
2801 my $ctx_ln = $linenr;
2802 my $ctx_skip = $realcnt;
2804 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2805 defined $lines[$ctx_ln - 1] &&
2806 $lines[$ctx_ln - 1] =~ /^-/)) {
2807 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2808 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2812 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2813 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2815 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2817 "that open brace { should be on the previous line\n" .
2818 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2820 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2821 $ctx =~ /\)\s*\;\s*$/ &&
2822 defined $lines[$ctx_ln - 1])
2824 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2825 if ($nindent > $indent) {
2826 WARN("TRAILING_SEMICOLON",
2827 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2828 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2833 # Check relative indent for conditionals and blocks.
2834 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2835 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2836 ctx_statement_block($linenr, $realcnt, 0)
2837 if (!defined $stat);
2838 my ($s, $c) = ($stat, $cond);
2840 substr($s, 0, length($c), '');
2842 # Make sure we remove the line prefixes as we have
2843 # none on the first line, and are going to readd them
2847 # Find out how long the conditional actually is.
2848 my @newlines = ($c =~ /\n/gs);
2849 my $cond_lines = 1 + $#newlines;
2851 # We want to check the first line inside the block
2852 # starting at the end of the conditional, so remove:
2853 # 1) any blank line termination
2854 # 2) any opening brace { on end of the line
2856 my $continuation = 0;
2858 $s =~ s/^.*\bdo\b//;
2860 if ($s =~ s/^\s*\\//) {
2863 if ($s =~ s/^\s*?\n//) {
2868 # Also ignore a loop construct at the end of a
2869 # preprocessor statement.
2870 if (($prevline =~ /^.\s*#\s*define\s/ ||
2871 $prevline =~ /\\\s*$/) && $continuation == 0) {
2877 while ($cond_ptr != $cond_lines) {
2878 $cond_ptr = $cond_lines;
2880 # If we see an #else/#elif then the code
2882 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2887 # 1) blank lines, they should be at 0,
2888 # 2) preprocessor lines, and
2890 if ($continuation ||
2892 $s =~ /^\s*#\s*?/ ||
2893 $s =~ /^\s*$Ident\s*:/) {
2894 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2895 if ($s =~ s/^.*?\n//) {
2901 my (undef, $sindent) = line_stats("+" . $s);
2902 my $stat_real = raw_line($linenr, $cond_lines);
2904 # Check if either of these lines are modified, else
2905 # this is not this patch's fault.
2906 if (!defined($stat_real) ||
2907 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2910 if (defined($stat_real) && $cond_lines > 1) {
2911 $stat_real = "[...]\n$stat_real";
2914 #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";
2916 if ($check && (($sindent % 8) != 0 ||
2917 ($sindent <= $indent && $s ne ''))) {
2918 WARN("SUSPECT_CODE_INDENT",
2919 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2923 # Track the 'values' across context and added lines.
2924 my $opline = $line; $opline =~ s/^./ /;
2925 my ($curr_values, $curr_vars) =
2926 annotate_values($opline . "\n", $prev_values);
2927 $curr_values = $prev_values . $curr_values;
2929 my $outline = $opline; $outline =~ s/\t/ /g;
2930 print "$linenr > .$outline\n";
2931 print "$linenr > $curr_values\n";
2932 print "$linenr > $curr_vars\n";
2934 $prev_values = substr($curr_values, -1);
2936 #ignore lines not being added
2937 next if ($line =~ /^[^\+]/);
2939 # TEST: allow direct testing of the type matcher.
2941 if ($line =~ /^.\s*$Declare\s*$/) {
2943 "TEST: is type\n" . $herecurr);
2944 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2945 ERROR("TEST_NOT_TYPE",
2946 "TEST: is not type ($1 is)\n". $herecurr);
2950 # TEST: allow direct testing of the attribute matcher.
2952 if ($line =~ /^.\s*$Modifier\s*$/) {
2954 "TEST: is attr\n" . $herecurr);
2955 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2956 ERROR("TEST_NOT_ATTR",
2957 "TEST: is not attr ($1 is)\n". $herecurr);
2962 # check for initialisation to aggregates open brace on the next line
2963 if ($line =~ /^.\s*{/ &&
2964 $prevline =~ /(?:^|[^=])=\s*$/) {
2965 if (ERROR("OPEN_BRACE",
2966 "that open brace { should be on the previous line\n" . $hereprev) &&
2967 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
2968 fix_delete_line($fixlinenr - 1, $prevrawline);
2969 fix_delete_line($fixlinenr, $rawline);
2970 my $fixedline = $prevrawline;
2971 $fixedline =~ s/\s*=\s*$/ = {/;
2972 fix_insert_line($fixlinenr, $fixedline);
2974 $fixedline =~ s/^(.\s*){\s*/$1/;
2975 fix_insert_line($fixlinenr, $fixedline);
2980 # Checks which are anchored on the added line.
2983 # check for malformed paths in #include statements (uses RAW line)
2984 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2986 if ($path =~ m{//}) {
2987 ERROR("MALFORMED_INCLUDE",
2988 "malformed #include filename\n" . $herecurr);
2990 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2991 ERROR("UAPI_INCLUDE",
2992 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2996 # no C99 // comments
2997 if ($line =~ m{//}) {
2998 if (ERROR("C99_COMMENTS",
2999 "do not use C99 // comments\n" . $herecurr) &&
3001 my $line = $fixed[$fixlinenr];
3002 if ($line =~ /\/\/(.*)$/) {
3003 my $comment = trim($1);
3004 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3008 # Remove C99 comments.
3010 $opline =~ s@//.*@@;
3012 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3013 # the whole statement.
3014 #print "APW <$lines[$realline_next - 1]>\n";
3015 if (defined $realline_next &&
3016 exists $lines[$realline_next - 1] &&
3017 !defined $suppress_export{$realline_next} &&
3018 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3019 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3020 # Handle definitions which produce identifiers with
3023 # EXPORT_SYMBOL(something_foo);
3025 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3026 $name =~ /^${Ident}_$2/) {
3027 #print "FOO C name<$name>\n";
3028 $suppress_export{$realline_next} = 1;
3030 } elsif ($stat !~ /(?:
3032 ^.DEFINE_$Ident\(\Q$name\E\)|
3033 ^.DECLARE_$Ident\(\Q$name\E\)|
3034 ^.LIST_HEAD\(\Q$name\E\)|
3035 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3036 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3038 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3039 $suppress_export{$realline_next} = 2;
3041 $suppress_export{$realline_next} = 1;
3044 if (!defined $suppress_export{$linenr} &&
3045 $prevline =~ /^.\s*$/ &&
3046 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3047 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3048 #print "FOO B <$lines[$linenr - 1]>\n";
3049 $suppress_export{$linenr} = 2;
3051 if (defined $suppress_export{$linenr} &&
3052 $suppress_export{$linenr} == 2) {
3053 WARN("EXPORT_SYMBOL",
3054 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3057 # check for global initialisers.
3058 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3059 if (ERROR("GLOBAL_INITIALISERS",
3060 "do not initialise globals to 0 or NULL\n" .
3063 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3066 # check for static initialisers.
3067 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3068 if (ERROR("INITIALISED_STATIC",
3069 "do not initialise statics to 0 or NULL\n" .
3072 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3076 # check for misordered declarations of char/short/int/long with signed/unsigned
3077 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3079 WARN("MISORDERED_TYPE",
3080 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3083 # check for static const char * arrays.
3084 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3085 WARN("STATIC_CONST_CHAR_ARRAY",
3086 "static const char * array should probably be static const char * const\n" .
3090 # check for static char foo[] = "bar" declarations.
3091 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3092 WARN("STATIC_CONST_CHAR_ARRAY",
3093 "static char array declaration should probably be static const char\n" .
3097 # check for non-global char *foo[] = {"bar", ...} declarations.
3098 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3099 WARN("STATIC_CONST_CHAR_ARRAY",
3100 "char * array declaration might be better as static const\n" .
3104 # check for function declarations without arguments like "int foo()"
3105 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3106 if (ERROR("FUNCTION_WITHOUT_ARGS",
3107 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3109 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3113 # check for uses of DEFINE_PCI_DEVICE_TABLE
3114 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3115 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3116 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3118 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3122 # check for new typedefs, only function parameters and sparse annotations
3124 if ($line =~ /\btypedef\s/ &&
3125 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3126 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3127 $line !~ /\b$typeTypedefs\b/ &&
3128 $line !~ /\b__bitwise(?:__|)\b/) {
3129 WARN("NEW_TYPEDEFS",
3130 "do not add new typedefs\n" . $herecurr);
3133 # * goes on variable not on type
3135 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3137 my ($ident, $from, $to) = ($1, $2, $2);
3139 # Should start with a space.
3140 $to =~ s/^(\S)/ $1/;
3141 # Should not end with a space.
3143 # '*'s should not have spaces between.
3144 while ($to =~ s/\*\s+\*/\*\*/) {
3147 ## print "1: from<$from> to<$to> ident<$ident>\n";
3149 if (ERROR("POINTER_LOCATION",
3150 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3152 my $sub_from = $ident;
3153 my $sub_to = $ident;
3154 $sub_to =~ s/\Q$from\E/$to/;
3155 $fixed[$fixlinenr] =~
3156 s@\Q$sub_from\E@$sub_to@;
3160 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3162 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3164 # Should start with a space.
3165 $to =~ s/^(\S)/ $1/;
3166 # Should not end with a space.
3168 # '*'s should not have spaces between.
3169 while ($to =~ s/\*\s+\*/\*\*/) {
3171 # Modifiers should have spaces.
3172 $to =~ s/(\b$Modifier$)/$1 /;
3174 ## print "2: from<$from> to<$to> ident<$ident>\n";
3175 if ($from ne $to && $ident !~ /^$Modifier$/) {
3176 if (ERROR("POINTER_LOCATION",
3177 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3180 my $sub_from = $match;
3181 my $sub_to = $match;
3182 $sub_to =~ s/\Q$from\E/$to/;
3183 $fixed[$fixlinenr] =~
3184 s@\Q$sub_from\E@$sub_to@;
3189 # # no BUG() or BUG_ON()
3190 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3191 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3192 # print "$herecurr";
3196 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3197 WARN("LINUX_VERSION_CODE",
3198 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3201 # check for uses of printk_ratelimit
3202 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3203 WARN("PRINTK_RATELIMITED",
3204 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3207 # printk should use KERN_* levels. Note that follow on printk's on the
3208 # same line do not need a level, so we use the current block context
3209 # to try and find and validate the current printk. In summary the current
3210 # printk includes all preceding printk's which have no newline on the end.
3211 # we assume the first bad printk is the one to report.
3212 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3214 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3215 #print "CHECK<$lines[$ln - 1]\n";
3216 # we have a preceding printk if it ends
3217 # with "\n" ignore it, else it is to blame
3218 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3219 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3226 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3227 "printk() should include KERN_ facility level\n" . $herecurr);
3231 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3233 my $level = lc($orig);
3234 $level = "warn" if ($level eq "warning");
3235 my $level2 = $level;
3236 $level2 = "dbg" if ($level eq "debug");
3237 WARN("PREFER_PR_LEVEL",
3238 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3241 if ($line =~ /\bpr_warning\s*\(/) {
3242 if (WARN("PREFER_PR_LEVEL",
3243 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3245 $fixed[$fixlinenr] =~
3246 s/\bpr_warning\b/pr_warn/;
3250 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3252 my $level = lc($orig);
3253 $level = "warn" if ($level eq "warning");
3254 $level = "dbg" if ($level eq "debug");
3255 WARN("PREFER_DEV_LEVEL",
3256 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3259 # function brace can't be on same line, except for #defines of do while,
3260 # or if closed on same line
3261 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3262 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3263 if (ERROR("OPEN_BRACE",
3264 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3266 fix_delete_line($fixlinenr, $rawline);
3267 my $fixed_line = $rawline;
3268 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3271 fix_insert_line($fixlinenr, ltrim($line1));
3272 fix_insert_line($fixlinenr, "\+{");
3273 if ($line2 !~ /^\s*$/) {
3274 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3279 # open braces for enum, union and struct go on the same line.
3280 if ($line =~ /^.\s*{/ &&
3281 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3282 if (ERROR("OPEN_BRACE",
3283 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3284 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3285 fix_delete_line($fixlinenr - 1, $prevrawline);
3286 fix_delete_line($fixlinenr, $rawline);
3287 my $fixedline = rtrim($prevrawline) . " {";
3288 fix_insert_line($fixlinenr, $fixedline);
3289 $fixedline = $rawline;
3290 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3291 if ($fixedline !~ /^\+\s*$/) {
3292 fix_insert_line($fixlinenr, $fixedline);
3297 # missing space after union, struct or enum definition
3298 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3300 "missing space after $1 definition\n" . $herecurr) &&
3302 $fixed[$fixlinenr] =~
3303 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3307 # Function pointer declarations
3308 # check spacing between type, funcptr, and args
3309 # canonical declaration is "type (*funcptr)(args...)"
3310 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3312 my $pre_pointer_space = $2;
3313 my $post_pointer_space = $3;
3315 my $post_funcname_space = $5;
3316 my $pre_args_space = $6;
3318 # the $Declare variable will capture all spaces after the type
3319 # so check it for a missing trailing missing space but pointer return types
3320 # don't need a space so don't warn for those.
3321 my $post_declare_space = "";
3322 if ($declare =~ /(\s+)$/) {
3323 $post_declare_space = $1;
3324 $declare = rtrim($declare);
3326 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3328 "missing space after return type\n" . $herecurr);
3329 $post_declare_space = " ";
3332 # unnecessary space "type (*funcptr)(args...)"
3333 # This test is not currently implemented because these declarations are
3335 # int foo(int bar, ...)
3336 # and this is form shouldn't/doesn't generate a checkpatch warning.
3338 # elsif ($declare =~ /\s{2,}$/) {
3340 # "Multiple spaces after return type\n" . $herecurr);
3343 # unnecessary space "type ( *funcptr)(args...)"
3344 if (defined $pre_pointer_space &&
3345 $pre_pointer_space =~ /^\s/) {
3347 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3350 # unnecessary space "type (* funcptr)(args...)"
3351 if (defined $post_pointer_space &&
3352 $post_pointer_space =~ /^\s/) {
3354 "Unnecessary space before function pointer name\n" . $herecurr);
3357 # unnecessary space "type (*funcptr )(args...)"
3358 if (defined $post_funcname_space &&
3359 $post_funcname_space =~ /^\s/) {
3361 "Unnecessary space after function pointer name\n" . $herecurr);
3364 # unnecessary space "type (*funcptr) (args...)"
3365 if (defined $pre_args_space &&
3366 $pre_args_space =~ /^\s/) {
3368 "Unnecessary space before function pointer arguments\n" . $herecurr);
3371 if (show_type("SPACING") && $fix) {
3372 $fixed[$fixlinenr] =~
3373 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3377 # check for spacing round square brackets; allowed:
3378 # 1. with a type on the left -- int [] a;
3379 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3380 # 3. inside a curly brace -- = { [0...10] = 5 }
3381 while ($line =~ /(.*?\s)\[/g) {
3382 my ($where, $prefix) = ($-[1], $1);
3383 if ($prefix !~ /$Type\s+$/ &&
3384 ($where != 0 || $prefix !~ /^.\s+$/) &&
3385 $prefix !~ /[{,]\s+$/) {
3386 if (ERROR("BRACKET_SPACE",
3387 "space prohibited before open square bracket '['\n" . $herecurr) &&
3389 $fixed[$fixlinenr] =~
3390 s/^(\+.*?)\s+\[/$1\[/;
3395 # check for spaces between functions and their parentheses.
3396 while ($line =~ /($Ident)\s+\(/g) {
3398 my $ctx_before = substr($line, 0, $-[1]);
3399 my $ctx = "$ctx_before$name";
3401 # Ignore those directives where spaces _are_ permitted.
3403 if|for|while|switch|return|case|
3404 volatile|__volatile__|
3405 __attribute__|format|__extension__|
3408 # cpp #define statements have non-optional spaces, ie
3409 # if there is a space between the name and the open
3410 # parenthesis it is simply not a parameter group.
3411 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3413 # cpp #elif statement condition may start with a (
3414 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3416 # If this whole things ends with a type its most
3417 # likely a typedef for a function.
3418 } elsif ($ctx =~ /$Type$/) {
3422 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3424 $fixed[$fixlinenr] =~
3425 s/\b$name\s+\(/$name\(/;
3430 # Check operator spacing.
3431 if (!($line=~/\#\s*include/)) {
3432 my $fixed_line = "";
3436 <<=|>>=|<=|>=|==|!=|
3437 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3438 =>|->|<<|>>|<|>|=|!|~|
3439 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3442 my @elements = split(/($ops|;)/, $opline);
3444 ## print("element count: <" . $#elements . ">\n");
3445 ## foreach my $el (@elements) {
3446 ## print("el: <$el>\n");
3449 my @fix_elements = ();
3452 foreach my $el (@elements) {
3453 push(@fix_elements, substr($rawline, $off, length($el)));
3454 $off += length($el);
3459 my $blank = copy_spacing($opline);
3460 my $last_after = -1;
3462 for (my $n = 0; $n < $#elements; $n += 2) {
3464 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3466 ## print("n: <$n> good: <$good>\n");
3468 $off += length($elements[$n]);
3470 # Pick up the preceding and succeeding characters.
3471 my $ca = substr($opline, 0, $off);
3473 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3474 $cc = substr($opline, $off + length($elements[$n + 1]));
3476 my $cb = "$ca$;$cc";
3479 $a = 'V' if ($elements[$n] ne '');
3480 $a = 'W' if ($elements[$n] =~ /\s$/);
3481 $a = 'C' if ($elements[$n] =~ /$;$/);
3482 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3483 $a = 'O' if ($elements[$n] eq '');
3484 $a = 'E' if ($ca =~ /^\s*$/);
3486 my $op = $elements[$n + 1];
3489 if (defined $elements[$n + 2]) {
3490 $c = 'V' if ($elements[$n + 2] ne '');
3491 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3492 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3493 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3494 $c = 'O' if ($elements[$n + 2] eq '');
3495 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3500 my $ctx = "${a}x${c}";
3502 my $at = "(ctx:$ctx)";
3504 my $ptr = substr($blank, 0, $off) . "^";
3505 my $hereptr = "$hereline$ptr\n";
3507 # Pull out the value of this operator.
3508 my $op_type = substr($curr_values, $off + 1, 1);
3510 # Get the full operator variant.
3511 my $opv = $op . substr($curr_vars, $off, 1);
3513 # Ignore operators passed as parameters.
3514 if ($op_type ne 'V' &&
3515 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3518 # } elsif ($op =~ /^$;+$/) {
3520 # ; should have either the end of line or a space or \ after it
3521 } elsif ($op eq ';') {
3522 if ($ctx !~ /.x[WEBC]/ &&
3523 $cc !~ /^\\/ && $cc !~ /^;/) {
3524 if (ERROR("SPACING",
3525 "space required after that '$op' $at\n" . $hereptr)) {
3526 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3532 } elsif ($op eq '//') {
3534 # : when part of a bitfield
3535 } elsif ($opv eq ':B') {
3536 # skip the bitfield test for now
3540 } elsif ($op eq '->') {
3541 if ($ctx =~ /Wx.|.xW/) {
3542 if (ERROR("SPACING",
3543 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3544 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3545 if (defined $fix_elements[$n + 2]) {
3546 $fix_elements[$n + 2] =~ s/^\s+//;
3552 # , must not have a space before and must have a space on the right.
3553 } elsif ($op eq ',') {
3554 my $rtrim_before = 0;
3555 my $space_after = 0;
3556 if ($ctx =~ /Wx./) {
3557 if (ERROR("SPACING",
3558 "space prohibited before that '$op' $at\n" . $hereptr)) {
3563 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3564 if (ERROR("SPACING",
3565 "space required after that '$op' $at\n" . $hereptr)) {
3571 if ($rtrim_before || $space_after) {
3572 if ($rtrim_before) {
3573 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3575 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3582 # '*' as part of a type definition -- reported already.
3583 } elsif ($opv eq '*_') {
3584 #warn "'*' is part of type\n";
3586 # unary operators should have a space before and
3587 # none after. May be left adjacent to another
3588 # unary operator, or a cast
3589 } elsif ($op eq '!' || $op eq '~' ||
3590 $opv eq '*U' || $opv eq '-U' ||
3591 $opv eq '&U' || $opv eq '&&U') {
3592 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3593 if (ERROR("SPACING",
3594 "space required before that '$op' $at\n" . $hereptr)) {
3595 if ($n != $last_after + 2) {
3596 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3601 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3602 # A unary '*' may be const
3604 } elsif ($ctx =~ /.xW/) {
3605 if (ERROR("SPACING",
3606 "space prohibited after that '$op' $at\n" . $hereptr)) {
3607 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3608 if (defined $fix_elements[$n + 2]) {
3609 $fix_elements[$n + 2] =~ s/^\s+//;
3615 # unary ++ and unary -- are allowed no space on one side.
3616 } elsif ($op eq '++' or $op eq '--') {
3617 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3618 if (ERROR("SPACING",
3619 "space required one side of that '$op' $at\n" . $hereptr)) {
3620 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3624 if ($ctx =~ /Wx[BE]/ ||
3625 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3626 if (ERROR("SPACING",
3627 "space prohibited before that '$op' $at\n" . $hereptr)) {
3628 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3632 if ($ctx =~ /ExW/) {
3633 if (ERROR("SPACING",
3634 "space prohibited after that '$op' $at\n" . $hereptr)) {
3635 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3636 if (defined $fix_elements[$n + 2]) {
3637 $fix_elements[$n + 2] =~ s/^\s+//;
3643 # << and >> may either have or not have spaces both sides
3644 } elsif ($op eq '<<' or $op eq '>>' or
3645 $op eq '&' or $op eq '^' or $op eq '|' or
3646 $op eq '+' or $op eq '-' or
3647 $op eq '*' or $op eq '/' or
3650 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3651 if (ERROR("SPACING",
3652 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3653 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3654 if (defined $fix_elements[$n + 2]) {
3655 $fix_elements[$n + 2] =~ s/^\s+//;
3661 # A colon needs no spaces before when it is
3662 # terminating a case value or a label.
3663 } elsif ($opv eq ':C' || $opv eq ':L') {
3664 if ($ctx =~ /Wx./) {
3665 if (ERROR("SPACING",
3666 "space prohibited before that '$op' $at\n" . $hereptr)) {
3667 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3672 # All the others need spaces both sides.
3673 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3676 # Ignore email addresses <foo@bar>
3678 $cc =~ /^\S+\@\S+>/) ||
3680 $ca =~ /<\S+\@\S+$/))
3685 # messages are ERROR, but ?: are CHK
3687 my $msg_type = \&ERROR;
3688 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3690 if (&{$msg_type}("SPACING",
3691 "spaces required around that '$op' $at\n" . $hereptr)) {
3692 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3693 if (defined $fix_elements[$n + 2]) {
3694 $fix_elements[$n + 2] =~ s/^\s+//;
3700 $off += length($elements[$n + 1]);
3702 ## print("n: <$n> GOOD: <$good>\n");
3704 $fixed_line = $fixed_line . $good;
3707 if (($#elements % 2) == 0) {
3708 $fixed_line = $fixed_line . $fix_elements[$#elements];
3711 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3712 $fixed[$fixlinenr] = $fixed_line;
3718 # check for whitespace before a non-naked semicolon
3719 if ($line =~ /^\+.*\S\s+;\s*$/) {
3721 "space prohibited before semicolon\n" . $herecurr) &&
3723 1 while $fixed[$fixlinenr] =~
3724 s/^(\+.*\S)\s+;/$1;/;
3728 # check for multiple assignments
3729 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3730 CHK("MULTIPLE_ASSIGNMENTS",
3731 "multiple assignments should be avoided\n" . $herecurr);
3734 ## # check for multiple declarations, allowing for a function declaration
3736 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3737 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3739 ## # Remove any bracketed sections to ensure we do not
3740 ## # falsly report the parameters of functions.
3742 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3744 ## if ($ln =~ /,/) {
3745 ## WARN("MULTIPLE_DECLARATION",
3746 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3750 #need space before brace following if, while, etc
3751 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3753 if (ERROR("SPACING",
3754 "space required before the open brace '{'\n" . $herecurr) &&
3756 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3760 ## # check for blank lines before declarations
3761 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3762 ## $prevrawline =~ /^.\s*$/) {
3764 ## "No blank lines before declarations\n" . $hereprev);
3768 # closing brace should have a space following it when it has anything
3770 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3771 if (ERROR("SPACING",
3772 "space required after that close brace '}'\n" . $herecurr) &&
3774 $fixed[$fixlinenr] =~
3775 s/}((?!(?:,|;|\)))\S)/} $1/;
3779 # check spacing on square brackets
3780 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3781 if (ERROR("SPACING",
3782 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3784 $fixed[$fixlinenr] =~
3788 if ($line =~ /\s\]/) {
3789 if (ERROR("SPACING",
3790 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3792 $fixed[$fixlinenr] =~
3797 # check spacing on parentheses
3798 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3799 $line !~ /for\s*\(\s+;/) {
3800 if (ERROR("SPACING",
3801 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3803 $fixed[$fixlinenr] =~
3807 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3808 $line !~ /for\s*\(.*;\s+\)/ &&
3809 $line !~ /:\s+\)/) {
3810 if (ERROR("SPACING",
3811 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3813 $fixed[$fixlinenr] =~
3818 # check unnecessary parentheses around addressof/dereference single $Lvals
3819 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3821 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3823 if (CHK("UNNECESSARY_PARENTHESES",
3824 "Unnecessary parentheses around $var\n" . $herecurr) &&
3826 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3830 # check for unnecessary parentheses around function pointer uses
3831 # ie: (foo->bar)(); should be foo->bar();
3832 # but not "if (foo->bar) (" to avoid some false positives
3833 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3835 if (CHK("UNNECESSARY_PARENTHESES",
3836 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3838 my $var2 = deparenthesize($var);
3840 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3844 #goto labels aren't indented, allow a single space however
3845 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3846 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3847 if (WARN("INDENTED_LABEL",
3848 "labels should not be indented\n" . $herecurr) &&
3850 $fixed[$fixlinenr] =~
3855 # return is not a function
3856 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3858 if ($^V && $^V ge 5.10.0 &&
3859 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3861 $value = deparenthesize($value);
3862 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3863 ERROR("RETURN_PARENTHESES",
3864 "return is not a function, parentheses are not required\n" . $herecurr);
3866 } elsif ($spacing !~ /\s+/) {
3868 "space required before the open parenthesis '('\n" . $herecurr);
3872 # unnecessary return in a void function
3873 # at end-of-function, with the previous line a single leading tab, then return;
3874 # and the line before that not a goto label target like "out:"
3875 if ($sline =~ /^[ \+]}\s*$/ &&
3876 $prevline =~ /^\+\treturn\s*;\s*$/ &&
3878 $lines[$linenr - 3] =~ /^[ +]/ &&
3879 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3881 "void function return statements are not generally useful\n" . $hereprev);
3884 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3885 if ($^V && $^V ge 5.10.0 &&
3886 $line =~ /\bif\s*((?:\(\s*){2,})/) {
3887 my $openparens = $1;
3888 my $count = $openparens =~ tr@\(@\(@;
3890 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3891 my $comp = $4; #Not $1 because of $LvalOrFunc
3892 $msg = " - maybe == should be = ?" if ($comp eq "==");
3893 WARN("UNNECESSARY_PARENTHESES",
3894 "Unnecessary parentheses$msg\n" . $herecurr);
3898 # Return of what appears to be an errno should normally be -'ve
3899 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3901 if ($name ne 'EOF' && $name ne 'ERROR') {
3902 WARN("USE_NEGATIVE_ERRNO",
3903 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3907 # Need a space before open parenthesis after if, while etc
3908 if ($line =~ /\b(if|while|for|switch)\(/) {
3909 if (ERROR("SPACING",
3910 "space required before the open parenthesis '('\n" . $herecurr) &&
3912 $fixed[$fixlinenr] =~
3913 s/\b(if|while|for|switch)\(/$1 \(/;
3917 # Check for illegal assignment in if conditional -- and check for trailing
3918 # statements after the conditional.
3919 if ($line =~ /do\s*(?!{)/) {
3920 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3921 ctx_statement_block($linenr, $realcnt, 0)
3922 if (!defined $stat);
3923 my ($stat_next) = ctx_statement_block($line_nr_next,
3924 $remain_next, $off_next);
3925 $stat_next =~ s/\n./\n /g;
3926 ##print "stat<$stat> stat_next<$stat_next>\n";
3928 if ($stat_next =~ /^\s*while\b/) {
3929 # If the statement carries leading newlines,
3930 # then count those as offsets.
3932 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3934 statement_rawlines($whitespace) - 1;
3936 $suppress_whiletrailers{$line_nr_next +
3940 if (!defined $suppress_whiletrailers{$linenr} &&
3941 defined($stat) && defined($cond) &&
3942 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3943 my ($s, $c) = ($stat, $cond);
3945 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3946 ERROR("ASSIGN_IN_IF",
3947 "do not use assignment in if condition\n" . $herecurr);
3950 # Find out what is on the end of the line after the
3952 substr($s, 0, length($c), '');
3954 $s =~ s/$;//g; # Remove any comments
3955 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3956 $c !~ /}\s*while\s*/)
3958 # Find out how long the conditional actually is.
3959 my @newlines = ($c =~ /\n/gs);
3960 my $cond_lines = 1 + $#newlines;
3963 $stat_real = raw_line($linenr, $cond_lines)
3964 . "\n" if ($cond_lines);
3965 if (defined($stat_real) && $cond_lines > 1) {
3966 $stat_real = "[...]\n$stat_real";
3969 ERROR("TRAILING_STATEMENTS",
3970 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3974 # Check for bitwise tests written as boolean
3986 WARN("HEXADECIMAL_BOOLEAN_TEST",
3987 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3990 # if and else should not have general statements after it
3991 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3993 $s =~ s/$;//g; # Remove any comments
3994 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3995 ERROR("TRAILING_STATEMENTS",
3996 "trailing statements should be on next line\n" . $herecurr);
3999 # if should not continue a brace
4000 if ($line =~ /}\s*if\b/) {
4001 ERROR("TRAILING_STATEMENTS",
4002 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4005 # case and default should not have general statements after them
4006 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4008 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4012 ERROR("TRAILING_STATEMENTS",
4013 "trailing statements should be on next line\n" . $herecurr);
4016 # Check for }<nl>else {, these must be at the same
4017 # indent level to be relevant to each other.
4018 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4019 $previndent == $indent) {
4020 if (ERROR("ELSE_AFTER_BRACE",
4021 "else should follow close brace '}'\n" . $hereprev) &&
4022 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4023 fix_delete_line($fixlinenr - 1, $prevrawline);
4024 fix_delete_line($fixlinenr, $rawline);
4025 my $fixedline = $prevrawline;
4026 $fixedline =~ s/}\s*$//;
4027 if ($fixedline !~ /^\+\s*$/) {
4028 fix_insert_line($fixlinenr, $fixedline);
4030 $fixedline = $rawline;
4031 $fixedline =~ s/^(.\s*)else/$1} else/;
4032 fix_insert_line($fixlinenr, $fixedline);
4036 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4037 $previndent == $indent) {
4038 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4040 # Find out what is on the end of the line after the
4042 substr($s, 0, length($c), '');
4045 if ($s =~ /^\s*;/) {
4046 if (ERROR("WHILE_AFTER_BRACE",
4047 "while should follow close brace '}'\n" . $hereprev) &&
4048 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4049 fix_delete_line($fixlinenr - 1, $prevrawline);
4050 fix_delete_line($fixlinenr, $rawline);
4051 my $fixedline = $prevrawline;
4052 my $trailing = $rawline;
4053 $trailing =~ s/^\+//;
4054 $trailing = trim($trailing);
4055 $fixedline =~ s/}\s*$/} $trailing/;
4056 fix_insert_line($fixlinenr, $fixedline);
4061 #Specific variable tests
4062 while ($line =~ m{($Constant|$Lval)}g) {
4065 #gcc binary extension
4066 if ($var =~ /^$Binary$/) {
4067 if (WARN("GCC_BINARY_CONSTANT",
4068 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4070 my $hexval = sprintf("0x%x", oct($var));
4071 $fixed[$fixlinenr] =~
4072 s/\b$var\b/$hexval/;
4077 if ($var !~ /^$Constant$/ &&
4078 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4079 #Ignore Page<foo> variants
4080 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4081 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4082 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4083 #Ignore some three character SI units explicitly, like MiB and KHz
4084 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4085 while ($var =~ m{($Ident)}g) {
4087 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4089 seed_camelcase_includes();
4090 if (!$file && !$camelcase_file_seeded) {
4091 seed_camelcase_file($realfile);
4092 $camelcase_file_seeded = 1;
4095 if (!defined $camelcase{$word}) {
4096 $camelcase{$word} = 1;
4098 "Avoid CamelCase: <$word>\n" . $herecurr);
4104 #no spaces allowed after \ in define
4105 if ($line =~ /\#\s*define.*\\\s+$/) {
4106 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4107 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4109 $fixed[$fixlinenr] =~ s/\s+$//;
4113 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4114 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4116 my $checkfile = "include/linux/$file";
4117 if (-f "$root/$checkfile" &&
4118 $realfile ne $checkfile &&
4119 $1 !~ /$allowed_asm_includes/)
4121 if ($realfile =~ m{^arch/}) {
4122 CHK("ARCH_INCLUDE_LINUX",
4123 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4125 WARN("INCLUDE_LINUX",
4126 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4131 # multi-statement macros should be enclosed in a do while loop, grab the
4132 # first statement and ensure its the whole macro if its not enclosed
4133 # in a known good container
4134 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4135 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4138 my ($off, $dstat, $dcond, $rest);
4140 my $has_flow_statement = 0;
4141 my $has_arg_concat = 0;
4142 ($dstat, $dcond, $ln, $cnt, $off) =
4143 ctx_statement_block($linenr, $realcnt, 0);
4145 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4146 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4148 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4149 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4151 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4153 $dstat =~ s/\\\n.//g;
4154 $dstat =~ s/^\s*//s;
4155 $dstat =~ s/\s*$//s;
4157 # Flatten any parentheses and braces
4158 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4159 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4160 $dstat =~ s/\[[^\[\]]*\]/1/)
4164 # Flatten any obvious string concatentation.
4165 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4166 $dstat =~ s/$Ident\s*("X*")/$1/)
4170 my $exceptions = qr{
4182 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4184 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4185 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4186 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4187 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4188 $dstat !~ /$exceptions/ &&
4189 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4190 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4191 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4192 $dstat !~ /^for\s*$Constant$/ && # for (...)
4193 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4194 $dstat !~ /^do\s*{/ && # do {...
4195 $dstat !~ /^\({/ && # ({...
4196 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4199 my $herectx = $here . "\n";
4200 my $cnt = statement_rawlines($ctx);
4202 for (my $n = 0; $n < $cnt; $n++) {
4203 $herectx .= raw_line($linenr, $n) . "\n";
4206 if ($dstat =~ /;/) {
4207 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4208 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4210 ERROR("COMPLEX_MACRO",
4211 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4215 # check for macros with flow control, but without ## concatenation
4216 # ## concatenation is commonly a macro that defines a function so ignore those
4217 if ($has_flow_statement && !$has_arg_concat) {
4218 my $herectx = $here . "\n";
4219 my $cnt = statement_rawlines($ctx);
4221 for (my $n = 0; $n < $cnt; $n++) {
4222 $herectx .= raw_line($linenr, $n) . "\n";
4224 WARN("MACRO_WITH_FLOW_CONTROL",
4225 "Macros with flow control statements should be avoided\n" . "$herectx");
4228 # check for line continuations outside of #defines, preprocessor #, and asm
4231 if ($prevline !~ /^..*\\$/ &&
4232 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4233 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4234 $line =~ /^\+.*\\$/) {
4235 WARN("LINE_CONTINUATIONS",
4236 "Avoid unnecessary line continuations\n" . $herecurr);
4240 # do {} while (0) macro tests:
4241 # single-statement macros do not need to be enclosed in do while (0) loop,
4242 # macro should not end with a semicolon
4243 if ($^V && $^V ge 5.10.0 &&
4244 $realfile !~ m@/vmlinux.lds.h$@ &&
4245 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4248 my ($off, $dstat, $dcond, $rest);
4250 ($dstat, $dcond, $ln, $cnt, $off) =
4251 ctx_statement_block($linenr, $realcnt, 0);
4254 $dstat =~ s/\\\n.//g;
4256 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4261 my $cnt = statement_rawlines($ctx);
4262 my $herectx = $here . "\n";
4264 for (my $n = 0; $n < $cnt; $n++) {
4265 $herectx .= raw_line($linenr, $n) . "\n";
4268 if (($stmts =~ tr/;/;/) == 1 &&
4269 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4270 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4271 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4273 if (defined $semis && $semis ne "") {
4274 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4275 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4277 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4279 my $cnt = statement_rawlines($ctx);
4280 my $herectx = $here . "\n";
4282 for (my $n = 0; $n < $cnt; $n++) {
4283 $herectx .= raw_line($linenr, $n) . "\n";
4286 WARN("TRAILING_SEMICOLON",
4287 "macros should not use a trailing semicolon\n" . "$herectx");
4291 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4292 # all assignments may have only one of the following with an assignment:
4295 # VMLINUX_SYMBOL(...)
4296 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4297 WARN("MISSING_VMLINUX_SYMBOL",
4298 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4301 # check for redundant bracing round if etc
4302 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4303 my ($level, $endln, @chunks) =
4304 ctx_statement_full($linenr, $realcnt, 1);
4305 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4306 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4307 if ($#chunks > 0 && $level == 0) {
4311 my $herectx = $here . "\n";
4312 my $ln = $linenr - 1;
4313 for my $chunk (@chunks) {
4314 my ($cond, $block) = @{$chunk};
4316 # If the condition carries leading newlines, then count those as offsets.
4317 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4318 my $offset = statement_rawlines($whitespace) - 1;
4320 $allowed[$allow] = 0;
4321 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4323 # We have looked at and allowed this specific line.
4324 $suppress_ifbraces{$ln + $offset} = 1;
4326 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4327 $ln += statement_rawlines($block) - 1;
4329 substr($block, 0, length($cond), '');
4331 $seen++ if ($block =~ /^\s*{/);
4333 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4334 if (statement_lines($cond) > 1) {
4335 #print "APW: ALLOWED: cond<$cond>\n";
4336 $allowed[$allow] = 1;
4338 if ($block =~/\b(?:if|for|while)\b/) {
4339 #print "APW: ALLOWED: block<$block>\n";
4340 $allowed[$allow] = 1;
4342 if (statement_block_size($block) > 1) {
4343 #print "APW: ALLOWED: lines block<$block>\n";
4344 $allowed[$allow] = 1;
4349 my $sum_allowed = 0;
4350 foreach (@allowed) {
4353 if ($sum_allowed == 0) {
4355 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4356 } elsif ($sum_allowed != $allow &&
4359 "braces {} should be used on all arms of this statement\n" . $herectx);
4364 if (!defined $suppress_ifbraces{$linenr - 1} &&
4365 $line =~ /\b(if|while|for|else)\b/) {
4368 # Check the pre-context.
4369 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4370 #print "APW: ALLOWED: pre<$1>\n";
4374 my ($level, $endln, @chunks) =
4375 ctx_statement_full($linenr, $realcnt, $-[0]);
4377 # Check the condition.
4378 my ($cond, $block) = @{$chunks[0]};
4379 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4380 if (defined $cond) {
4381 substr($block, 0, length($cond), '');
4383 if (statement_lines($cond) > 1) {
4384 #print "APW: ALLOWED: cond<$cond>\n";
4387 if ($block =~/\b(?:if|for|while)\b/) {
4388 #print "APW: ALLOWED: block<$block>\n";
4391 if (statement_block_size($block) > 1) {
4392 #print "APW: ALLOWED: lines block<$block>\n";
4395 # Check the post-context.
4396 if (defined $chunks[1]) {
4397 my ($cond, $block) = @{$chunks[1]};
4398 if (defined $cond) {
4399 substr($block, 0, length($cond), '');
4401 if ($block =~ /^\s*\{/) {
4402 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4406 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4407 my $herectx = $here . "\n";
4408 my $cnt = statement_rawlines($block);
4410 for (my $n = 0; $n < $cnt; $n++) {
4411 $herectx .= raw_line($linenr, $n) . "\n";
4415 "braces {} are not necessary for single statement blocks\n" . $herectx);
4419 # check for unnecessary blank lines around braces
4420 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4422 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
4424 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4426 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
4429 # no volatiles please
4430 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4431 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4433 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4436 # Check for user-visible strings broken across lines, which breaks the ability
4437 # to grep for the string. Make exceptions when the previous string ends in a
4438 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4439 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4440 if ($line =~ /^\+\s*"[X\t]*"/ &&
4441 $prevline =~ /"\s*$/ &&
4442 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4443 if (WARN("SPLIT_STRING",
4444 "quoted string split across lines\n" . $hereprev) &&
4446 $prevrawline =~ /^\+.*"\s*$/ &&
4447 $last_coalesced_string_linenr != $linenr - 1) {
4448 my $extracted_string = get_quoted_string($line, $rawline);
4449 my $comma_close = "";
4450 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4454 fix_delete_line($fixlinenr - 1, $prevrawline);
4455 fix_delete_line($fixlinenr, $rawline);
4456 my $fixedline = $prevrawline;
4457 $fixedline =~ s/"\s*$//;
4458 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4459 fix_insert_line($fixlinenr - 1, $fixedline);
4460 $fixedline = $rawline;
4461 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4462 if ($fixedline !~ /\+\s*$/) {
4463 fix_insert_line($fixlinenr, $fixedline);
4465 $last_coalesced_string_linenr = $linenr;
4469 # check for missing a space in a string concatenation
4470 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4471 WARN('MISSING_SPACE',
4472 "break quoted strings at a space character\n" . $hereprev);
4475 # check for spaces before a quoted newline
4476 if ($rawline =~ /^.*\".*\s\\n/) {
4477 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4478 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4480 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4485 # concatenated string without spaces between elements
4486 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4487 CHK("CONCATENATED_STRING",
4488 "Concatenated strings should use spaces between elements\n" . $herecurr);
4491 # uncoalesced string fragments
4492 if ($line =~ /"X*"\s*"/) {
4493 WARN("STRING_FRAGMENTS",
4494 "Consecutive strings are generally better as a single string\n" . $herecurr);
4497 # check for %L{u,d,i} in strings
4499 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4500 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4501 $string =~ s/%%/__/g;
4502 if ($string =~ /(?<!%)%L[udi]/) {
4504 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4509 # check for line continuations in quoted strings with odd counts of "
4510 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4511 WARN("LINE_CONTINUATIONS",
4512 "Avoid line continuations in quoted strings\n" . $herecurr);
4516 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4517 CHK("REDUNDANT_CODE",
4518 "if this code is redundant consider removing it\n" .
4522 # check for needless "if (<foo>) fn(<foo>)" uses
4523 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4524 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4525 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4527 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4531 # check for unnecessary "Out of Memory" messages
4532 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4533 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4534 (defined $1 || defined $3) &&
4537 my $testline = $lines[$linenr - 3];
4539 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4540 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4542 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4544 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4548 # check for logging functions with KERN_<LEVEL>
4549 if ($line !~ /printk\s*\(/ &&
4550 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4552 if (WARN("UNNECESSARY_KERN_LEVEL",
4553 "Possible unnecessary $level\n" . $herecurr) &&
4555 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4559 # check for mask then right shift without a parentheses
4560 if ($^V && $^V ge 5.10.0 &&
4561 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4562 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4563 WARN("MASK_THEN_SHIFT",
4564 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4567 # check for pointer comparisons to NULL
4568 if ($^V && $^V ge 5.10.0) {
4569 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4572 $equal = "" if ($4 eq "!=");
4573 if (CHK("COMPARISON_TO_NULL",
4574 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4576 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4581 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4582 if ($line =~ /(\b$InitAttribute\b)/) {
4584 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4587 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4588 ERROR("MISPLACED_INIT",
4589 "$attr should be placed after $var\n" . $herecurr)) ||
4590 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4591 WARN("MISPLACED_INIT",
4592 "$attr should be placed after $var\n" . $herecurr))) &&
4594 $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;
4599 # check for $InitAttributeData (ie: __initdata) with const
4600 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4602 $attr =~ /($InitAttributePrefix)(.*)/;
4603 my $attr_prefix = $1;
4605 if (ERROR("INIT_ATTRIBUTE",
4606 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4608 $fixed[$fixlinenr] =~
4609 s/$InitAttributeData/${attr_prefix}initconst/;
4613 # check for $InitAttributeConst (ie: __initconst) without const
4614 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4616 if (ERROR("INIT_ATTRIBUTE",
4617 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4619 my $lead = $fixed[$fixlinenr] =~
4620 /(^\+\s*(?:static\s+))/;
4622 $lead = "$lead " if ($lead !~ /^\+$/);
4623 $lead = "${lead}const ";
4624 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4628 # don't use __constant_<foo> functions outside of include/uapi/
4629 if ($realfile !~ m@^include/uapi/@ &&
4630 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4631 my $constant_func = $1;
4632 my $func = $constant_func;
4633 $func =~ s/^__constant_//;
4634 if (WARN("CONSTANT_CONVERSION",
4635 "$constant_func should be $func\n" . $herecurr) &&
4637 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4641 # prefer usleep_range over udelay
4642 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4644 # ignore udelay's < 10, however
4645 if (! ($delay < 10) ) {
4647 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4649 if ($delay > 2000) {
4651 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4655 # warn about unexpectedly long msleep's
4656 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4659 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4663 # check for comparisons of jiffies
4664 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4665 WARN("JIFFIES_COMPARISON",
4666 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4669 # check for comparisons of get_jiffies_64()
4670 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4671 WARN("JIFFIES_COMPARISON",
4672 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4675 # warn about #ifdefs in C files
4676 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4677 # print "#ifdef in C files should be avoided\n";
4678 # print "$herecurr";
4682 # warn about spacing in #ifdefs
4683 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4684 if (ERROR("SPACING",
4685 "exactly one space required after that #$1\n" . $herecurr) &&
4687 $fixed[$fixlinenr] =~
4688 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4693 # check for spinlock_t definitions without a comment.
4694 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4695 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4697 if (!ctx_has_comment($first_line, $linenr)) {
4698 CHK("UNCOMMENTED_DEFINITION",
4699 "$1 definition without comment\n" . $herecurr);
4702 # check for memory barriers without a comment.
4703 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4704 if (!ctx_has_comment($first_line, $linenr)) {
4705 WARN("MEMORY_BARRIER",
4706 "memory barrier without comment\n" . $herecurr);
4709 # check of hardware specific defines
4710 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4712 "architecture specific defines should be avoided\n" . $herecurr);
4715 # Check that the storage class is at the beginning of a declaration
4716 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4717 WARN("STORAGE_CLASS",
4718 "storage class should be at the beginning of the declaration\n" . $herecurr)
4721 # check the location of the inline attribute, that it is between
4722 # storage class and type.
4723 if ($line =~ /\b$Type\s+$Inline\b/ ||
4724 $line =~ /\b$Inline\s+$Storage\b/) {
4725 ERROR("INLINE_LOCATION",
4726 "inline keyword should sit between storage class and type\n" . $herecurr);
4729 # Check for __inline__ and __inline, prefer inline
4730 if ($realfile !~ m@\binclude/uapi/@ &&
4731 $line =~ /\b(__inline__|__inline)\b/) {
4733 "plain inline is preferred over $1\n" . $herecurr) &&
4735 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4740 # Check for __attribute__ packed, prefer __packed
4741 if ($realfile !~ m@\binclude/uapi/@ &&
4742 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4743 WARN("PREFER_PACKED",
4744 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4747 # Check for __attribute__ aligned, prefer __aligned
4748 if ($realfile !~ m@\binclude/uapi/@ &&
4749 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4750 WARN("PREFER_ALIGNED",
4751 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4754 # Check for __attribute__ format(printf, prefer __printf
4755 if ($realfile !~ m@\binclude/uapi/@ &&
4756 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4757 if (WARN("PREFER_PRINTF",
4758 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4760 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4765 # Check for __attribute__ format(scanf, prefer __scanf
4766 if ($realfile !~ m@\binclude/uapi/@ &&
4767 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4768 if (WARN("PREFER_SCANF",
4769 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4771 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4775 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4776 if ($^V && $^V ge 5.10.0 &&
4777 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4778 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4779 $line =~ /\b__weak\b/)) {
4780 ERROR("WEAK_DECLARATION",
4781 "Using weak declarations can have unintended link defects\n" . $herecurr);
4784 # check for sizeof(&)
4785 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4786 WARN("SIZEOF_ADDRESS",
4787 "sizeof(& should be avoided\n" . $herecurr);
4790 # check for sizeof without parenthesis
4791 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4792 if (WARN("SIZEOF_PARENTHESIS",
4793 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4795 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4799 # check for struct spinlock declarations
4800 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4801 WARN("USE_SPINLOCK_T",
4802 "struct spinlock should be spinlock_t\n" . $herecurr);
4805 # check for seq_printf uses that could be seq_puts
4806 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4807 my $fmt = get_quoted_string($line, $rawline);
4808 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4809 if (WARN("PREFER_SEQ_PUTS",
4810 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4812 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4817 # Check for misused memsets
4818 if ($^V && $^V ge 5.10.0 &&
4820 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4826 if ($ms_size =~ /^(0x|)0$/i) {
4828 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4829 } elsif ($ms_size =~ /^(0x|)1$/i) {
4831 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4835 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4836 if ($^V && $^V ge 5.10.0 &&
4837 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4838 if (WARN("PREFER_ETHER_ADDR_COPY",
4839 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4841 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4845 # typecasts on min/max could be min_t/max_t
4846 if ($^V && $^V ge 5.10.0 &&
4848 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4849 if (defined $2 || defined $7) {
4851 my $cast1 = deparenthesize($2);
4853 my $cast2 = deparenthesize($7);
4857 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4858 $cast = "$cast1 or $cast2";
4859 } elsif ($cast1 ne "") {
4865 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4869 # check usleep_range arguments
4870 if ($^V && $^V ge 5.10.0 &&
4872 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4876 WARN("USLEEP_RANGE",
4877 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4878 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4880 WARN("USLEEP_RANGE",
4881 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4885 # check for naked sscanf
4886 if ($^V && $^V ge 5.10.0 &&
4888 $line =~ /\bsscanf\b/ &&
4889 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4890 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4891 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4892 my $lc = $stat =~ tr@\n@@;
4893 $lc = $lc + $linenr;
4894 my $stat_real = raw_line($linenr, 0);
4895 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4896 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4898 WARN("NAKED_SSCANF",
4899 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4902 # check for simple sscanf that should be kstrto<foo>
4903 if ($^V && $^V ge 5.10.0 &&
4905 $line =~ /\bsscanf\b/) {
4906 my $lc = $stat =~ tr@\n@@;
4907 $lc = $lc + $linenr;
4908 my $stat_real = raw_line($linenr, 0);
4909 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4910 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4912 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4914 my $count = $format =~ tr@%@%@;
4916 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4917 WARN("SSCANF_TO_KSTRTO",
4918 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4923 # check for new externs in .h files.
4924 if ($realfile =~ /\.h$/ &&
4925 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4926 if (CHK("AVOID_EXTERNS",
4927 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4929 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4933 # check for new externs in .c files.
4934 if ($realfile =~ /\.c$/ && defined $stat &&
4935 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4937 my $function_name = $1;
4938 my $paren_space = $2;
4941 if (defined $cond) {
4942 substr($s, 0, length($cond), '');
4944 if ($s =~ /^\s*;/ &&
4945 $function_name ne 'uninitialized_var')
4947 WARN("AVOID_EXTERNS",
4948 "externs should be avoided in .c files\n" . $herecurr);
4951 if ($paren_space =~ /\n/) {
4952 WARN("FUNCTION_ARGUMENTS",
4953 "arguments for function declarations should follow identifier\n" . $herecurr);
4956 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4957 $stat =~ /^.\s*extern\s+/)
4959 WARN("AVOID_EXTERNS",
4960 "externs should be avoided in .c files\n" . $herecurr);
4963 # checks for new __setup's
4964 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4967 if (!grep(/$name/, @setup_docs)) {
4968 CHK("UNDOCUMENTED_SETUP",
4969 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4973 # check for pointless casting of kmalloc return
4974 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4975 WARN("UNNECESSARY_CASTS",
4976 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4980 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4981 if ($^V && $^V ge 5.10.0 &&
4982 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4983 CHK("ALLOC_SIZEOF_STRUCT",
4984 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4987 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
4988 if ($^V && $^V ge 5.10.0 &&
4989 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
4993 my $newfunc = "kmalloc_array";
4994 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
4997 if ($a1 =~ /^sizeof\s*\S/) {
5001 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5002 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5003 if (WARN("ALLOC_WITH_MULTIPLY",
5004 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5006 $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;
5012 # check for krealloc arg reuse
5013 if ($^V && $^V ge 5.10.0 &&
5014 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5015 WARN("KREALLOC_ARG_REUSE",
5016 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5019 # check for alloc argument mismatch
5020 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5021 WARN("ALLOC_ARRAY_ARGS",
5022 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5025 # check for multiple semicolons
5026 if ($line =~ /;\s*;\s*$/) {
5027 if (WARN("ONE_SEMICOLON",
5028 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5030 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5034 # check for #defines like: 1 << <digit> that could be BIT(digit)
5035 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5037 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5038 if (CHK("BIT_MACRO",
5039 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5041 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5045 # check for case / default statements not preceded by break/fallthrough/switch
5046 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5048 my $has_statement = 0;
5050 my $prevline = $linenr;
5051 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5053 my $rline = $rawlines[$prevline - 1];
5054 my $fline = $lines[$prevline - 1];
5055 last if ($fline =~ /^\@\@/);
5056 next if ($fline =~ /^\-/);
5057 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5058 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5059 next if ($fline =~ /^.[\s$;]*$/);
5062 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5064 if (!$has_break && $has_statement) {
5065 WARN("MISSING_BREAK",
5066 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5070 # check for switch/default statements without a break;
5071 if ($^V && $^V ge 5.10.0 &&
5073 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5075 my $herectx = $here . "\n";
5076 my $cnt = statement_rawlines($stat);
5077 for (my $n = 0; $n < $cnt; $n++) {
5078 $herectx .= raw_line($linenr, $n) . "\n";
5080 WARN("DEFAULT_NO_BREAK",
5081 "switch default: should use break\n" . $herectx);
5084 # check for gcc specific __FUNCTION__
5085 if ($line =~ /\b__FUNCTION__\b/) {
5086 if (WARN("USE_FUNC",
5087 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5089 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5093 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5094 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5096 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5099 # check for use of yield()
5100 if ($line =~ /\byield\s*\(\s*\)/) {
5102 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5105 # check for comparisons against true and false
5106 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5114 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5116 my $type = lc($otype);
5117 if ($type =~ /^(?:true|false)$/) {
5118 if (("$test" eq "==" && "$type" eq "true") ||
5119 ("$test" eq "!=" && "$type" eq "false")) {
5123 CHK("BOOL_COMPARISON",
5124 "Using comparison to $otype is error prone\n" . $herecurr);
5126 ## maybe suggesting a correct construct would better
5127 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5132 # check for semaphores initialized locked
5133 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5134 WARN("CONSIDER_COMPLETION",
5135 "consider using a completion\n" . $herecurr);
5138 # recommend kstrto* over simple_strto* and strict_strto*
5139 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5140 WARN("CONSIDER_KSTRTO",
5141 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5144 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5145 if ($line =~ /^.\s*__initcall\s*\(/) {
5146 WARN("USE_DEVICE_INITCALL",
5147 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5150 # check for various ops structs, ensure they are const.
5151 my $struct_ops = qr{acpi_dock_ops|
5152 address_space_operations|
5154 block_device_operations|
5159 file_lock_operations|
5169 lock_manager_operations|
5175 pipe_buf_operations|
5176 platform_hibernation_ops|
5177 platform_suspend_ops|
5182 soc_pcmcia_socket_ops|
5188 if ($line !~ /\bconst\b/ &&
5189 $line =~ /\bstruct\s+($struct_ops)\b/) {
5190 WARN("CONST_STRUCT",
5191 "struct $1 should normally be const\n" .
5195 # use of NR_CPUS is usually wrong
5196 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5197 if ($line =~ /\bNR_CPUS\b/ &&
5198 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5199 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5200 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5201 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5202 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5205 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5208 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5209 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5210 ERROR("DEFINE_ARCH_HAS",
5211 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5214 # whine mightly about in_atomic
5215 if ($line =~ /\bin_atomic\s*\(/) {
5216 if ($realfile =~ m@^drivers/@) {
5218 "do not use in_atomic in drivers\n" . $herecurr);
5219 } elsif ($realfile !~ m@^kernel/@) {
5221 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5225 # check for lockdep_set_novalidate_class
5226 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5227 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5228 if ($realfile !~ m@^kernel/lockdep@ &&
5229 $realfile !~ m@^include/linux/lockdep@ &&
5230 $realfile !~ m@^drivers/base/core@) {
5232 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5236 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5237 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5238 WARN("EXPORTED_WORLD_WRITABLE",
5239 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5242 # Mode permission misuses where it seems decimal should be octal
5243 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5244 if ($^V && $^V ge 5.10.0 &&
5245 $line =~ /$mode_perms_search/) {
5246 foreach my $entry (@mode_permission_funcs) {
5247 my $func = $entry->[0];
5248 my $arg_pos = $entry->[1];
5253 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5255 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5256 if ($line =~ /$test/) {
5258 $val = $6 if ($skip_args ne "");
5260 if ($val !~ /^0$/ &&
5261 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5262 length($val) ne 4)) {
5263 ERROR("NON_OCTAL_PERMISSIONS",
5264 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5265 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5266 ERROR("EXPORTED_WORLD_WRITABLE",
5267 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5274 # If we have no input at all, then there is nothing to report on
5275 # so just keep quiet.
5276 if ($#rawlines == -1) {
5280 # In mailback mode only produce a report in the negative, for
5281 # things that appear to be patches.
5282 if ($mailback && ($clean == 1 || !$is_patch)) {
5286 # This is not a patch, and we are are in 'no-patch' mode so
5288 if (!$chk_patch && !$is_patch) {
5293 ERROR("NOT_UNIFIED_DIFF",
5294 "Does not appear to be a unified-diff format patch\n");
5296 if ($is_patch && $chk_signoff && $signoff == 0) {
5297 ERROR("MISSING_SIGN_OFF",
5298 "Missing Signed-off-by: line(s)\n");
5301 print report_dump();
5302 if ($summary && !($clean == 1 && $quiet == 1)) {
5303 print "$filename " if ($summary_file);
5304 print "total: $cnt_error errors, $cnt_warn warnings, " .
5305 (($check)? "$cnt_chk checks, " : "") .
5306 "$cnt_lines lines checked\n";
5307 print "\n" if ($quiet == 0);
5312 if ($^V lt 5.10.0) {
5313 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5314 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5317 # If there were whitespace errors which cleanpatch can fix
5318 # then suggest that.
5319 if ($rpt_cleaners) {
5320 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5321 print " scripts/cleanfile\n\n";
5326 hash_show_words(\%use_type, "Used");
5327 hash_show_words(\%ignore_type, "Ignored");
5329 if ($clean == 0 && $fix &&
5330 ("@rawlines" ne "@fixed" ||
5331 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5332 my $newfile = $filename;
5333 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5337 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5339 open($f, '>', $newfile)
5340 or die "$P: Can't open $newfile for write\n";
5341 foreach my $fixed_line (@fixed) {
5344 if ($linecount > 3) {
5345 $fixed_line =~ s/^\+//;
5346 print $f $fixed_line . "\n";
5349 print $f $fixed_line . "\n";
5356 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5358 Do _NOT_ trust the results written to this file.
5359 Do _NOT_ submit these changes without inspecting them for correctness.
5361 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5362 No warranties, expressed or implied...
5368 if ($clean == 1 && $quiet == 0) {
5369 print "$vname has no obvious style problems and is ready for submission.\n"
5371 if ($clean == 0 && $quiet == 0) {
5373 $vname has style problems, please review.
5375 If any of these errors are false positives, please report
5376 them to the maintainer, see CHECKPATCH in MAINTAINERS.