2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
14 my $D = dirname(abs_path($P));
18 use Getopt::Long qw(:config no_auto_abbrev);
44 my $configuration_file = ".checkpatch.conf";
45 my $max_line_length = 80;
46 my $ignore_perl_version = 0;
47 my $minimum_perl_version = 5.10.0;
48 my $min_conf_desc_length = 4;
49 my $spelling_file = "$D/spelling.txt";
55 Usage: $P [OPTION]... [FILE]...
60 --no-tree run without a kernel tree
61 --no-signoff do not check for 'Signed-off-by' line
62 --patch treat FILE as patchfile (default)
63 --emacs emacs compile window format
64 --terse one line per report
65 -f, --file treat FILE as regular source file
66 --subjective, --strict enable more subjective tests
67 --types TYPE(,TYPE2...) show only these comma separated message types
68 --ignore TYPE(,TYPE2...) ignore various comma separated message types
69 --max-line-length=n set the maximum line length, if exceeded, warn
70 --min-conf-desc-length=n set the min description length, if shorter, warn
71 --show-types show the message "types" in the output
72 --root=PATH PATH to the kernel tree root
73 --no-summary suppress the per-file summary
74 --mailback only produce a report in case of warnings/errors
75 --summary-file include the filename in summary
76 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
77 'values', 'possible', 'type', and 'attr' (default
79 --test-only=WORD report only warnings/errors containing WORD
81 --fix EXPERIMENTAL - may create horrible results
82 If correctable single-line errors exist, create
83 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84 with potential errors corrected to the preferred
86 --fix-inplace EXPERIMENTAL - may create horrible results
87 Is the same as --fix, but overwrites the input
88 file. It's your fault if there's no backup or git
89 --ignore-perl-version override checking of perl version. expect
91 -h, --help, --version display this help and exit
93 When FILE is - read standard input.
99 my $conf = which_conf($configuration_file);
102 open(my $conffile, '<', "$conf")
103 or warn "$P: Can't find a readable $configuration_file file $!\n";
105 while (<$conffile>) {
108 $line =~ s/\s*\n?$//g;
112 next if ($line =~ m/^\s*#/);
113 next if ($line =~ m/^\s*$/);
115 my @words = split(" ", $line);
116 foreach my $word (@words) {
117 last if ($word =~ m/^#/);
118 push (@conf_args, $word);
122 unshift(@ARGV, @conf_args) if @conf_args;
126 'q|quiet+' => \$quiet,
128 'signoff!' => \$chk_signoff,
129 'patch!' => \$chk_patch,
133 'subjective!' => \$check,
134 'strict!' => \$check,
135 'ignore=s' => \@ignore,
137 'show-types!' => \$show_types,
138 'max-line-length=i' => \$max_line_length,
139 'min-conf-desc-length=i' => \$min_conf_desc_length,
141 'summary!' => \$summary,
142 'mailback!' => \$mailback,
143 'summary-file!' => \$summary_file,
145 'fix-inplace!' => \$fix_inplace,
146 'ignore-perl-version!' => \$ignore_perl_version,
147 'debug=s' => \%debug,
148 'test-only=s' => \$tst_only,
155 $fix = 1 if ($fix_inplace);
156 $check_orig = $check;
160 if ($^V && $^V lt $minimum_perl_version) {
161 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
162 if (!$ignore_perl_version) {
168 print "$P: no input files\n";
172 sub hash_save_array_words {
173 my ($hashRef, $arrayRef) = @_;
175 my @array = split(/,/, join(',', @$arrayRef));
176 foreach my $word (@array) {
177 $word =~ s/\s*\n?$//g;
180 $word =~ tr/[a-z]/[A-Z]/;
182 next if ($word =~ m/^\s*#/);
183 next if ($word =~ m/^\s*$/);
189 sub hash_show_words {
190 my ($hashRef, $prefix) = @_;
192 if ($quiet == 0 && keys %$hashRef) {
193 print "NOTE: $prefix message types:";
194 foreach my $word (sort keys %$hashRef) {
201 hash_save_array_words(\%ignore_type, \@ignore);
202 hash_save_array_words(\%use_type, \@use);
205 my $dbg_possible = 0;
208 for my $key (keys %debug) {
210 eval "\${dbg_$key} = '$debug{$key}';";
214 my $rpt_cleaners = 0;
223 if (!top_of_kernel_tree($root)) {
224 die "$P: $root: --root does not point at a valid tree\n";
227 if (top_of_kernel_tree('.')) {
229 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
230 top_of_kernel_tree($1)) {
235 if (!defined $root) {
236 print "Must be run from the top-level dir. of a kernel tree\n";
241 my $emitted_corrupt = 0;
244 [A-Za-z_][A-Za-z\d_]*
245 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
247 our $Storage = qr{extern|static|asmlinkage};
259 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
260 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
261 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
262 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
263 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
265 # Notes to $Attribute:
266 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
287 ____cacheline_aligned|
288 ____cacheline_aligned_in_smp|
289 ____cacheline_internodealigned_in_smp|
293 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
294 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
295 our $Lval = qr{$Ident(?:$Member)*};
297 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
298 our $Binary = qr{(?i)0b[01]+$Int_type?};
299 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
300 our $Int = qr{[0-9]+$Int_type?};
301 our $Octal = qr{0[0-7]+$Int_type?};
302 our $String = qr{"[X\t]*"};
303 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
304 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
305 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
306 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
307 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
308 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
309 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
310 our $Arithmetic = qr{\+|-|\*|\/|%};
314 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
317 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
320 our $NonptrTypeMisordered;
321 our $NonptrTypeWithAttr;
325 our $DeclareMisordered;
327 our $NON_ASCII_UTF8 = qr{
328 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
329 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
330 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
331 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
332 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
333 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
334 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
338 [\x09\x0A\x0D\x20-\x7E] # ASCII
342 our $typeTypedefs = qr{(?x:
343 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
347 our $logFunctions = qr{(?x:
348 printk(?:_ratelimited|_once|)|
349 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
350 WARN(?:_RATELIMIT|_ONCE|)|
353 seq_vprintf|seq_printf|seq_puts
356 our $signature_tags = qr{(?xi:
367 our @typeListMisordered = (
368 qr{char\s+(?:un)?signed},
369 qr{int\s+(?:(?:un)?signed\s+)?short\s},
370 qr{int\s+short(?:\s+(?:un)?signed)},
371 qr{short\s+int(?:\s+(?:un)?signed)},
372 qr{(?:un)?signed\s+int\s+short},
373 qr{short\s+(?:un)?signed},
374 qr{long\s+int\s+(?:un)?signed},
375 qr{int\s+long\s+(?:un)?signed},
376 qr{long\s+(?:un)?signed\s+int},
377 qr{int\s+(?:un)?signed\s+long},
378 qr{int\s+(?:un)?signed},
379 qr{int\s+long\s+long\s+(?:un)?signed},
380 qr{long\s+long\s+int\s+(?:un)?signed},
381 qr{long\s+long\s+(?:un)?signed\s+int},
382 qr{long\s+long\s+(?:un)?signed},
383 qr{long\s+(?:un)?signed},
388 qr{(?:(?:un)?signed\s+)?char},
389 qr{(?:(?:un)?signed\s+)?short\s+int},
390 qr{(?:(?:un)?signed\s+)?short},
391 qr{(?:(?:un)?signed\s+)?int},
392 qr{(?:(?:un)?signed\s+)?long\s+int},
393 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
394 qr{(?:(?:un)?signed\s+)?long\s+long},
395 qr{(?:(?:un)?signed\s+)?long},
404 qr{${Ident}_handler},
405 qr{${Ident}_handler_fn},
408 our @typeListWithAttr = (
410 qr{struct\s+$InitAttribute\s+$Ident},
411 qr{union\s+$InitAttribute\s+$Ident},
414 our @modifierList = (
418 our @mode_permission_funcs = (
420 ["module_param_(?:array|named|string)", 4],
421 ["module_param_array_named", 5],
422 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
423 ["proc_create(?:_data|)", 2],
424 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
427 #Create a search pattern for all these functions to speed up a loop below
428 our $mode_perms_search = "";
429 foreach my $entry (@mode_permission_funcs) {
430 $mode_perms_search .= '|' if ($mode_perms_search ne "");
431 $mode_perms_search .= $entry->[0];
434 our $allowed_asm_includes = qr{(?x:
440 # memory.h: ARM has a custom one
442 # Load common spelling mistakes and build regular expression list.
446 if (open(my $spelling, '<', $spelling_file)) {
448 while (<$spelling>) {
451 $line =~ s/\s*\n?$//g;
454 next if ($line =~ m/^\s*#/);
455 next if ($line =~ m/^\s*$/);
457 my ($suspect, $fix) = split(/\|\|/, $line);
459 push(@spelling_list, $suspect);
460 $spelling_fix{$suspect} = $fix;
463 $misspellings = join("|", @spelling_list);
465 warn "No typos will be found - file '$spelling_file': $!\n";
469 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
470 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
471 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
472 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
473 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
475 (?:$Modifier\s+|const\s+)*
477 (?:typeof|__typeof__)\s*\([^\)]*\)|
481 (?:\s+$Modifier|\s+const)*
483 $NonptrTypeMisordered = qr{
484 (?:$Modifier\s+|const\s+)*
488 (?:\s+$Modifier|\s+const)*
490 $NonptrTypeWithAttr = qr{
491 (?:$Modifier\s+|const\s+)*
493 (?:typeof|__typeof__)\s*\([^\)]*\)|
497 (?:\s+$Modifier|\s+const)*
501 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
502 (?:\s+$Inline|\s+$Modifier)*
504 $TypeMisordered = qr{
505 $NonptrTypeMisordered
506 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
507 (?:\s+$Inline|\s+$Modifier)*
509 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
510 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
514 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
516 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
517 # requires at least perl version v5.10.0
518 # Any use must be runtime checked with $^V
520 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
521 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
522 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
524 our $declaration_macros = qr{(?x:
525 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
526 (?:$Storage\s+)?LIST_HEAD\s*\(|
527 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
532 return "" if (!defined($string));
534 while ($string =~ /^\s*\(.*\)\s*$/) {
535 $string =~ s@^\s*\(\s*@@;
536 $string =~ s@\s*\)\s*$@@;
539 $string =~ s@\s+@ @g;
544 sub seed_camelcase_file {
547 return if (!(-f $file));
551 open(my $include_file, '<', "$file")
552 or warn "$P: Can't read '$file' $!\n";
553 my $text = <$include_file>;
554 close($include_file);
556 my @lines = split('\n', $text);
558 foreach my $line (@lines) {
559 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
560 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
562 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
564 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
570 my $camelcase_seeded = 0;
571 sub seed_camelcase_includes {
572 return if ($camelcase_seeded);
575 my $camelcase_cache = "";
576 my @include_files = ();
578 $camelcase_seeded = 1;
581 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
582 chomp $git_last_include_commit;
583 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
585 my $last_mod_date = 0;
586 $files = `find $root/include -name "*.h"`;
587 @include_files = split('\n', $files);
588 foreach my $file (@include_files) {
589 my $date = POSIX::strftime("%Y%m%d%H%M",
590 localtime((stat $file)[9]));
591 $last_mod_date = $date if ($last_mod_date < $date);
593 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
596 if ($camelcase_cache ne "" && -f $camelcase_cache) {
597 open(my $camelcase_file, '<', "$camelcase_cache")
598 or warn "$P: Can't read '$camelcase_cache' $!\n";
599 while (<$camelcase_file>) {
603 close($camelcase_file);
609 $files = `git ls-files "include/*.h"`;
610 @include_files = split('\n', $files);
613 foreach my $file (@include_files) {
614 seed_camelcase_file($file);
617 if ($camelcase_cache ne "") {
618 unlink glob ".checkpatch-camelcase.*";
619 open(my $camelcase_file, '>', "$camelcase_cache")
620 or warn "$P: Can't write '$camelcase_cache' $!\n";
621 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
622 print $camelcase_file ("$_\n");
624 close($camelcase_file);
628 sub git_commit_info {
629 my ($commit, $id, $desc) = @_;
631 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
633 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
634 $output =~ s/^\s*//gm;
635 my @lines = split("\n", $output);
637 return ($id, $desc) if ($#lines < 0);
639 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
640 # Maybe one day convert this block of bash into something that returns
641 # all matching commit ids, but it's very slow...
643 # echo "checking commits $1..."
644 # git rev-list --remotes | grep -i "^$1" |
645 # while read line ; do
646 # git log --format='%H %s' -1 $line |
647 # echo "commit $(cut -c 1-12,41-)"
649 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
651 $id = substr($lines[0], 0, 12);
652 $desc = substr($lines[0], 41);
658 $chk_signoff = 0 if ($file);
663 my @fixed_inserted = ();
664 my @fixed_deleted = ();
668 for my $filename (@ARGV) {
671 open($FILE, '-|', "diff -u /dev/null $filename") ||
672 die "$P: $filename: diff failed - $!\n";
673 } elsif ($filename eq '-') {
674 open($FILE, '<&STDIN');
676 open($FILE, '<', "$filename") ||
677 die "$P: $filename: open failed - $!\n";
679 if ($filename eq '-') {
680 $vname = 'Your patch';
689 if (!process($filename)) {
695 @fixed_inserted = ();
702 sub top_of_kernel_tree {
706 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
707 "README", "Documentation", "arch", "include", "drivers",
708 "fs", "init", "ipc", "kernel", "lib", "scripts",
711 foreach my $check (@tree_check) {
712 if (! -e $root . '/' . $check) {
720 my ($formatted_email) = @_;
726 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
729 $comment = $3 if defined $3;
730 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
732 $comment = $2 if defined $2;
733 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
735 $comment = $2 if defined $2;
736 $formatted_email =~ s/$address.*$//;
737 $name = $formatted_email;
739 $name =~ s/^\"|\"$//g;
740 # If there's a name left after stripping spaces and
741 # leading quotes, and the address doesn't have both
742 # leading and trailing angle brackets, the address
744 # "joe smith joe@smith.com" bad
745 # "joe smith <joe@smith.com" bad
746 if ($name ne "" && $address !~ /^<[^>]+>$/) {
754 $name =~ s/^\"|\"$//g;
755 $address = trim($address);
756 $address =~ s/^\<|\>$//g;
758 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
759 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
763 return ($name, $address, $comment);
767 my ($name, $address) = @_;
772 $name =~ s/^\"|\"$//g;
773 $address = trim($address);
775 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
776 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
781 $formatted_email = "$address";
783 $formatted_email = "$name <$address>";
786 return $formatted_email;
792 foreach my $path (split(/:/, $ENV{PATH})) {
793 if (-e "$path/$bin") {
804 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
805 if (-e "$path/$conf") {
806 return "$path/$conf";
818 for my $c (split(//, $str)) {
822 for (; ($n % 8) != 0; $n++) {
834 (my $res = shift) =~ tr/\t/ /c;
841 # Drop the diff line leader and expand tabs
843 $line = expand_tabs($line);
845 # Pick the indent from the front of the line.
846 my ($white) = ($line =~ /^(\s*)/);
848 return (length($line), length($white));
851 my $sanitise_quote = '';
853 sub sanitise_line_reset {
854 my ($in_comment) = @_;
857 $sanitise_quote = '*/';
859 $sanitise_quote = '';
872 # Always copy over the diff marker.
873 $res = substr($line, 0, 1);
875 for ($off = 1; $off < length($line); $off++) {
876 $c = substr($line, $off, 1);
878 # Comments we are wacking completly including the begin
879 # and end, all to $;.
880 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
881 $sanitise_quote = '*/';
883 substr($res, $off, 2, "$;$;");
887 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
888 $sanitise_quote = '';
889 substr($res, $off, 2, "$;$;");
893 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
894 $sanitise_quote = '//';
896 substr($res, $off, 2, $sanitise_quote);
901 # A \ in a string means ignore the next character.
902 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
904 substr($res, $off, 2, 'XX');
909 if ($c eq "'" || $c eq '"') {
910 if ($sanitise_quote eq '') {
911 $sanitise_quote = $c;
913 substr($res, $off, 1, $c);
915 } elsif ($sanitise_quote eq $c) {
916 $sanitise_quote = '';
920 #print "c<$c> SQ<$sanitise_quote>\n";
921 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
922 substr($res, $off, 1, $;);
923 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
924 substr($res, $off, 1, $;);
925 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
926 substr($res, $off, 1, 'X');
928 substr($res, $off, 1, $c);
932 if ($sanitise_quote eq '//') {
933 $sanitise_quote = '';
936 # The pathname on a #include may be surrounded by '<' and '>'.
937 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
938 my $clean = 'X' x length($1);
939 $res =~ s@\<.*\>@<$clean>@;
941 # The whole of a #error is a string.
942 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
943 my $clean = 'X' x length($1);
944 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
950 sub get_quoted_string {
951 my ($line, $rawline) = @_;
953 return "" if ($line !~ m/(\"[X\t]+\")/g);
954 return substr($rawline, $-[0], $+[0] - $-[0]);
957 sub ctx_statement_block {
958 my ($linenr, $remain, $off) = @_;
959 my $line = $linenr - 1;
976 @stack = (['', 0]) if ($#stack == -1);
978 #warn "CSB: blk<$blk> remain<$remain>\n";
979 # If we are about to drop off the end, pull in more
982 for (; $remain > 0; $line++) {
983 last if (!defined $lines[$line]);
984 next if ($lines[$line] =~ /^-/);
987 $blk .= $lines[$line] . "\n";
992 # Bail if there is no further context.
993 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
997 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1003 $c = substr($blk, $off, 1);
1004 $remainder = substr($blk, $off);
1006 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1008 # Handle nested #if/#else.
1009 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1010 push(@stack, [ $type, $level ]);
1011 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1012 ($type, $level) = @{$stack[$#stack - 1]};
1013 } elsif ($remainder =~ /^#\s*endif\b/) {
1014 ($type, $level) = @{pop(@stack)};
1017 # Statement ends at the ';' or a close '}' at the
1019 if ($level == 0 && $c eq ';') {
1023 # An else is really a conditional as long as its not else if
1024 if ($level == 0 && $coff_set == 0 &&
1025 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1026 $remainder =~ /^(else)(?:\s|{)/ &&
1027 $remainder !~ /^else\s+if\b/) {
1028 $coff = $off + length($1) - 1;
1030 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1031 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1034 if (($type eq '' || $type eq '(') && $c eq '(') {
1038 if ($type eq '(' && $c eq ')') {
1040 $type = ($level != 0)? '(' : '';
1042 if ($level == 0 && $coff < $soff) {
1045 #warn "CSB: mark coff<$coff>\n";
1048 if (($type eq '' || $type eq '{') && $c eq '{') {
1052 if ($type eq '{' && $c eq '}') {
1054 $type = ($level != 0)? '{' : '';
1057 if (substr($blk, $off + 1, 1) eq ';') {
1063 # Preprocessor commands end at the newline unless escaped.
1064 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1072 # We are truly at the end, so shuffle to the next line.
1079 my $statement = substr($blk, $soff, $off - $soff + 1);
1080 my $condition = substr($blk, $soff, $coff - $soff + 1);
1082 #warn "STATEMENT<$statement>\n";
1083 #warn "CONDITION<$condition>\n";
1085 #print "coff<$coff> soff<$off> loff<$loff>\n";
1087 return ($statement, $condition,
1088 $line, $remain + 1, $off - $loff + 1, $level);
1091 sub statement_lines {
1094 # Strip the diff line prefixes and rip blank lines at start and end.
1095 $stmt =~ s/(^|\n)./$1/g;
1099 my @stmt_lines = ($stmt =~ /\n/g);
1101 return $#stmt_lines + 2;
1104 sub statement_rawlines {
1107 my @stmt_lines = ($stmt =~ /\n/g);
1109 return $#stmt_lines + 2;
1112 sub statement_block_size {
1115 $stmt =~ s/(^|\n)./$1/g;
1121 my @stmt_lines = ($stmt =~ /\n/g);
1122 my @stmt_statements = ($stmt =~ /;/g);
1124 my $stmt_lines = $#stmt_lines + 2;
1125 my $stmt_statements = $#stmt_statements + 1;
1127 if ($stmt_lines > $stmt_statements) {
1130 return $stmt_statements;
1134 sub ctx_statement_full {
1135 my ($linenr, $remain, $off) = @_;
1136 my ($statement, $condition, $level);
1140 # Grab the first conditional/block pair.
1141 ($statement, $condition, $linenr, $remain, $off, $level) =
1142 ctx_statement_block($linenr, $remain, $off);
1143 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1144 push(@chunks, [ $condition, $statement ]);
1145 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1146 return ($level, $linenr, @chunks);
1149 # Pull in the following conditional/block pairs and see if they
1150 # could continue the statement.
1152 ($statement, $condition, $linenr, $remain, $off, $level) =
1153 ctx_statement_block($linenr, $remain, $off);
1154 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1155 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1157 push(@chunks, [ $condition, $statement ]);
1160 return ($level, $linenr, @chunks);
1164 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1166 my $start = $linenr - 1;
1173 my @stack = ($level);
1174 for ($line = $start; $remain > 0; $line++) {
1175 next if ($rawlines[$line] =~ /^-/);
1178 $blk .= $rawlines[$line];
1180 # Handle nested #if/#else.
1181 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1182 push(@stack, $level);
1183 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1184 $level = $stack[$#stack - 1];
1185 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1186 $level = pop(@stack);
1189 foreach my $c (split(//, $lines[$line])) {
1190 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1196 if ($c eq $close && $level > 0) {
1198 last if ($level == 0);
1199 } elsif ($c eq $open) {
1204 if (!$outer || $level <= 1) {
1205 push(@res, $rawlines[$line]);
1208 last if ($level == 0);
1211 return ($level, @res);
1213 sub ctx_block_outer {
1214 my ($linenr, $remain) = @_;
1216 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1220 my ($linenr, $remain) = @_;
1222 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1226 my ($linenr, $remain, $off) = @_;
1228 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1231 sub ctx_block_level {
1232 my ($linenr, $remain) = @_;
1234 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1236 sub ctx_statement_level {
1237 my ($linenr, $remain, $off) = @_;
1239 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1242 sub ctx_locate_comment {
1243 my ($first_line, $end_line) = @_;
1245 # Catch a comment on the end of the line itself.
1246 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1247 return $current_comment if (defined $current_comment);
1249 # Look through the context and try and figure out if there is a
1252 $current_comment = '';
1253 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1254 my $line = $rawlines[$linenr - 1];
1256 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1259 if ($line =~ m@/\*@) {
1262 if (!$in_comment && $current_comment ne '') {
1263 $current_comment = '';
1265 $current_comment .= $line . "\n" if ($in_comment);
1266 if ($line =~ m@\*/@) {
1271 chomp($current_comment);
1272 return($current_comment);
1274 sub ctx_has_comment {
1275 my ($first_line, $end_line) = @_;
1276 my $cmt = ctx_locate_comment($first_line, $end_line);
1278 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1279 ##print "CMMT: $cmt\n";
1281 return ($cmt ne '');
1285 my ($linenr, $cnt) = @_;
1287 my $offset = $linenr - 1;
1292 $line = $rawlines[$offset++];
1293 next if (defined($line) && $line =~ /^-/);
1305 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1308 $coded = sprintf("^%c", unpack('C', $2) + 64);
1317 my $av_preprocessor = 0;
1322 sub annotate_reset {
1323 $av_preprocessor = 0;
1325 @av_paren_type = ('E');
1326 $av_pend_colon = 'O';
1329 sub annotate_values {
1330 my ($stream, $type) = @_;
1333 my $var = '_' x length($stream);
1336 print "$stream\n" if ($dbg_values > 1);
1338 while (length($cur)) {
1339 @av_paren_type = ('E') if ($#av_paren_type < 0);
1340 print " <" . join('', @av_paren_type) .
1341 "> <$type> <$av_pending>" if ($dbg_values > 1);
1342 if ($cur =~ /^(\s+)/o) {
1343 print "WS($1)\n" if ($dbg_values > 1);
1344 if ($1 =~ /\n/ && $av_preprocessor) {
1345 $type = pop(@av_paren_type);
1346 $av_preprocessor = 0;
1349 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1350 print "CAST($1)\n" if ($dbg_values > 1);
1351 push(@av_paren_type, $type);
1354 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1355 print "DECLARE($1)\n" if ($dbg_values > 1);
1358 } elsif ($cur =~ /^($Modifier)\s*/) {
1359 print "MODIFIER($1)\n" if ($dbg_values > 1);
1362 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1363 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1364 $av_preprocessor = 1;
1365 push(@av_paren_type, $type);
1371 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1372 print "UNDEF($1)\n" if ($dbg_values > 1);
1373 $av_preprocessor = 1;
1374 push(@av_paren_type, $type);
1376 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1377 print "PRE_START($1)\n" if ($dbg_values > 1);
1378 $av_preprocessor = 1;
1380 push(@av_paren_type, $type);
1381 push(@av_paren_type, $type);
1384 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1385 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1386 $av_preprocessor = 1;
1388 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1392 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1393 print "PRE_END($1)\n" if ($dbg_values > 1);
1395 $av_preprocessor = 1;
1397 # Assume all arms of the conditional end as this
1398 # one does, and continue as if the #endif was not here.
1399 pop(@av_paren_type);
1400 push(@av_paren_type, $type);
1403 } elsif ($cur =~ /^(\\\n)/o) {
1404 print "PRECONT($1)\n" if ($dbg_values > 1);
1406 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1407 print "ATTR($1)\n" if ($dbg_values > 1);
1408 $av_pending = $type;
1411 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1412 print "SIZEOF($1)\n" if ($dbg_values > 1);
1418 } elsif ($cur =~ /^(if|while|for)\b/o) {
1419 print "COND($1)\n" if ($dbg_values > 1);
1423 } elsif ($cur =~/^(case)/o) {
1424 print "CASE($1)\n" if ($dbg_values > 1);
1425 $av_pend_colon = 'C';
1428 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1429 print "KEYWORD($1)\n" if ($dbg_values > 1);
1432 } elsif ($cur =~ /^(\()/o) {
1433 print "PAREN('$1')\n" if ($dbg_values > 1);
1434 push(@av_paren_type, $av_pending);
1438 } elsif ($cur =~ /^(\))/o) {
1439 my $new_type = pop(@av_paren_type);
1440 if ($new_type ne '_') {
1442 print "PAREN('$1') -> $type\n"
1443 if ($dbg_values > 1);
1445 print "PAREN('$1')\n" if ($dbg_values > 1);
1448 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1449 print "FUNC($1)\n" if ($dbg_values > 1);
1453 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1454 if (defined $2 && $type eq 'C' || $type eq 'T') {
1455 $av_pend_colon = 'B';
1456 } elsif ($type eq 'E') {
1457 $av_pend_colon = 'L';
1459 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1462 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1463 print "IDENT($1)\n" if ($dbg_values > 1);
1466 } elsif ($cur =~ /^($Assignment)/o) {
1467 print "ASSIGN($1)\n" if ($dbg_values > 1);
1470 } elsif ($cur =~/^(;|{|})/) {
1471 print "END($1)\n" if ($dbg_values > 1);
1473 $av_pend_colon = 'O';
1475 } elsif ($cur =~/^(,)/) {
1476 print "COMMA($1)\n" if ($dbg_values > 1);
1479 } elsif ($cur =~ /^(\?)/o) {
1480 print "QUESTION($1)\n" if ($dbg_values > 1);
1483 } elsif ($cur =~ /^(:)/o) {
1484 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1486 substr($var, length($res), 1, $av_pend_colon);
1487 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1492 $av_pend_colon = 'O';
1494 } elsif ($cur =~ /^(\[)/o) {
1495 print "CLOSE($1)\n" if ($dbg_values > 1);
1498 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1501 print "OPV($1)\n" if ($dbg_values > 1);
1508 substr($var, length($res), 1, $variant);
1511 } elsif ($cur =~ /^($Operators)/o) {
1512 print "OP($1)\n" if ($dbg_values > 1);
1513 if ($1 ne '++' && $1 ne '--') {
1517 } elsif ($cur =~ /(^.)/o) {
1518 print "C($1)\n" if ($dbg_values > 1);
1521 $cur = substr($cur, length($1));
1522 $res .= $type x length($1);
1526 return ($res, $var);
1530 my ($possible, $line) = @_;
1531 my $notPermitted = qr{(?:
1548 ^(?:typedef|struct|enum)\b
1550 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1551 if ($possible !~ $notPermitted) {
1552 # Check for modifiers.
1553 $possible =~ s/\s*$Storage\s*//g;
1554 $possible =~ s/\s*$Sparse\s*//g;
1555 if ($possible =~ /^\s*$/) {
1557 } elsif ($possible =~ /\s/) {
1558 $possible =~ s/\s*$Type\s*//g;
1559 for my $modifier (split(' ', $possible)) {
1560 if ($modifier !~ $notPermitted) {
1561 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1562 push(@modifierList, $modifier);
1567 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1568 push(@typeList, $possible);
1572 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1581 return defined $use_type{$type} if (scalar keys %use_type > 0);
1583 return !defined $ignore_type{$type};
1587 my ($level, $type, $msg) = @_;
1589 if (!show_type($type) ||
1590 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1595 $line = "$prefix$level:$type: $msg\n";
1597 $line = "$prefix$level: $msg\n";
1599 $line = (split('\n', $line))[0] . "\n" if ($terse);
1601 push(our @report, $line);
1610 sub fixup_current_range {
1611 my ($lineRef, $offset, $length) = @_;
1613 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1616 my $no = $o + $offset;
1617 my $nl = $l + $length;
1618 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1622 sub fix_inserted_deleted_lines {
1623 my ($linesRef, $insertedRef, $deletedRef) = @_;
1625 my $range_last_linenr = 0;
1626 my $delta_offset = 0;
1631 my $next_insert = 0;
1632 my $next_delete = 0;
1636 my $inserted = @{$insertedRef}[$next_insert++];
1637 my $deleted = @{$deletedRef}[$next_delete++];
1639 foreach my $old_line (@{$linesRef}) {
1641 my $line = $old_line; #don't modify the array
1642 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1644 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1645 $range_last_linenr = $new_linenr;
1646 fixup_current_range(\$line, $delta_offset, 0);
1649 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1650 $deleted = @{$deletedRef}[$next_delete++];
1652 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1655 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1656 push(@lines, ${$inserted}{'LINE'});
1657 $inserted = @{$insertedRef}[$next_insert++];
1659 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1663 push(@lines, $line);
1673 sub fix_insert_line {
1674 my ($linenr, $line) = @_;
1680 push(@fixed_inserted, $inserted);
1683 sub fix_delete_line {
1684 my ($linenr, $line) = @_;
1691 push(@fixed_deleted, $deleted);
1695 my ($type, $msg) = @_;
1697 if (report("ERROR", $type, $msg)) {
1705 my ($type, $msg) = @_;
1707 if (report("WARNING", $type, $msg)) {
1715 my ($type, $msg) = @_;
1717 if ($check && report("CHECK", $type, $msg)) {
1725 sub check_absolute_file {
1726 my ($absolute, $herecurr) = @_;
1727 my $file = $absolute;
1729 ##print "absolute<$absolute>\n";
1731 # See if any suffix of this path is a path within the tree.
1732 while ($file =~ s@^[^/]*/@@) {
1733 if (-f "$root/$file") {
1734 ##print "file<$file>\n";
1742 # It is, so see if the prefix is acceptable.
1743 my $prefix = $absolute;
1744 substr($prefix, -length($file)) = '';
1746 ##print "prefix<$prefix>\n";
1747 if ($prefix ne ".../") {
1748 WARN("USE_RELATIVE_PATH",
1749 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1756 $string =~ s/^\s+|\s+$//g;
1764 $string =~ s/^\s+//;
1772 $string =~ s/\s+$//;
1777 sub string_find_replace {
1778 my ($string, $find, $replace) = @_;
1780 $string =~ s/$find/$replace/g;
1788 my $source_indent = 8;
1789 my $max_spaces_before_tab = $source_indent - 1;
1790 my $spaces_to_tab = " " x $source_indent;
1792 #convert leading spaces to tabs
1793 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1794 #Remove spaces before a tab
1795 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1800 sub pos_last_openparen {
1805 my $opens = $line =~ tr/\(/\(/;
1806 my $closes = $line =~ tr/\)/\)/;
1808 my $last_openparen = 0;
1810 if (($opens == 0) || ($closes >= $opens)) {
1814 my $len = length($line);
1816 for ($pos = 0; $pos < $len; $pos++) {
1817 my $string = substr($line, $pos);
1818 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1819 $pos += length($1) - 1;
1820 } elsif (substr($line, $pos, 1) eq '(') {
1821 $last_openparen = $pos;
1822 } elsif (index($string, '(') == -1) {
1827 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1831 my $filename = shift;
1837 my $stashrawline="";
1848 my $in_header_lines = $file ? 0 : 1;
1849 my $in_commit_log = 0; #Scanning lines before patch
1850 my $reported_maintainer_file = 0;
1851 my $non_utf8_charset = 0;
1853 my $last_blank_line = 0;
1854 my $last_coalesced_string_linenr = -1;
1862 # Trace the real file/line as we go.
1868 my $comment_edge = 0;
1872 my $prev_values = 'E';
1875 my %suppress_ifbraces;
1876 my %suppress_whiletrailers;
1877 my %suppress_export;
1878 my $suppress_statement = 0;
1880 my %signatures = ();
1882 # Pre-scan the patch sanitizing the lines.
1883 # Pre-scan the patch looking for any __setup documentation.
1885 my @setup_docs = ();
1888 my $camelcase_file_seeded = 0;
1890 sanitise_line_reset();
1892 foreach my $rawline (@rawlines) {
1896 push(@fixed, $rawline) if ($fix);
1898 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1900 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1905 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1914 # Guestimate if this is a continuing comment. Run
1915 # the context looking for a comment "edge". If this
1916 # edge is a close comment then we must be in a comment
1920 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1921 next if (defined $rawlines[$ln - 1] &&
1922 $rawlines[$ln - 1] =~ /^-/);
1924 #print "RAW<$rawlines[$ln - 1]>\n";
1925 last if (!defined $rawlines[$ln - 1]);
1926 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1927 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1932 if (defined $edge && $edge eq '*/') {
1936 # Guestimate if this is a continuing comment. If this
1937 # is the start of a diff block and this line starts
1938 # ' *' then it is very likely a comment.
1939 if (!defined $edge &&
1940 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1945 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1946 sanitise_line_reset($in_comment);
1948 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1949 # Standardise the strings and chars within the input to
1950 # simplify matching -- only bother with positive lines.
1951 $line = sanitise_line($rawline);
1953 push(@lines, $line);
1956 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1961 #print "==>$rawline\n";
1962 #print "-->$line\n";
1964 if ($setup_docs && $line =~ /^\+/) {
1965 push(@setup_docs, $line);
1974 foreach my $line (@lines) {
1977 my $sline = $line; #copy of $line
1978 $sline =~ s/$;/ /g; #with comments as spaces
1980 my $rawline = $rawlines[$linenr - 1];
1982 #extract the line range in the file after the patch is applied
1983 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1985 $first_line = $linenr + 1;
1995 %suppress_ifbraces = ();
1996 %suppress_whiletrailers = ();
1997 %suppress_export = ();
1998 $suppress_statement = 0;
2001 # track the line number as we move through the hunk, note that
2002 # new versions of GNU diff omit the leading space on completely
2003 # blank context lines so we need to count that too.
2004 } elsif ($line =~ /^( |\+|$)/) {
2006 $realcnt-- if ($realcnt != 0);
2008 # Measure the line length and indent.
2009 ($length, $indent) = line_stats($rawline);
2011 # Track the previous line.
2012 ($prevline, $stashline) = ($stashline, $line);
2013 ($previndent, $stashindent) = ($stashindent, $indent);
2014 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2016 #warn "line<$line>\n";
2018 } elsif ($realcnt == 1) {
2022 my $hunk_line = ($realcnt != 0);
2024 #make up the handle for any error we report on this line
2025 $prefix = "$filename:$realline: " if ($emacs && $file);
2026 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2028 $here = "#$linenr: " if (!$file);
2029 $here = "#$realline: " if ($file);
2032 # extract the filename as it passes
2033 if ($line =~ /^diff --git.*?(\S+)$/) {
2035 $realfile =~ s@^([^/]*)/@@ if (!$file);
2038 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2040 $realfile =~ s@^([^/]*)/@@ if (!$file);
2044 if (!$file && $tree && $p1_prefix ne '' &&
2045 -e "$root/$p1_prefix") {
2046 WARN("PATCH_PREFIX",
2047 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2050 if ($realfile =~ m@^include/asm/@) {
2051 ERROR("MODIFIED_INCLUDE_ASM",
2052 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2058 if ($realfile =~ m@^(drivers/net/|net/)@) {
2061 $check = $check_orig;
2066 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2068 my $hereline = "$here\n$rawline\n";
2069 my $herecurr = "$here\n$rawline\n";
2070 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2072 $cnt_lines++ if ($realcnt != 0);
2074 # Check for incorrect file permissions
2075 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2076 my $permhere = $here . "FILE: $realfile\n";
2077 if ($realfile !~ m@scripts/@ &&
2078 $realfile !~ /\.(py|pl|awk|sh)$/) {
2079 ERROR("EXECUTE_PERMISSIONS",
2080 "do not set execute permissions for source files\n" . $permhere);
2084 # Check the patch for a signoff:
2085 if ($line =~ /^\s*signed-off-by:/i) {
2090 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2091 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2092 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2093 $reported_maintainer_file = 1;
2096 # Check signature styles
2097 if (!$in_header_lines &&
2098 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2099 my $space_before = $1;
2101 my $space_after = $3;
2103 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2105 if ($sign_off !~ /$signature_tags/) {
2106 WARN("BAD_SIGN_OFF",
2107 "Non-standard signature: $sign_off\n" . $herecurr);
2109 if (defined $space_before && $space_before ne "") {
2110 if (WARN("BAD_SIGN_OFF",
2111 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2113 $fixed[$fixlinenr] =
2114 "$ucfirst_sign_off $email";
2117 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2118 if (WARN("BAD_SIGN_OFF",
2119 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2121 $fixed[$fixlinenr] =
2122 "$ucfirst_sign_off $email";
2126 if (!defined $space_after || $space_after ne " ") {
2127 if (WARN("BAD_SIGN_OFF",
2128 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2130 $fixed[$fixlinenr] =
2131 "$ucfirst_sign_off $email";
2135 my ($email_name, $email_address, $comment) = parse_email($email);
2136 my $suggested_email = format_email(($email_name, $email_address));
2137 if ($suggested_email eq "") {
2138 ERROR("BAD_SIGN_OFF",
2139 "Unrecognized email address: '$email'\n" . $herecurr);
2141 my $dequoted = $suggested_email;
2142 $dequoted =~ s/^"//;
2143 $dequoted =~ s/" </ </;
2144 # Don't force email to have quotes
2145 # Allow just an angle bracketed address
2146 if ("$dequoted$comment" ne $email &&
2147 "<$email_address>$comment" ne $email &&
2148 "$suggested_email$comment" ne $email) {
2149 WARN("BAD_SIGN_OFF",
2150 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2154 # Check for duplicate signatures
2155 my $sig_nospace = $line;
2156 $sig_nospace =~ s/\s//g;
2157 $sig_nospace = lc($sig_nospace);
2158 if (defined $signatures{$sig_nospace}) {
2159 WARN("BAD_SIGN_OFF",
2160 "Duplicate signature\n" . $herecurr);
2162 $signatures{$sig_nospace} = 1;
2166 # Check for old stable address
2167 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2168 ERROR("STABLE_ADDRESS",
2169 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2172 # Check for unwanted Gerrit info
2173 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2174 ERROR("GERRIT_CHANGE_ID",
2175 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2178 # Check for git id commit length and improperly formed commit descriptions
2179 if ($in_commit_log && $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i) {
2181 my $orig_commit = lc($2);
2187 my $id = '0123456789ab';
2188 my $orig_desc = "commit description";
2189 my $description = "";
2191 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2192 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2193 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2194 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2195 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2197 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2198 defined $rawlines[$linenr] &&
2199 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2203 ($id, $description) = git_commit_info($orig_commit,
2206 if ($short || $long || $space || $case || ($orig_desc ne $description)) {
2207 ERROR("GIT_COMMIT_ID",
2208 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2212 # Check for added, moved or deleted files
2213 if (!$reported_maintainer_file && !$in_commit_log &&
2214 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2215 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2216 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2217 (defined($1) || defined($2))))) {
2218 $reported_maintainer_file = 1;
2219 WARN("FILE_PATH_CHANGES",
2220 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2223 # Check for wrappage within a valid hunk of the file
2224 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2225 ERROR("CORRUPTED_PATCH",
2226 "patch seems to be corrupt (line wrapped?)\n" .
2227 $herecurr) if (!$emitted_corrupt++);
2230 # Check for absolute kernel paths.
2232 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2235 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2236 check_absolute_file($1, $herecurr)) {
2239 check_absolute_file($file, $herecurr);
2244 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2245 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2246 $rawline !~ m/^$UTF8*$/) {
2247 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2249 my $blank = copy_spacing($rawline);
2250 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2251 my $hereptr = "$hereline$ptr\n";
2254 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2257 # Check if it's the start of a commit log
2258 # (not a header line and we haven't seen the patch filename)
2259 if ($in_header_lines && $realfile =~ /^$/ &&
2260 !($rawline =~ /^\s+\S/ ||
2261 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2262 $in_header_lines = 0;
2266 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2267 # declined it, i.e defined some charset where it is missing.
2268 if ($in_header_lines &&
2269 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2271 $non_utf8_charset = 1;
2274 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2275 $rawline =~ /$NON_ASCII_UTF8/) {
2276 WARN("UTF8_BEFORE_PATCH",
2277 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2280 # Check for various typo / spelling mistakes
2281 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2282 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2284 my $typo_fix = $spelling_fix{lc($typo)};
2285 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2286 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2287 my $msg_type = \&WARN;
2288 $msg_type = \&CHK if ($file);
2289 if (&{$msg_type}("TYPO_SPELLING",
2290 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2292 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2297 # ignore non-hunk lines and lines being removed
2298 next if (!$hunk_line || $line =~ /^-/);
2300 #trailing whitespace
2301 if ($line =~ /^\+.*\015/) {
2302 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2303 if (ERROR("DOS_LINE_ENDINGS",
2304 "DOS line endings\n" . $herevet) &&
2306 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2308 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2309 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2310 if (ERROR("TRAILING_WHITESPACE",
2311 "trailing whitespace\n" . $herevet) &&
2313 $fixed[$fixlinenr] =~ s/\s+$//;
2319 # Check for FSF mailing addresses.
2320 if ($rawline =~ /\bwrite to the Free/i ||
2321 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2322 $rawline =~ /\b51\s+Franklin\s+St/i) {
2323 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2324 my $msg_type = \&ERROR;
2325 $msg_type = \&CHK if ($file);
2326 &{$msg_type}("FSF_MAILING_ADDRESS",
2327 "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)
2330 # check for Kconfig help text having a real description
2331 # Only applies when adding the entry originally, after that we do not have
2332 # sufficient context to determine whether it is indeed long enough.
2333 if ($realfile =~ /Kconfig/ &&
2334 $line =~ /^\+\s*config\s+/) {
2337 my $ln = $linenr + 1;
2341 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2342 $f = $lines[$ln - 1];
2343 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2344 $is_end = $lines[$ln - 1] =~ /^\+/;
2346 next if ($f =~ /^-/);
2347 last if (!$file && $f =~ /^\@\@/);
2349 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2351 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2358 next if ($f =~ /^$/);
2359 if ($f =~ /^\s*config\s/) {
2365 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2366 WARN("CONFIG_DESCRIPTION",
2367 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2369 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2372 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2373 if ($realfile =~ /Kconfig/ &&
2374 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2375 WARN("CONFIG_EXPERIMENTAL",
2376 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2379 # discourage the use of boolean for type definition attributes of Kconfig options
2380 if ($realfile =~ /Kconfig/ &&
2381 $line =~ /^\+\s*\bboolean\b/) {
2382 WARN("CONFIG_TYPE_BOOLEAN",
2383 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2386 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2387 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2390 'EXTRA_AFLAGS' => 'asflags-y',
2391 'EXTRA_CFLAGS' => 'ccflags-y',
2392 'EXTRA_CPPFLAGS' => 'cppflags-y',
2393 'EXTRA_LDFLAGS' => 'ldflags-y',
2396 WARN("DEPRECATED_VARIABLE",
2397 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2400 # check for DT compatible documentation
2401 if (defined $root &&
2402 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2403 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2405 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2407 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2408 my $vp_file = $dt_path . "vendor-prefixes.txt";
2410 foreach my $compat (@compats) {
2411 my $compat2 = $compat;
2412 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2413 my $compat3 = $compat;
2414 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2415 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2417 WARN("UNDOCUMENTED_DT_STRING",
2418 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2421 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2423 `grep -Eq "^$vendor\\b" $vp_file`;
2425 WARN("UNDOCUMENTED_DT_STRING",
2426 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2431 # check we are in a valid source file if not then ignore this hunk
2432 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2435 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2436 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2437 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2438 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2439 $length > $max_line_length)
2442 "line over $max_line_length characters\n" . $herecurr);
2445 # check for adding lines without a newline.
2446 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2447 WARN("MISSING_EOF_NEWLINE",
2448 "adding a line without newline at end of file\n" . $herecurr);
2451 # Blackfin: use hi/lo macros
2452 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2453 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2454 my $herevet = "$here\n" . cat_vet($line) . "\n";
2456 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2458 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2459 my $herevet = "$here\n" . cat_vet($line) . "\n";
2461 "use the HI() macro, not (... >> 16)\n" . $herevet);
2465 # check we are in a valid source file C or perl if not then ignore this hunk
2466 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2468 # at the beginning of a line any tabs must come first and anything
2469 # more than 8 must use tabs.
2470 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2471 $rawline =~ /^\+\s* \s*/) {
2472 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2474 if (ERROR("CODE_INDENT",
2475 "code indent should use tabs where possible\n" . $herevet) &&
2477 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2481 # check for space before tabs.
2482 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2483 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2484 if (WARN("SPACE_BEFORE_TAB",
2485 "please, no space before tabs\n" . $herevet) &&
2487 while ($fixed[$fixlinenr] =~
2488 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2489 while ($fixed[$fixlinenr] =~
2490 s/(^\+.*) +\t/$1\t/) {}
2494 # check for && or || at the start of a line
2495 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2496 CHK("LOGICAL_CONTINUATIONS",
2497 "Logical continuations should be on the previous line\n" . $hereprev);
2500 # check multi-line statement indentation matches previous line
2501 if ($^V && $^V ge 5.10.0 &&
2502 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2503 $prevline =~ /^\+(\t*)(.*)$/;
2507 my $pos = pos_last_openparen($rest);
2509 $line =~ /^(\+| )([ \t]*)/;
2512 my $goodtabindent = $oldindent .
2515 my $goodspaceindent = $oldindent . " " x $pos;
2517 if ($newindent ne $goodtabindent &&
2518 $newindent ne $goodspaceindent) {
2520 if (CHK("PARENTHESIS_ALIGNMENT",
2521 "Alignment should match open parenthesis\n" . $hereprev) &&
2522 $fix && $line =~ /^\+/) {
2523 $fixed[$fixlinenr] =~
2524 s/^\+[ \t]*/\+$goodtabindent/;
2530 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;\({\[\<\>])/ &&
2531 (!defined($1) || $1 !~ /sizeof\s*/)) {
2533 "No space is necessary after a cast\n" . $herecurr) &&
2535 $fixed[$fixlinenr] =~
2536 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2540 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2541 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2542 $rawline =~ /^\+[ \t]*\*/ &&
2544 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2545 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2548 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2549 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2550 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2551 $rawline =~ /^\+/ && #line is new
2552 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2553 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2554 "networking block comments start with * on subsequent lines\n" . $hereprev);
2557 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2558 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2559 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2560 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2561 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2562 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2563 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2566 # check for missing blank lines after struct/union declarations
2567 # with exceptions for various attributes and macros
2568 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2570 !($line =~ /^\+\s*$/ ||
2571 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2572 $line =~ /^\+\s*MODULE_/i ||
2573 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2574 $line =~ /^\+[a-z_]*init/ ||
2575 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2576 $line =~ /^\+\s*DECLARE/ ||
2577 $line =~ /^\+\s*__setup/)) {
2578 if (CHK("LINE_SPACING",
2579 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2581 fix_insert_line($fixlinenr, "\+");
2585 # check for multiple consecutive blank lines
2586 if ($prevline =~ /^[\+ ]\s*$/ &&
2587 $line =~ /^\+\s*$/ &&
2588 $last_blank_line != ($linenr - 1)) {
2589 if (CHK("LINE_SPACING",
2590 "Please don't use multiple blank lines\n" . $hereprev) &&
2592 fix_delete_line($fixlinenr, $rawline);
2595 $last_blank_line = $linenr;
2598 # check for missing blank lines after declarations
2599 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2600 # actual declarations
2601 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2602 # function pointer declarations
2603 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2604 # foo bar; where foo is some local typedef or #define
2605 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2606 # known declaration macros
2607 $prevline =~ /^\+\s+$declaration_macros/) &&
2608 # for "else if" which can look like "$Ident $Ident"
2609 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2610 # other possible extensions of declaration lines
2611 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2612 # not starting a section or a macro "\" extended line
2613 $prevline =~ /(?:\{\s*|\\)$/) &&
2614 # looks like a declaration
2615 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2616 # function pointer declarations
2617 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2618 # foo bar; where foo is some local typedef or #define
2619 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2620 # known declaration macros
2621 $sline =~ /^\+\s+$declaration_macros/ ||
2622 # start of struct or union or enum
2623 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2624 # start or end of block or continuation of declaration
2625 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2626 # bitfield continuation
2627 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2628 # other possible extensions of declaration lines
2629 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2630 # indentation of previous and current line are the same
2631 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2632 if (WARN("LINE_SPACING",
2633 "Missing a blank line after declarations\n" . $hereprev) &&
2635 fix_insert_line($fixlinenr, "\+");
2639 # check for spaces at the beginning of a line.
2641 # 1) within comments
2642 # 2) indented preprocessor commands
2644 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2645 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2646 if (WARN("LEADING_SPACE",
2647 "please, no spaces at the start of a line\n" . $herevet) &&
2649 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2653 # check we are in a valid C source file if not then ignore this hunk
2654 next if ($realfile !~ /\.(h|c)$/);
2656 # check indentation of any line with a bare else
2657 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2658 # if the previous line is a break or return and is indented 1 tab more...
2659 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2660 my $tabs = length($1) + 1;
2661 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2662 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2663 defined $lines[$linenr] &&
2664 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2665 WARN("UNNECESSARY_ELSE",
2666 "else is not generally useful after a break or return\n" . $hereprev);
2670 # check indentation of a line with a break;
2671 # if the previous line is a goto or return and is indented the same # of tabs
2672 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2674 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2675 WARN("UNNECESSARY_BREAK",
2676 "break is not useful after a goto or return\n" . $hereprev);
2680 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2681 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2682 WARN("CONFIG_EXPERIMENTAL",
2683 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2686 # check for RCS/CVS revision markers
2687 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2689 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2692 # Blackfin: don't use __builtin_bfin_[cs]sync
2693 if ($line =~ /__builtin_bfin_csync/) {
2694 my $herevet = "$here\n" . cat_vet($line) . "\n";
2696 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2698 if ($line =~ /__builtin_bfin_ssync/) {
2699 my $herevet = "$here\n" . cat_vet($line) . "\n";
2701 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2704 # check for old HOTPLUG __dev<foo> section markings
2705 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2706 WARN("HOTPLUG_SECTION",
2707 "Using $1 is unnecessary\n" . $herecurr);
2710 # Check for potential 'bare' types
2711 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2713 #print "LINE<$line>\n";
2714 if ($linenr >= $suppress_statement &&
2715 $realcnt && $sline =~ /.\s*\S/) {
2716 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2717 ctx_statement_block($linenr, $realcnt, 0);
2718 $stat =~ s/\n./\n /g;
2719 $cond =~ s/\n./\n /g;
2721 #print "linenr<$linenr> <$stat>\n";
2722 # If this statement has no statement boundaries within
2723 # it there is no point in retrying a statement scan
2724 # until we hit end of it.
2725 my $frag = $stat; $frag =~ s/;+\s*$//;
2726 if ($frag !~ /(?:{|;)/) {
2727 #print "skip<$line_nr_next>\n";
2728 $suppress_statement = $line_nr_next;
2731 # Find the real next line.
2732 $realline_next = $line_nr_next;
2733 if (defined $realline_next &&
2734 (!defined $lines[$realline_next - 1] ||
2735 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2742 # Ignore goto labels.
2743 if ($s =~ /$Ident:\*$/s) {
2745 # Ignore functions being called
2746 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2748 } elsif ($s =~ /^.\s*else\b/s) {
2750 # declarations always start with types
2751 } 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) {
2754 possible($type, "A:" . $s);
2756 # definitions in global scope can only start with types
2757 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2758 possible($1, "B:" . $s);
2761 # any (foo ... *) is a pointer cast, and foo is a type
2762 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2763 possible($1, "C:" . $s);
2766 # Check for any sort of function declaration.
2767 # int foo(something bar, other baz);
2768 # void (*store_gdt)(x86_descr_ptr *);
2769 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2770 my ($name_len) = length($1);
2773 substr($ctx, 0, $name_len + 1, '');
2774 $ctx =~ s/\)[^\)]*$//;
2776 for my $arg (split(/\s*,\s*/, $ctx)) {
2777 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2779 possible($1, "D:" . $s);
2787 # Checks which may be anchored in the context.
2790 # Check for switch () and associated case and default
2791 # statements should be at the same indent.
2792 if ($line=~/\bswitch\s*\(.*\)/) {
2795 my @ctx = ctx_block_outer($linenr, $realcnt);
2797 for my $ctx (@ctx) {
2798 my ($clen, $cindent) = line_stats($ctx);
2799 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2800 $indent != $cindent) {
2801 $err .= "$sep$ctx\n";
2808 ERROR("SWITCH_CASE_INDENT_LEVEL",
2809 "switch and case should be at the same indent\n$hereline$err");
2813 # if/while/etc brace do not go on next line, unless defining a do while loop,
2814 # or if that brace on the next line is for something else
2815 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2816 my $pre_ctx = "$1$2";
2818 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2820 if ($line =~ /^\+\t{6,}/) {
2821 WARN("DEEP_INDENTATION",
2822 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2825 my $ctx_cnt = $realcnt - $#ctx - 1;
2826 my $ctx = join("\n", @ctx);
2828 my $ctx_ln = $linenr;
2829 my $ctx_skip = $realcnt;
2831 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2832 defined $lines[$ctx_ln - 1] &&
2833 $lines[$ctx_ln - 1] =~ /^-/)) {
2834 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2835 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2839 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2840 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2842 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2844 "that open brace { should be on the previous line\n" .
2845 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2847 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2848 $ctx =~ /\)\s*\;\s*$/ &&
2849 defined $lines[$ctx_ln - 1])
2851 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2852 if ($nindent > $indent) {
2853 WARN("TRAILING_SEMICOLON",
2854 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2855 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2860 # Check relative indent for conditionals and blocks.
2861 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2862 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2863 ctx_statement_block($linenr, $realcnt, 0)
2864 if (!defined $stat);
2865 my ($s, $c) = ($stat, $cond);
2867 substr($s, 0, length($c), '');
2869 # Make sure we remove the line prefixes as we have
2870 # none on the first line, and are going to readd them
2874 # Find out how long the conditional actually is.
2875 my @newlines = ($c =~ /\n/gs);
2876 my $cond_lines = 1 + $#newlines;
2878 # We want to check the first line inside the block
2879 # starting at the end of the conditional, so remove:
2880 # 1) any blank line termination
2881 # 2) any opening brace { on end of the line
2883 my $continuation = 0;
2885 $s =~ s/^.*\bdo\b//;
2887 if ($s =~ s/^\s*\\//) {
2890 if ($s =~ s/^\s*?\n//) {
2895 # Also ignore a loop construct at the end of a
2896 # preprocessor statement.
2897 if (($prevline =~ /^.\s*#\s*define\s/ ||
2898 $prevline =~ /\\\s*$/) && $continuation == 0) {
2904 while ($cond_ptr != $cond_lines) {
2905 $cond_ptr = $cond_lines;
2907 # If we see an #else/#elif then the code
2909 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2914 # 1) blank lines, they should be at 0,
2915 # 2) preprocessor lines, and
2917 if ($continuation ||
2919 $s =~ /^\s*#\s*?/ ||
2920 $s =~ /^\s*$Ident\s*:/) {
2921 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2922 if ($s =~ s/^.*?\n//) {
2928 my (undef, $sindent) = line_stats("+" . $s);
2929 my $stat_real = raw_line($linenr, $cond_lines);
2931 # Check if either of these lines are modified, else
2932 # this is not this patch's fault.
2933 if (!defined($stat_real) ||
2934 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2937 if (defined($stat_real) && $cond_lines > 1) {
2938 $stat_real = "[...]\n$stat_real";
2941 #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";
2943 if ($check && (($sindent % 8) != 0 ||
2944 ($sindent <= $indent && $s ne ''))) {
2945 WARN("SUSPECT_CODE_INDENT",
2946 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2950 # Track the 'values' across context and added lines.
2951 my $opline = $line; $opline =~ s/^./ /;
2952 my ($curr_values, $curr_vars) =
2953 annotate_values($opline . "\n", $prev_values);
2954 $curr_values = $prev_values . $curr_values;
2956 my $outline = $opline; $outline =~ s/\t/ /g;
2957 print "$linenr > .$outline\n";
2958 print "$linenr > $curr_values\n";
2959 print "$linenr > $curr_vars\n";
2961 $prev_values = substr($curr_values, -1);
2963 #ignore lines not being added
2964 next if ($line =~ /^[^\+]/);
2966 # TEST: allow direct testing of the type matcher.
2968 if ($line =~ /^.\s*$Declare\s*$/) {
2970 "TEST: is type\n" . $herecurr);
2971 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2972 ERROR("TEST_NOT_TYPE",
2973 "TEST: is not type ($1 is)\n". $herecurr);
2977 # TEST: allow direct testing of the attribute matcher.
2979 if ($line =~ /^.\s*$Modifier\s*$/) {
2981 "TEST: is attr\n" . $herecurr);
2982 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2983 ERROR("TEST_NOT_ATTR",
2984 "TEST: is not attr ($1 is)\n". $herecurr);
2989 # check for initialisation to aggregates open brace on the next line
2990 if ($line =~ /^.\s*{/ &&
2991 $prevline =~ /(?:^|[^=])=\s*$/) {
2992 if (ERROR("OPEN_BRACE",
2993 "that open brace { should be on the previous line\n" . $hereprev) &&
2994 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
2995 fix_delete_line($fixlinenr - 1, $prevrawline);
2996 fix_delete_line($fixlinenr, $rawline);
2997 my $fixedline = $prevrawline;
2998 $fixedline =~ s/\s*=\s*$/ = {/;
2999 fix_insert_line($fixlinenr, $fixedline);
3001 $fixedline =~ s/^(.\s*){\s*/$1/;
3002 fix_insert_line($fixlinenr, $fixedline);
3007 # Checks which are anchored on the added line.
3010 # check for malformed paths in #include statements (uses RAW line)
3011 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3013 if ($path =~ m{//}) {
3014 ERROR("MALFORMED_INCLUDE",
3015 "malformed #include filename\n" . $herecurr);
3017 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3018 ERROR("UAPI_INCLUDE",
3019 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3023 # no C99 // comments
3024 if ($line =~ m{//}) {
3025 if (ERROR("C99_COMMENTS",
3026 "do not use C99 // comments\n" . $herecurr) &&
3028 my $line = $fixed[$fixlinenr];
3029 if ($line =~ /\/\/(.*)$/) {
3030 my $comment = trim($1);
3031 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3035 # Remove C99 comments.
3037 $opline =~ s@//.*@@;
3039 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3040 # the whole statement.
3041 #print "APW <$lines[$realline_next - 1]>\n";
3042 if (defined $realline_next &&
3043 exists $lines[$realline_next - 1] &&
3044 !defined $suppress_export{$realline_next} &&
3045 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3046 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3047 # Handle definitions which produce identifiers with
3050 # EXPORT_SYMBOL(something_foo);
3052 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3053 $name =~ /^${Ident}_$2/) {
3054 #print "FOO C name<$name>\n";
3055 $suppress_export{$realline_next} = 1;
3057 } elsif ($stat !~ /(?:
3059 ^.DEFINE_$Ident\(\Q$name\E\)|
3060 ^.DECLARE_$Ident\(\Q$name\E\)|
3061 ^.LIST_HEAD\(\Q$name\E\)|
3062 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3063 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3065 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3066 $suppress_export{$realline_next} = 2;
3068 $suppress_export{$realline_next} = 1;
3071 if (!defined $suppress_export{$linenr} &&
3072 $prevline =~ /^.\s*$/ &&
3073 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3074 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3075 #print "FOO B <$lines[$linenr - 1]>\n";
3076 $suppress_export{$linenr} = 2;
3078 if (defined $suppress_export{$linenr} &&
3079 $suppress_export{$linenr} == 2) {
3080 WARN("EXPORT_SYMBOL",
3081 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3084 # check for global initialisers.
3085 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3086 if (ERROR("GLOBAL_INITIALISERS",
3087 "do not initialise globals to 0 or NULL\n" .
3090 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3093 # check for static initialisers.
3094 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3095 if (ERROR("INITIALISED_STATIC",
3096 "do not initialise statics to 0 or NULL\n" .
3099 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3103 # check for misordered declarations of char/short/int/long with signed/unsigned
3104 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3106 WARN("MISORDERED_TYPE",
3107 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3110 # check for static const char * arrays.
3111 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3112 WARN("STATIC_CONST_CHAR_ARRAY",
3113 "static const char * array should probably be static const char * const\n" .
3117 # check for static char foo[] = "bar" declarations.
3118 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3119 WARN("STATIC_CONST_CHAR_ARRAY",
3120 "static char array declaration should probably be static const char\n" .
3124 # check for non-global char *foo[] = {"bar", ...} declarations.
3125 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3126 WARN("STATIC_CONST_CHAR_ARRAY",
3127 "char * array declaration might be better as static const\n" .
3131 # check for function declarations without arguments like "int foo()"
3132 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3133 if (ERROR("FUNCTION_WITHOUT_ARGS",
3134 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3136 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3140 # check for uses of DEFINE_PCI_DEVICE_TABLE
3141 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3142 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3143 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3145 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3149 # check for new typedefs, only function parameters and sparse annotations
3151 if ($line =~ /\btypedef\s/ &&
3152 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3153 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3154 $line !~ /\b$typeTypedefs\b/ &&
3155 $line !~ /\b__bitwise(?:__|)\b/) {
3156 WARN("NEW_TYPEDEFS",
3157 "do not add new typedefs\n" . $herecurr);
3160 # * goes on variable not on type
3162 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3164 my ($ident, $from, $to) = ($1, $2, $2);
3166 # Should start with a space.
3167 $to =~ s/^(\S)/ $1/;
3168 # Should not end with a space.
3170 # '*'s should not have spaces between.
3171 while ($to =~ s/\*\s+\*/\*\*/) {
3174 ## print "1: from<$from> to<$to> ident<$ident>\n";
3176 if (ERROR("POINTER_LOCATION",
3177 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3179 my $sub_from = $ident;
3180 my $sub_to = $ident;
3181 $sub_to =~ s/\Q$from\E/$to/;
3182 $fixed[$fixlinenr] =~
3183 s@\Q$sub_from\E@$sub_to@;
3187 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3189 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3191 # Should start with a space.
3192 $to =~ s/^(\S)/ $1/;
3193 # Should not end with a space.
3195 # '*'s should not have spaces between.
3196 while ($to =~ s/\*\s+\*/\*\*/) {
3198 # Modifiers should have spaces.
3199 $to =~ s/(\b$Modifier$)/$1 /;
3201 ## print "2: from<$from> to<$to> ident<$ident>\n";
3202 if ($from ne $to && $ident !~ /^$Modifier$/) {
3203 if (ERROR("POINTER_LOCATION",
3204 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3207 my $sub_from = $match;
3208 my $sub_to = $match;
3209 $sub_to =~ s/\Q$from\E/$to/;
3210 $fixed[$fixlinenr] =~
3211 s@\Q$sub_from\E@$sub_to@;
3216 # # no BUG() or BUG_ON()
3217 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3218 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3219 # print "$herecurr";
3223 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3224 WARN("LINUX_VERSION_CODE",
3225 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3228 # check for uses of printk_ratelimit
3229 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3230 WARN("PRINTK_RATELIMITED",
3231 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3234 # printk should use KERN_* levels. Note that follow on printk's on the
3235 # same line do not need a level, so we use the current block context
3236 # to try and find and validate the current printk. In summary the current
3237 # printk includes all preceding printk's which have no newline on the end.
3238 # we assume the first bad printk is the one to report.
3239 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3241 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3242 #print "CHECK<$lines[$ln - 1]\n";
3243 # we have a preceding printk if it ends
3244 # with "\n" ignore it, else it is to blame
3245 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3246 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3253 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3254 "printk() should include KERN_ facility level\n" . $herecurr);
3258 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3260 my $level = lc($orig);
3261 $level = "warn" if ($level eq "warning");
3262 my $level2 = $level;
3263 $level2 = "dbg" if ($level eq "debug");
3264 WARN("PREFER_PR_LEVEL",
3265 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3268 if ($line =~ /\bpr_warning\s*\(/) {
3269 if (WARN("PREFER_PR_LEVEL",
3270 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3272 $fixed[$fixlinenr] =~
3273 s/\bpr_warning\b/pr_warn/;
3277 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3279 my $level = lc($orig);
3280 $level = "warn" if ($level eq "warning");
3281 $level = "dbg" if ($level eq "debug");
3282 WARN("PREFER_DEV_LEVEL",
3283 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3286 # function brace can't be on same line, except for #defines of do while,
3287 # or if closed on same line
3288 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3289 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3290 if (ERROR("OPEN_BRACE",
3291 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3293 fix_delete_line($fixlinenr, $rawline);
3294 my $fixed_line = $rawline;
3295 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3298 fix_insert_line($fixlinenr, ltrim($line1));
3299 fix_insert_line($fixlinenr, "\+{");
3300 if ($line2 !~ /^\s*$/) {
3301 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3306 # open braces for enum, union and struct go on the same line.
3307 if ($line =~ /^.\s*{/ &&
3308 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3309 if (ERROR("OPEN_BRACE",
3310 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3311 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3312 fix_delete_line($fixlinenr - 1, $prevrawline);
3313 fix_delete_line($fixlinenr, $rawline);
3314 my $fixedline = rtrim($prevrawline) . " {";
3315 fix_insert_line($fixlinenr, $fixedline);
3316 $fixedline = $rawline;
3317 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3318 if ($fixedline !~ /^\+\s*$/) {
3319 fix_insert_line($fixlinenr, $fixedline);
3324 # missing space after union, struct or enum definition
3325 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3327 "missing space after $1 definition\n" . $herecurr) &&
3329 $fixed[$fixlinenr] =~
3330 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3334 # Function pointer declarations
3335 # check spacing between type, funcptr, and args
3336 # canonical declaration is "type (*funcptr)(args...)"
3337 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3339 my $pre_pointer_space = $2;
3340 my $post_pointer_space = $3;
3342 my $post_funcname_space = $5;
3343 my $pre_args_space = $6;
3345 # the $Declare variable will capture all spaces after the type
3346 # so check it for a missing trailing missing space but pointer return types
3347 # don't need a space so don't warn for those.
3348 my $post_declare_space = "";
3349 if ($declare =~ /(\s+)$/) {
3350 $post_declare_space = $1;
3351 $declare = rtrim($declare);
3353 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3355 "missing space after return type\n" . $herecurr);
3356 $post_declare_space = " ";
3359 # unnecessary space "type (*funcptr)(args...)"
3360 # This test is not currently implemented because these declarations are
3362 # int foo(int bar, ...)
3363 # and this is form shouldn't/doesn't generate a checkpatch warning.
3365 # elsif ($declare =~ /\s{2,}$/) {
3367 # "Multiple spaces after return type\n" . $herecurr);
3370 # unnecessary space "type ( *funcptr)(args...)"
3371 if (defined $pre_pointer_space &&
3372 $pre_pointer_space =~ /^\s/) {
3374 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3377 # unnecessary space "type (* funcptr)(args...)"
3378 if (defined $post_pointer_space &&
3379 $post_pointer_space =~ /^\s/) {
3381 "Unnecessary space before function pointer name\n" . $herecurr);
3384 # unnecessary space "type (*funcptr )(args...)"
3385 if (defined $post_funcname_space &&
3386 $post_funcname_space =~ /^\s/) {
3388 "Unnecessary space after function pointer name\n" . $herecurr);
3391 # unnecessary space "type (*funcptr) (args...)"
3392 if (defined $pre_args_space &&
3393 $pre_args_space =~ /^\s/) {
3395 "Unnecessary space before function pointer arguments\n" . $herecurr);
3398 if (show_type("SPACING") && $fix) {
3399 $fixed[$fixlinenr] =~
3400 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3404 # check for spacing round square brackets; allowed:
3405 # 1. with a type on the left -- int [] a;
3406 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3407 # 3. inside a curly brace -- = { [0...10] = 5 }
3408 while ($line =~ /(.*?\s)\[/g) {
3409 my ($where, $prefix) = ($-[1], $1);
3410 if ($prefix !~ /$Type\s+$/ &&
3411 ($where != 0 || $prefix !~ /^.\s+$/) &&
3412 $prefix !~ /[{,]\s+$/) {
3413 if (ERROR("BRACKET_SPACE",
3414 "space prohibited before open square bracket '['\n" . $herecurr) &&
3416 $fixed[$fixlinenr] =~
3417 s/^(\+.*?)\s+\[/$1\[/;
3422 # check for spaces between functions and their parentheses.
3423 while ($line =~ /($Ident)\s+\(/g) {
3425 my $ctx_before = substr($line, 0, $-[1]);
3426 my $ctx = "$ctx_before$name";
3428 # Ignore those directives where spaces _are_ permitted.
3430 if|for|while|switch|return|case|
3431 volatile|__volatile__|
3432 __attribute__|format|__extension__|
3435 # cpp #define statements have non-optional spaces, ie
3436 # if there is a space between the name and the open
3437 # parenthesis it is simply not a parameter group.
3438 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3440 # cpp #elif statement condition may start with a (
3441 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3443 # If this whole things ends with a type its most
3444 # likely a typedef for a function.
3445 } elsif ($ctx =~ /$Type$/) {
3449 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3451 $fixed[$fixlinenr] =~
3452 s/\b$name\s+\(/$name\(/;
3457 # Check operator spacing.
3458 if (!($line=~/\#\s*include/)) {
3459 my $fixed_line = "";
3463 <<=|>>=|<=|>=|==|!=|
3464 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3465 =>|->|<<|>>|<|>|=|!|~|
3466 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3469 my @elements = split(/($ops|;)/, $opline);
3471 ## print("element count: <" . $#elements . ">\n");
3472 ## foreach my $el (@elements) {
3473 ## print("el: <$el>\n");
3476 my @fix_elements = ();
3479 foreach my $el (@elements) {
3480 push(@fix_elements, substr($rawline, $off, length($el)));
3481 $off += length($el);
3486 my $blank = copy_spacing($opline);
3487 my $last_after = -1;
3489 for (my $n = 0; $n < $#elements; $n += 2) {
3491 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3493 ## print("n: <$n> good: <$good>\n");
3495 $off += length($elements[$n]);
3497 # Pick up the preceding and succeeding characters.
3498 my $ca = substr($opline, 0, $off);
3500 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3501 $cc = substr($opline, $off + length($elements[$n + 1]));
3503 my $cb = "$ca$;$cc";
3506 $a = 'V' if ($elements[$n] ne '');
3507 $a = 'W' if ($elements[$n] =~ /\s$/);
3508 $a = 'C' if ($elements[$n] =~ /$;$/);
3509 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3510 $a = 'O' if ($elements[$n] eq '');
3511 $a = 'E' if ($ca =~ /^\s*$/);
3513 my $op = $elements[$n + 1];
3516 if (defined $elements[$n + 2]) {
3517 $c = 'V' if ($elements[$n + 2] ne '');
3518 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3519 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3520 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3521 $c = 'O' if ($elements[$n + 2] eq '');
3522 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3527 my $ctx = "${a}x${c}";
3529 my $at = "(ctx:$ctx)";
3531 my $ptr = substr($blank, 0, $off) . "^";
3532 my $hereptr = "$hereline$ptr\n";
3534 # Pull out the value of this operator.
3535 my $op_type = substr($curr_values, $off + 1, 1);
3537 # Get the full operator variant.
3538 my $opv = $op . substr($curr_vars, $off, 1);
3540 # Ignore operators passed as parameters.
3541 if ($op_type ne 'V' &&
3542 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3545 # } elsif ($op =~ /^$;+$/) {
3547 # ; should have either the end of line or a space or \ after it
3548 } elsif ($op eq ';') {
3549 if ($ctx !~ /.x[WEBC]/ &&
3550 $cc !~ /^\\/ && $cc !~ /^;/) {
3551 if (ERROR("SPACING",
3552 "space required after that '$op' $at\n" . $hereptr)) {
3553 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3559 } elsif ($op eq '//') {
3561 # : when part of a bitfield
3562 } elsif ($opv eq ':B') {
3563 # skip the bitfield test for now
3567 } elsif ($op eq '->') {
3568 if ($ctx =~ /Wx.|.xW/) {
3569 if (ERROR("SPACING",
3570 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3571 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3572 if (defined $fix_elements[$n + 2]) {
3573 $fix_elements[$n + 2] =~ s/^\s+//;
3579 # , must not have a space before and must have a space on the right.
3580 } elsif ($op eq ',') {
3581 my $rtrim_before = 0;
3582 my $space_after = 0;
3583 if ($ctx =~ /Wx./) {
3584 if (ERROR("SPACING",
3585 "space prohibited before that '$op' $at\n" . $hereptr)) {
3590 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3591 if (ERROR("SPACING",
3592 "space required after that '$op' $at\n" . $hereptr)) {
3598 if ($rtrim_before || $space_after) {
3599 if ($rtrim_before) {
3600 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3602 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3609 # '*' as part of a type definition -- reported already.
3610 } elsif ($opv eq '*_') {
3611 #warn "'*' is part of type\n";
3613 # unary operators should have a space before and
3614 # none after. May be left adjacent to another
3615 # unary operator, or a cast
3616 } elsif ($op eq '!' || $op eq '~' ||
3617 $opv eq '*U' || $opv eq '-U' ||
3618 $opv eq '&U' || $opv eq '&&U') {
3619 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3620 if (ERROR("SPACING",
3621 "space required before that '$op' $at\n" . $hereptr)) {
3622 if ($n != $last_after + 2) {
3623 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3628 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3629 # A unary '*' may be const
3631 } elsif ($ctx =~ /.xW/) {
3632 if (ERROR("SPACING",
3633 "space prohibited after that '$op' $at\n" . $hereptr)) {
3634 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3635 if (defined $fix_elements[$n + 2]) {
3636 $fix_elements[$n + 2] =~ s/^\s+//;
3642 # unary ++ and unary -- are allowed no space on one side.
3643 } elsif ($op eq '++' or $op eq '--') {
3644 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3645 if (ERROR("SPACING",
3646 "space required one side of that '$op' $at\n" . $hereptr)) {
3647 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3651 if ($ctx =~ /Wx[BE]/ ||
3652 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3653 if (ERROR("SPACING",
3654 "space prohibited before that '$op' $at\n" . $hereptr)) {
3655 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3659 if ($ctx =~ /ExW/) {
3660 if (ERROR("SPACING",
3661 "space prohibited after that '$op' $at\n" . $hereptr)) {
3662 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3663 if (defined $fix_elements[$n + 2]) {
3664 $fix_elements[$n + 2] =~ s/^\s+//;
3670 # << and >> may either have or not have spaces both sides
3671 } elsif ($op eq '<<' or $op eq '>>' or
3672 $op eq '&' or $op eq '^' or $op eq '|' or
3673 $op eq '+' or $op eq '-' or
3674 $op eq '*' or $op eq '/' or
3677 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3678 if (ERROR("SPACING",
3679 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3680 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3681 if (defined $fix_elements[$n + 2]) {
3682 $fix_elements[$n + 2] =~ s/^\s+//;
3688 # A colon needs no spaces before when it is
3689 # terminating a case value or a label.
3690 } elsif ($opv eq ':C' || $opv eq ':L') {
3691 if ($ctx =~ /Wx./) {
3692 if (ERROR("SPACING",
3693 "space prohibited before that '$op' $at\n" . $hereptr)) {
3694 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3699 # All the others need spaces both sides.
3700 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3703 # Ignore email addresses <foo@bar>
3705 $cc =~ /^\S+\@\S+>/) ||
3707 $ca =~ /<\S+\@\S+$/))
3712 # messages are ERROR, but ?: are CHK
3714 my $msg_type = \&ERROR;
3715 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3717 if (&{$msg_type}("SPACING",
3718 "spaces required around that '$op' $at\n" . $hereptr)) {
3719 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3720 if (defined $fix_elements[$n + 2]) {
3721 $fix_elements[$n + 2] =~ s/^\s+//;
3727 $off += length($elements[$n + 1]);
3729 ## print("n: <$n> GOOD: <$good>\n");
3731 $fixed_line = $fixed_line . $good;
3734 if (($#elements % 2) == 0) {
3735 $fixed_line = $fixed_line . $fix_elements[$#elements];
3738 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3739 $fixed[$fixlinenr] = $fixed_line;
3745 # check for whitespace before a non-naked semicolon
3746 if ($line =~ /^\+.*\S\s+;\s*$/) {
3748 "space prohibited before semicolon\n" . $herecurr) &&
3750 1 while $fixed[$fixlinenr] =~
3751 s/^(\+.*\S)\s+;/$1;/;
3755 # check for multiple assignments
3756 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3757 CHK("MULTIPLE_ASSIGNMENTS",
3758 "multiple assignments should be avoided\n" . $herecurr);
3761 ## # check for multiple declarations, allowing for a function declaration
3763 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3764 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3766 ## # Remove any bracketed sections to ensure we do not
3767 ## # falsly report the parameters of functions.
3769 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3771 ## if ($ln =~ /,/) {
3772 ## WARN("MULTIPLE_DECLARATION",
3773 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3777 #need space before brace following if, while, etc
3778 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3780 if (ERROR("SPACING",
3781 "space required before the open brace '{'\n" . $herecurr) &&
3783 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3787 ## # check for blank lines before declarations
3788 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3789 ## $prevrawline =~ /^.\s*$/) {
3791 ## "No blank lines before declarations\n" . $hereprev);
3795 # closing brace should have a space following it when it has anything
3797 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3798 if (ERROR("SPACING",
3799 "space required after that close brace '}'\n" . $herecurr) &&
3801 $fixed[$fixlinenr] =~
3802 s/}((?!(?:,|;|\)))\S)/} $1/;
3806 # check spacing on square brackets
3807 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3808 if (ERROR("SPACING",
3809 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3811 $fixed[$fixlinenr] =~
3815 if ($line =~ /\s\]/) {
3816 if (ERROR("SPACING",
3817 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3819 $fixed[$fixlinenr] =~
3824 # check spacing on parentheses
3825 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3826 $line !~ /for\s*\(\s+;/) {
3827 if (ERROR("SPACING",
3828 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3830 $fixed[$fixlinenr] =~
3834 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3835 $line !~ /for\s*\(.*;\s+\)/ &&
3836 $line !~ /:\s+\)/) {
3837 if (ERROR("SPACING",
3838 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3840 $fixed[$fixlinenr] =~
3845 # check unnecessary parentheses around addressof/dereference single $Lvals
3846 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3848 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3850 if (CHK("UNNECESSARY_PARENTHESES",
3851 "Unnecessary parentheses around $var\n" . $herecurr) &&
3853 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3857 # check for unnecessary parentheses around function pointer uses
3858 # ie: (foo->bar)(); should be foo->bar();
3859 # but not "if (foo->bar) (" to avoid some false positives
3860 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3862 if (CHK("UNNECESSARY_PARENTHESES",
3863 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3865 my $var2 = deparenthesize($var);
3867 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3871 #goto labels aren't indented, allow a single space however
3872 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3873 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3874 if (WARN("INDENTED_LABEL",
3875 "labels should not be indented\n" . $herecurr) &&
3877 $fixed[$fixlinenr] =~
3882 # return is not a function
3883 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3885 if ($^V && $^V ge 5.10.0 &&
3886 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3888 $value = deparenthesize($value);
3889 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3890 ERROR("RETURN_PARENTHESES",
3891 "return is not a function, parentheses are not required\n" . $herecurr);
3893 } elsif ($spacing !~ /\s+/) {
3895 "space required before the open parenthesis '('\n" . $herecurr);
3899 # unnecessary return in a void function
3900 # at end-of-function, with the previous line a single leading tab, then return;
3901 # and the line before that not a goto label target like "out:"
3902 if ($sline =~ /^[ \+]}\s*$/ &&
3903 $prevline =~ /^\+\treturn\s*;\s*$/ &&
3905 $lines[$linenr - 3] =~ /^[ +]/ &&
3906 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3908 "void function return statements are not generally useful\n" . $hereprev);
3911 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3912 if ($^V && $^V ge 5.10.0 &&
3913 $line =~ /\bif\s*((?:\(\s*){2,})/) {
3914 my $openparens = $1;
3915 my $count = $openparens =~ tr@\(@\(@;
3917 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3918 my $comp = $4; #Not $1 because of $LvalOrFunc
3919 $msg = " - maybe == should be = ?" if ($comp eq "==");
3920 WARN("UNNECESSARY_PARENTHESES",
3921 "Unnecessary parentheses$msg\n" . $herecurr);
3925 # Return of what appears to be an errno should normally be -'ve
3926 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3928 if ($name ne 'EOF' && $name ne 'ERROR') {
3929 WARN("USE_NEGATIVE_ERRNO",
3930 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3934 # Need a space before open parenthesis after if, while etc
3935 if ($line =~ /\b(if|while|for|switch)\(/) {
3936 if (ERROR("SPACING",
3937 "space required before the open parenthesis '('\n" . $herecurr) &&
3939 $fixed[$fixlinenr] =~
3940 s/\b(if|while|for|switch)\(/$1 \(/;
3944 # Check for illegal assignment in if conditional -- and check for trailing
3945 # statements after the conditional.
3946 if ($line =~ /do\s*(?!{)/) {
3947 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3948 ctx_statement_block($linenr, $realcnt, 0)
3949 if (!defined $stat);
3950 my ($stat_next) = ctx_statement_block($line_nr_next,
3951 $remain_next, $off_next);
3952 $stat_next =~ s/\n./\n /g;
3953 ##print "stat<$stat> stat_next<$stat_next>\n";
3955 if ($stat_next =~ /^\s*while\b/) {
3956 # If the statement carries leading newlines,
3957 # then count those as offsets.
3959 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3961 statement_rawlines($whitespace) - 1;
3963 $suppress_whiletrailers{$line_nr_next +
3967 if (!defined $suppress_whiletrailers{$linenr} &&
3968 defined($stat) && defined($cond) &&
3969 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3970 my ($s, $c) = ($stat, $cond);
3972 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3973 ERROR("ASSIGN_IN_IF",
3974 "do not use assignment in if condition\n" . $herecurr);
3977 # Find out what is on the end of the line after the
3979 substr($s, 0, length($c), '');
3981 $s =~ s/$;//g; # Remove any comments
3982 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3983 $c !~ /}\s*while\s*/)
3985 # Find out how long the conditional actually is.
3986 my @newlines = ($c =~ /\n/gs);
3987 my $cond_lines = 1 + $#newlines;
3990 $stat_real = raw_line($linenr, $cond_lines)
3991 . "\n" if ($cond_lines);
3992 if (defined($stat_real) && $cond_lines > 1) {
3993 $stat_real = "[...]\n$stat_real";
3996 ERROR("TRAILING_STATEMENTS",
3997 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4001 # Check for bitwise tests written as boolean
4013 WARN("HEXADECIMAL_BOOLEAN_TEST",
4014 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4017 # if and else should not have general statements after it
4018 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4020 $s =~ s/$;//g; # Remove any comments
4021 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4022 ERROR("TRAILING_STATEMENTS",
4023 "trailing statements should be on next line\n" . $herecurr);
4026 # if should not continue a brace
4027 if ($line =~ /}\s*if\b/) {
4028 ERROR("TRAILING_STATEMENTS",
4029 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4032 # case and default should not have general statements after them
4033 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4035 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4039 ERROR("TRAILING_STATEMENTS",
4040 "trailing statements should be on next line\n" . $herecurr);
4043 # Check for }<nl>else {, these must be at the same
4044 # indent level to be relevant to each other.
4045 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4046 $previndent == $indent) {
4047 if (ERROR("ELSE_AFTER_BRACE",
4048 "else should follow close brace '}'\n" . $hereprev) &&
4049 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4050 fix_delete_line($fixlinenr - 1, $prevrawline);
4051 fix_delete_line($fixlinenr, $rawline);
4052 my $fixedline = $prevrawline;
4053 $fixedline =~ s/}\s*$//;
4054 if ($fixedline !~ /^\+\s*$/) {
4055 fix_insert_line($fixlinenr, $fixedline);
4057 $fixedline = $rawline;
4058 $fixedline =~ s/^(.\s*)else/$1} else/;
4059 fix_insert_line($fixlinenr, $fixedline);
4063 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4064 $previndent == $indent) {
4065 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4067 # Find out what is on the end of the line after the
4069 substr($s, 0, length($c), '');
4072 if ($s =~ /^\s*;/) {
4073 if (ERROR("WHILE_AFTER_BRACE",
4074 "while should follow close brace '}'\n" . $hereprev) &&
4075 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4076 fix_delete_line($fixlinenr - 1, $prevrawline);
4077 fix_delete_line($fixlinenr, $rawline);
4078 my $fixedline = $prevrawline;
4079 my $trailing = $rawline;
4080 $trailing =~ s/^\+//;
4081 $trailing = trim($trailing);
4082 $fixedline =~ s/}\s*$/} $trailing/;
4083 fix_insert_line($fixlinenr, $fixedline);
4088 #Specific variable tests
4089 while ($line =~ m{($Constant|$Lval)}g) {
4092 #gcc binary extension
4093 if ($var =~ /^$Binary$/) {
4094 if (WARN("GCC_BINARY_CONSTANT",
4095 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4097 my $hexval = sprintf("0x%x", oct($var));
4098 $fixed[$fixlinenr] =~
4099 s/\b$var\b/$hexval/;
4104 if ($var !~ /^$Constant$/ &&
4105 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4106 #Ignore Page<foo> variants
4107 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4108 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4109 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4110 #Ignore some three character SI units explicitly, like MiB and KHz
4111 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4112 while ($var =~ m{($Ident)}g) {
4114 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4116 seed_camelcase_includes();
4117 if (!$file && !$camelcase_file_seeded) {
4118 seed_camelcase_file($realfile);
4119 $camelcase_file_seeded = 1;
4122 if (!defined $camelcase{$word}) {
4123 $camelcase{$word} = 1;
4125 "Avoid CamelCase: <$word>\n" . $herecurr);
4131 #no spaces allowed after \ in define
4132 if ($line =~ /\#\s*define.*\\\s+$/) {
4133 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4134 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4136 $fixed[$fixlinenr] =~ s/\s+$//;
4140 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4141 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4143 my $checkfile = "include/linux/$file";
4144 if (-f "$root/$checkfile" &&
4145 $realfile ne $checkfile &&
4146 $1 !~ /$allowed_asm_includes/)
4148 if ($realfile =~ m{^arch/}) {
4149 CHK("ARCH_INCLUDE_LINUX",
4150 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4152 WARN("INCLUDE_LINUX",
4153 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4158 # multi-statement macros should be enclosed in a do while loop, grab the
4159 # first statement and ensure its the whole macro if its not enclosed
4160 # in a known good container
4161 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4162 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4165 my ($off, $dstat, $dcond, $rest);
4167 my $has_flow_statement = 0;
4168 my $has_arg_concat = 0;
4169 ($dstat, $dcond, $ln, $cnt, $off) =
4170 ctx_statement_block($linenr, $realcnt, 0);
4172 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4173 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4175 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4176 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4178 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4180 $dstat =~ s/\\\n.//g;
4181 $dstat =~ s/^\s*//s;
4182 $dstat =~ s/\s*$//s;
4184 # Flatten any parentheses and braces
4185 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4186 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4187 $dstat =~ s/\[[^\[\]]*\]/1/)
4191 # Flatten any obvious string concatentation.
4192 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4193 $dstat =~ s/$Ident\s*("X*")/$1/)
4197 my $exceptions = qr{
4209 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4211 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4212 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4213 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4214 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4215 $dstat !~ /$exceptions/ &&
4216 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4217 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4218 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4219 $dstat !~ /^for\s*$Constant$/ && # for (...)
4220 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4221 $dstat !~ /^do\s*{/ && # do {...
4222 $dstat !~ /^\({/ && # ({...
4223 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4226 my $herectx = $here . "\n";
4227 my $cnt = statement_rawlines($ctx);
4229 for (my $n = 0; $n < $cnt; $n++) {
4230 $herectx .= raw_line($linenr, $n) . "\n";
4233 if ($dstat =~ /;/) {
4234 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4235 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4237 ERROR("COMPLEX_MACRO",
4238 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4242 # check for macros with flow control, but without ## concatenation
4243 # ## concatenation is commonly a macro that defines a function so ignore those
4244 if ($has_flow_statement && !$has_arg_concat) {
4245 my $herectx = $here . "\n";
4246 my $cnt = statement_rawlines($ctx);
4248 for (my $n = 0; $n < $cnt; $n++) {
4249 $herectx .= raw_line($linenr, $n) . "\n";
4251 WARN("MACRO_WITH_FLOW_CONTROL",
4252 "Macros with flow control statements should be avoided\n" . "$herectx");
4255 # check for line continuations outside of #defines, preprocessor #, and asm
4258 if ($prevline !~ /^..*\\$/ &&
4259 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4260 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4261 $line =~ /^\+.*\\$/) {
4262 WARN("LINE_CONTINUATIONS",
4263 "Avoid unnecessary line continuations\n" . $herecurr);
4267 # do {} while (0) macro tests:
4268 # single-statement macros do not need to be enclosed in do while (0) loop,
4269 # macro should not end with a semicolon
4270 if ($^V && $^V ge 5.10.0 &&
4271 $realfile !~ m@/vmlinux.lds.h$@ &&
4272 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4275 my ($off, $dstat, $dcond, $rest);
4277 ($dstat, $dcond, $ln, $cnt, $off) =
4278 ctx_statement_block($linenr, $realcnt, 0);
4281 $dstat =~ s/\\\n.//g;
4284 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4289 my $cnt = statement_rawlines($ctx);
4290 my $herectx = $here . "\n";
4292 for (my $n = 0; $n < $cnt; $n++) {
4293 $herectx .= raw_line($linenr, $n) . "\n";
4296 if (($stmts =~ tr/;/;/) == 1 &&
4297 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4298 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4299 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4301 if (defined $semis && $semis ne "") {
4302 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4303 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4305 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4307 my $cnt = statement_rawlines($ctx);
4308 my $herectx = $here . "\n";
4310 for (my $n = 0; $n < $cnt; $n++) {
4311 $herectx .= raw_line($linenr, $n) . "\n";
4314 WARN("TRAILING_SEMICOLON",
4315 "macros should not use a trailing semicolon\n" . "$herectx");
4319 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4320 # all assignments may have only one of the following with an assignment:
4323 # VMLINUX_SYMBOL(...)
4324 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4325 WARN("MISSING_VMLINUX_SYMBOL",
4326 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4329 # check for redundant bracing round if etc
4330 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4331 my ($level, $endln, @chunks) =
4332 ctx_statement_full($linenr, $realcnt, 1);
4333 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4334 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4335 if ($#chunks > 0 && $level == 0) {
4339 my $herectx = $here . "\n";
4340 my $ln = $linenr - 1;
4341 for my $chunk (@chunks) {
4342 my ($cond, $block) = @{$chunk};
4344 # If the condition carries leading newlines, then count those as offsets.
4345 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4346 my $offset = statement_rawlines($whitespace) - 1;
4348 $allowed[$allow] = 0;
4349 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4351 # We have looked at and allowed this specific line.
4352 $suppress_ifbraces{$ln + $offset} = 1;
4354 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4355 $ln += statement_rawlines($block) - 1;
4357 substr($block, 0, length($cond), '');
4359 $seen++ if ($block =~ /^\s*{/);
4361 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4362 if (statement_lines($cond) > 1) {
4363 #print "APW: ALLOWED: cond<$cond>\n";
4364 $allowed[$allow] = 1;
4366 if ($block =~/\b(?:if|for|while)\b/) {
4367 #print "APW: ALLOWED: block<$block>\n";
4368 $allowed[$allow] = 1;
4370 if (statement_block_size($block) > 1) {
4371 #print "APW: ALLOWED: lines block<$block>\n";
4372 $allowed[$allow] = 1;
4377 my $sum_allowed = 0;
4378 foreach (@allowed) {
4381 if ($sum_allowed == 0) {
4383 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4384 } elsif ($sum_allowed != $allow &&
4387 "braces {} should be used on all arms of this statement\n" . $herectx);
4392 if (!defined $suppress_ifbraces{$linenr - 1} &&
4393 $line =~ /\b(if|while|for|else)\b/) {
4396 # Check the pre-context.
4397 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4398 #print "APW: ALLOWED: pre<$1>\n";
4402 my ($level, $endln, @chunks) =
4403 ctx_statement_full($linenr, $realcnt, $-[0]);
4405 # Check the condition.
4406 my ($cond, $block) = @{$chunks[0]};
4407 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4408 if (defined $cond) {
4409 substr($block, 0, length($cond), '');
4411 if (statement_lines($cond) > 1) {
4412 #print "APW: ALLOWED: cond<$cond>\n";
4415 if ($block =~/\b(?:if|for|while)\b/) {
4416 #print "APW: ALLOWED: block<$block>\n";
4419 if (statement_block_size($block) > 1) {
4420 #print "APW: ALLOWED: lines block<$block>\n";
4423 # Check the post-context.
4424 if (defined $chunks[1]) {
4425 my ($cond, $block) = @{$chunks[1]};
4426 if (defined $cond) {
4427 substr($block, 0, length($cond), '');
4429 if ($block =~ /^\s*\{/) {
4430 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4434 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4435 my $herectx = $here . "\n";
4436 my $cnt = statement_rawlines($block);
4438 for (my $n = 0; $n < $cnt; $n++) {
4439 $herectx .= raw_line($linenr, $n) . "\n";
4443 "braces {} are not necessary for single statement blocks\n" . $herectx);
4447 # check for unnecessary blank lines around braces
4448 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4450 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
4452 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4454 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
4457 # no volatiles please
4458 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4459 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4461 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4464 # Check for user-visible strings broken across lines, which breaks the ability
4465 # to grep for the string. Make exceptions when the previous string ends in a
4466 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4467 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4468 if ($line =~ /^\+\s*"[X\t]*"/ &&
4469 $prevline =~ /"\s*$/ &&
4470 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4471 if (WARN("SPLIT_STRING",
4472 "quoted string split across lines\n" . $hereprev) &&
4474 $prevrawline =~ /^\+.*"\s*$/ &&
4475 $last_coalesced_string_linenr != $linenr - 1) {
4476 my $extracted_string = get_quoted_string($line, $rawline);
4477 my $comma_close = "";
4478 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4482 fix_delete_line($fixlinenr - 1, $prevrawline);
4483 fix_delete_line($fixlinenr, $rawline);
4484 my $fixedline = $prevrawline;
4485 $fixedline =~ s/"\s*$//;
4486 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4487 fix_insert_line($fixlinenr - 1, $fixedline);
4488 $fixedline = $rawline;
4489 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4490 if ($fixedline !~ /\+\s*$/) {
4491 fix_insert_line($fixlinenr, $fixedline);
4493 $last_coalesced_string_linenr = $linenr;
4497 # check for missing a space in a string concatenation
4498 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4499 WARN('MISSING_SPACE',
4500 "break quoted strings at a space character\n" . $hereprev);
4503 # check for spaces before a quoted newline
4504 if ($rawline =~ /^.*\".*\s\\n/) {
4505 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4506 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4508 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4513 # concatenated string without spaces between elements
4514 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4515 CHK("CONCATENATED_STRING",
4516 "Concatenated strings should use spaces between elements\n" . $herecurr);
4519 # uncoalesced string fragments
4520 if ($line =~ /"X*"\s*"/) {
4521 WARN("STRING_FRAGMENTS",
4522 "Consecutive strings are generally better as a single string\n" . $herecurr);
4525 # check for %L{u,d,i} in strings
4527 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4528 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4529 $string =~ s/%%/__/g;
4530 if ($string =~ /(?<!%)%L[udi]/) {
4532 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4537 # check for line continuations in quoted strings with odd counts of "
4538 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4539 WARN("LINE_CONTINUATIONS",
4540 "Avoid line continuations in quoted strings\n" . $herecurr);
4544 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4545 CHK("REDUNDANT_CODE",
4546 "if this code is redundant consider removing it\n" .
4550 # check for needless "if (<foo>) fn(<foo>)" uses
4551 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4552 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4553 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4555 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4559 # check for unnecessary "Out of Memory" messages
4560 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4561 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4562 (defined $1 || defined $3) &&
4565 my $testline = $lines[$linenr - 3];
4567 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4568 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4570 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4572 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4576 # check for logging functions with KERN_<LEVEL>
4577 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4578 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4580 if (WARN("UNNECESSARY_KERN_LEVEL",
4581 "Possible unnecessary $level\n" . $herecurr) &&
4583 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4587 # check for mask then right shift without a parentheses
4588 if ($^V && $^V ge 5.10.0 &&
4589 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4590 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4591 WARN("MASK_THEN_SHIFT",
4592 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4595 # check for pointer comparisons to NULL
4596 if ($^V && $^V ge 5.10.0) {
4597 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4600 $equal = "" if ($4 eq "!=");
4601 if (CHK("COMPARISON_TO_NULL",
4602 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4604 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4609 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4610 if ($line =~ /(\b$InitAttribute\b)/) {
4612 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4615 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4616 ERROR("MISPLACED_INIT",
4617 "$attr should be placed after $var\n" . $herecurr)) ||
4618 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4619 WARN("MISPLACED_INIT",
4620 "$attr should be placed after $var\n" . $herecurr))) &&
4622 $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;
4627 # check for $InitAttributeData (ie: __initdata) with const
4628 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4630 $attr =~ /($InitAttributePrefix)(.*)/;
4631 my $attr_prefix = $1;
4633 if (ERROR("INIT_ATTRIBUTE",
4634 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4636 $fixed[$fixlinenr] =~
4637 s/$InitAttributeData/${attr_prefix}initconst/;
4641 # check for $InitAttributeConst (ie: __initconst) without const
4642 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4644 if (ERROR("INIT_ATTRIBUTE",
4645 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4647 my $lead = $fixed[$fixlinenr] =~
4648 /(^\+\s*(?:static\s+))/;
4650 $lead = "$lead " if ($lead !~ /^\+$/);
4651 $lead = "${lead}const ";
4652 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4656 # don't use __constant_<foo> functions outside of include/uapi/
4657 if ($realfile !~ m@^include/uapi/@ &&
4658 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4659 my $constant_func = $1;
4660 my $func = $constant_func;
4661 $func =~ s/^__constant_//;
4662 if (WARN("CONSTANT_CONVERSION",
4663 "$constant_func should be $func\n" . $herecurr) &&
4665 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4669 # prefer usleep_range over udelay
4670 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4672 # ignore udelay's < 10, however
4673 if (! ($delay < 10) ) {
4675 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4677 if ($delay > 2000) {
4679 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4683 # warn about unexpectedly long msleep's
4684 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4687 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4691 # check for comparisons of jiffies
4692 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4693 WARN("JIFFIES_COMPARISON",
4694 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4697 # check for comparisons of get_jiffies_64()
4698 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4699 WARN("JIFFIES_COMPARISON",
4700 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4703 # warn about #ifdefs in C files
4704 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4705 # print "#ifdef in C files should be avoided\n";
4706 # print "$herecurr";
4710 # warn about spacing in #ifdefs
4711 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4712 if (ERROR("SPACING",
4713 "exactly one space required after that #$1\n" . $herecurr) &&
4715 $fixed[$fixlinenr] =~
4716 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4721 # check for spinlock_t definitions without a comment.
4722 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4723 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4725 if (!ctx_has_comment($first_line, $linenr)) {
4726 CHK("UNCOMMENTED_DEFINITION",
4727 "$1 definition without comment\n" . $herecurr);
4730 # check for memory barriers without a comment.
4731 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4732 if (!ctx_has_comment($first_line, $linenr)) {
4733 WARN("MEMORY_BARRIER",
4734 "memory barrier without comment\n" . $herecurr);
4737 # check of hardware specific defines
4738 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4740 "architecture specific defines should be avoided\n" . $herecurr);
4743 # Check that the storage class is at the beginning of a declaration
4744 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4745 WARN("STORAGE_CLASS",
4746 "storage class should be at the beginning of the declaration\n" . $herecurr)
4749 # check the location of the inline attribute, that it is between
4750 # storage class and type.
4751 if ($line =~ /\b$Type\s+$Inline\b/ ||
4752 $line =~ /\b$Inline\s+$Storage\b/) {
4753 ERROR("INLINE_LOCATION",
4754 "inline keyword should sit between storage class and type\n" . $herecurr);
4757 # Check for __inline__ and __inline, prefer inline
4758 if ($realfile !~ m@\binclude/uapi/@ &&
4759 $line =~ /\b(__inline__|__inline)\b/) {
4761 "plain inline is preferred over $1\n" . $herecurr) &&
4763 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4768 # Check for __attribute__ packed, prefer __packed
4769 if ($realfile !~ m@\binclude/uapi/@ &&
4770 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4771 WARN("PREFER_PACKED",
4772 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4775 # Check for __attribute__ aligned, prefer __aligned
4776 if ($realfile !~ m@\binclude/uapi/@ &&
4777 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4778 WARN("PREFER_ALIGNED",
4779 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4782 # Check for __attribute__ format(printf, prefer __printf
4783 if ($realfile !~ m@\binclude/uapi/@ &&
4784 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4785 if (WARN("PREFER_PRINTF",
4786 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4788 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4793 # Check for __attribute__ format(scanf, prefer __scanf
4794 if ($realfile !~ m@\binclude/uapi/@ &&
4795 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4796 if (WARN("PREFER_SCANF",
4797 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4799 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4803 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4804 if ($^V && $^V ge 5.10.0 &&
4805 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4806 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4807 $line =~ /\b__weak\b/)) {
4808 ERROR("WEAK_DECLARATION",
4809 "Using weak declarations can have unintended link defects\n" . $herecurr);
4812 # check for sizeof(&)
4813 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4814 WARN("SIZEOF_ADDRESS",
4815 "sizeof(& should be avoided\n" . $herecurr);
4818 # check for sizeof without parenthesis
4819 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4820 if (WARN("SIZEOF_PARENTHESIS",
4821 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4823 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4827 # check for struct spinlock declarations
4828 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4829 WARN("USE_SPINLOCK_T",
4830 "struct spinlock should be spinlock_t\n" . $herecurr);
4833 # check for seq_printf uses that could be seq_puts
4834 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4835 my $fmt = get_quoted_string($line, $rawline);
4836 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4837 if (WARN("PREFER_SEQ_PUTS",
4838 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4840 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4845 # Check for misused memsets
4846 if ($^V && $^V ge 5.10.0 &&
4848 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4854 if ($ms_size =~ /^(0x|)0$/i) {
4856 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4857 } elsif ($ms_size =~ /^(0x|)1$/i) {
4859 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4863 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4864 if ($^V && $^V ge 5.10.0 &&
4865 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4866 if (WARN("PREFER_ETHER_ADDR_COPY",
4867 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4869 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4873 # typecasts on min/max could be min_t/max_t
4874 if ($^V && $^V ge 5.10.0 &&
4876 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4877 if (defined $2 || defined $7) {
4879 my $cast1 = deparenthesize($2);
4881 my $cast2 = deparenthesize($7);
4885 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4886 $cast = "$cast1 or $cast2";
4887 } elsif ($cast1 ne "") {
4893 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4897 # check usleep_range arguments
4898 if ($^V && $^V ge 5.10.0 &&
4900 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4904 WARN("USLEEP_RANGE",
4905 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4906 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4908 WARN("USLEEP_RANGE",
4909 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4913 # check for naked sscanf
4914 if ($^V && $^V ge 5.10.0 &&
4916 $line =~ /\bsscanf\b/ &&
4917 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4918 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4919 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4920 my $lc = $stat =~ tr@\n@@;
4921 $lc = $lc + $linenr;
4922 my $stat_real = raw_line($linenr, 0);
4923 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4924 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4926 WARN("NAKED_SSCANF",
4927 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4930 # check for simple sscanf that should be kstrto<foo>
4931 if ($^V && $^V ge 5.10.0 &&
4933 $line =~ /\bsscanf\b/) {
4934 my $lc = $stat =~ tr@\n@@;
4935 $lc = $lc + $linenr;
4936 my $stat_real = raw_line($linenr, 0);
4937 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4938 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4940 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4942 my $count = $format =~ tr@%@%@;
4944 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4945 WARN("SSCANF_TO_KSTRTO",
4946 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4951 # check for new externs in .h files.
4952 if ($realfile =~ /\.h$/ &&
4953 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4954 if (CHK("AVOID_EXTERNS",
4955 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4957 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4961 # check for new externs in .c files.
4962 if ($realfile =~ /\.c$/ && defined $stat &&
4963 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4965 my $function_name = $1;
4966 my $paren_space = $2;
4969 if (defined $cond) {
4970 substr($s, 0, length($cond), '');
4972 if ($s =~ /^\s*;/ &&
4973 $function_name ne 'uninitialized_var')
4975 WARN("AVOID_EXTERNS",
4976 "externs should be avoided in .c files\n" . $herecurr);
4979 if ($paren_space =~ /\n/) {
4980 WARN("FUNCTION_ARGUMENTS",
4981 "arguments for function declarations should follow identifier\n" . $herecurr);
4984 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4985 $stat =~ /^.\s*extern\s+/)
4987 WARN("AVOID_EXTERNS",
4988 "externs should be avoided in .c files\n" . $herecurr);
4991 # checks for new __setup's
4992 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4995 if (!grep(/$name/, @setup_docs)) {
4996 CHK("UNDOCUMENTED_SETUP",
4997 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5001 # check for pointless casting of kmalloc return
5002 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5003 WARN("UNNECESSARY_CASTS",
5004 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5008 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5009 if ($^V && $^V ge 5.10.0 &&
5010 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5011 CHK("ALLOC_SIZEOF_STRUCT",
5012 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5015 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5016 if ($^V && $^V ge 5.10.0 &&
5017 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5021 my $newfunc = "kmalloc_array";
5022 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5025 if ($a1 =~ /^sizeof\s*\S/) {
5029 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5030 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5031 if (WARN("ALLOC_WITH_MULTIPLY",
5032 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5034 $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;
5040 # check for krealloc arg reuse
5041 if ($^V && $^V ge 5.10.0 &&
5042 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5043 WARN("KREALLOC_ARG_REUSE",
5044 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5047 # check for alloc argument mismatch
5048 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5049 WARN("ALLOC_ARRAY_ARGS",
5050 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5053 # check for multiple semicolons
5054 if ($line =~ /;\s*;\s*$/) {
5055 if (WARN("ONE_SEMICOLON",
5056 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5058 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5062 # check for #defines like: 1 << <digit> that could be BIT(digit)
5063 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5065 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5066 if (CHK("BIT_MACRO",
5067 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5069 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5073 # check for case / default statements not preceded by break/fallthrough/switch
5074 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5076 my $has_statement = 0;
5078 my $prevline = $linenr;
5079 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5081 my $rline = $rawlines[$prevline - 1];
5082 my $fline = $lines[$prevline - 1];
5083 last if ($fline =~ /^\@\@/);
5084 next if ($fline =~ /^\-/);
5085 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5086 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5087 next if ($fline =~ /^.[\s$;]*$/);
5090 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5092 if (!$has_break && $has_statement) {
5093 WARN("MISSING_BREAK",
5094 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5098 # check for switch/default statements without a break;
5099 if ($^V && $^V ge 5.10.0 &&
5101 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5103 my $herectx = $here . "\n";
5104 my $cnt = statement_rawlines($stat);
5105 for (my $n = 0; $n < $cnt; $n++) {
5106 $herectx .= raw_line($linenr, $n) . "\n";
5108 WARN("DEFAULT_NO_BREAK",
5109 "switch default: should use break\n" . $herectx);
5112 # check for gcc specific __FUNCTION__
5113 if ($line =~ /\b__FUNCTION__\b/) {
5114 if (WARN("USE_FUNC",
5115 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5117 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5121 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5122 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5124 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5127 # check for use of yield()
5128 if ($line =~ /\byield\s*\(\s*\)/) {
5130 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5133 # check for comparisons against true and false
5134 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5142 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5144 my $type = lc($otype);
5145 if ($type =~ /^(?:true|false)$/) {
5146 if (("$test" eq "==" && "$type" eq "true") ||
5147 ("$test" eq "!=" && "$type" eq "false")) {
5151 CHK("BOOL_COMPARISON",
5152 "Using comparison to $otype is error prone\n" . $herecurr);
5154 ## maybe suggesting a correct construct would better
5155 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5160 # check for semaphores initialized locked
5161 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5162 WARN("CONSIDER_COMPLETION",
5163 "consider using a completion\n" . $herecurr);
5166 # recommend kstrto* over simple_strto* and strict_strto*
5167 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5168 WARN("CONSIDER_KSTRTO",
5169 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5172 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5173 if ($line =~ /^.\s*__initcall\s*\(/) {
5174 WARN("USE_DEVICE_INITCALL",
5175 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5178 # check for various ops structs, ensure they are const.
5179 my $struct_ops = qr{acpi_dock_ops|
5180 address_space_operations|
5182 block_device_operations|
5187 file_lock_operations|
5197 lock_manager_operations|
5203 pipe_buf_operations|
5204 platform_hibernation_ops|
5205 platform_suspend_ops|
5210 soc_pcmcia_socket_ops|
5216 if ($line !~ /\bconst\b/ &&
5217 $line =~ /\bstruct\s+($struct_ops)\b/) {
5218 WARN("CONST_STRUCT",
5219 "struct $1 should normally be const\n" .
5223 # use of NR_CPUS is usually wrong
5224 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5225 if ($line =~ /\bNR_CPUS\b/ &&
5226 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5227 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5228 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5229 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5230 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5233 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5236 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5237 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5238 ERROR("DEFINE_ARCH_HAS",
5239 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5242 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5243 if ($^V && $^V ge 5.10.0 &&
5244 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5245 WARN("LIKELY_MISUSE",
5246 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5249 # whine mightly about in_atomic
5250 if ($line =~ /\bin_atomic\s*\(/) {
5251 if ($realfile =~ m@^drivers/@) {
5253 "do not use in_atomic in drivers\n" . $herecurr);
5254 } elsif ($realfile !~ m@^kernel/@) {
5256 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5260 # check for lockdep_set_novalidate_class
5261 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5262 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5263 if ($realfile !~ m@^kernel/lockdep@ &&
5264 $realfile !~ m@^include/linux/lockdep@ &&
5265 $realfile !~ m@^drivers/base/core@) {
5267 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5271 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5272 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5273 WARN("EXPORTED_WORLD_WRITABLE",
5274 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5277 # Mode permission misuses where it seems decimal should be octal
5278 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5279 if ($^V && $^V ge 5.10.0 &&
5280 $line =~ /$mode_perms_search/) {
5281 foreach my $entry (@mode_permission_funcs) {
5282 my $func = $entry->[0];
5283 my $arg_pos = $entry->[1];
5288 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5290 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5291 if ($line =~ /$test/) {
5293 $val = $6 if ($skip_args ne "");
5295 if ($val !~ /^0$/ &&
5296 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5297 length($val) ne 4)) {
5298 ERROR("NON_OCTAL_PERMISSIONS",
5299 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5300 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5301 ERROR("EXPORTED_WORLD_WRITABLE",
5302 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5309 # If we have no input at all, then there is nothing to report on
5310 # so just keep quiet.
5311 if ($#rawlines == -1) {
5315 # In mailback mode only produce a report in the negative, for
5316 # things that appear to be patches.
5317 if ($mailback && ($clean == 1 || !$is_patch)) {
5321 # This is not a patch, and we are are in 'no-patch' mode so
5323 if (!$chk_patch && !$is_patch) {
5328 ERROR("NOT_UNIFIED_DIFF",
5329 "Does not appear to be a unified-diff format patch\n");
5331 if ($is_patch && $chk_signoff && $signoff == 0) {
5332 ERROR("MISSING_SIGN_OFF",
5333 "Missing Signed-off-by: line(s)\n");
5336 print report_dump();
5337 if ($summary && !($clean == 1 && $quiet == 1)) {
5338 print "$filename " if ($summary_file);
5339 print "total: $cnt_error errors, $cnt_warn warnings, " .
5340 (($check)? "$cnt_chk checks, " : "") .
5341 "$cnt_lines lines checked\n";
5342 print "\n" if ($quiet == 0);
5347 if ($^V lt 5.10.0) {
5348 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5349 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5352 # If there were whitespace errors which cleanpatch can fix
5353 # then suggest that.
5354 if ($rpt_cleaners) {
5355 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5356 print " scripts/cleanfile\n\n";
5361 hash_show_words(\%use_type, "Used");
5362 hash_show_words(\%ignore_type, "Ignored");
5364 if ($clean == 0 && $fix &&
5365 ("@rawlines" ne "@fixed" ||
5366 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5367 my $newfile = $filename;
5368 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5372 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5374 open($f, '>', $newfile)
5375 or die "$P: Can't open $newfile for write\n";
5376 foreach my $fixed_line (@fixed) {
5379 if ($linecount > 3) {
5380 $fixed_line =~ s/^\+//;
5381 print $f $fixed_line . "\n";
5384 print $f $fixed_line . "\n";
5391 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5393 Do _NOT_ trust the results written to this file.
5394 Do _NOT_ submit these changes without inspecting them for correctness.
5396 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5397 No warranties, expressed or implied...
5403 if ($clean == 1 && $quiet == 0) {
5404 print "$vname has no obvious style problems and is ready for submission.\n"
5406 if ($clean == 0 && $quiet == 0) {
5408 $vname has style problems, please review.
5410 If any of these errors are false positives, please report
5411 them to the maintainer, see CHECKPATCH in MAINTAINERS.