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";
51 my $codespellfile = "/usr/local/share/codespell/dictionary.txt";
57 Usage: $P [OPTION]... [FILE]...
62 --no-tree run without a kernel tree
63 --no-signoff do not check for 'Signed-off-by' line
64 --patch treat FILE as patchfile (default)
65 --emacs emacs compile window format
66 --terse one line per report
67 -f, --file treat FILE as regular source file
68 --subjective, --strict enable more subjective tests
69 --types TYPE(,TYPE2...) show only these comma separated message types
70 --ignore TYPE(,TYPE2...) ignore various comma separated message types
71 --max-line-length=n set the maximum line length, if exceeded, warn
72 --min-conf-desc-length=n set the min description length, if shorter, warn
73 --show-types show the message "types" in the output
74 --root=PATH PATH to the kernel tree root
75 --no-summary suppress the per-file summary
76 --mailback only produce a report in case of warnings/errors
77 --summary-file include the filename in summary
78 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
79 'values', 'possible', 'type', and 'attr' (default
81 --test-only=WORD report only warnings/errors containing WORD
83 --fix EXPERIMENTAL - may create horrible results
84 If correctable single-line errors exist, create
85 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
86 with potential errors corrected to the preferred
88 --fix-inplace EXPERIMENTAL - may create horrible results
89 Is the same as --fix, but overwrites the input
90 file. It's your fault if there's no backup or git
91 --ignore-perl-version override checking of perl version. expect
93 --codespell Use the codespell dictionary for spelling/typos
94 (default:/usr/local/share/codespell/dictionary.txt)
95 --codespellfile Use this codespell dictionary
96 -h, --help, --version display this help and exit
98 When FILE is - read standard input.
104 my $conf = which_conf($configuration_file);
107 open(my $conffile, '<', "$conf")
108 or warn "$P: Can't find a readable $configuration_file file $!\n";
110 while (<$conffile>) {
113 $line =~ s/\s*\n?$//g;
117 next if ($line =~ m/^\s*#/);
118 next if ($line =~ m/^\s*$/);
120 my @words = split(" ", $line);
121 foreach my $word (@words) {
122 last if ($word =~ m/^#/);
123 push (@conf_args, $word);
127 unshift(@ARGV, @conf_args) if @conf_args;
131 'q|quiet+' => \$quiet,
133 'signoff!' => \$chk_signoff,
134 'patch!' => \$chk_patch,
138 'subjective!' => \$check,
139 'strict!' => \$check,
140 'ignore=s' => \@ignore,
142 'show-types!' => \$show_types,
143 'max-line-length=i' => \$max_line_length,
144 'min-conf-desc-length=i' => \$min_conf_desc_length,
146 'summary!' => \$summary,
147 'mailback!' => \$mailback,
148 'summary-file!' => \$summary_file,
150 'fix-inplace!' => \$fix_inplace,
151 'ignore-perl-version!' => \$ignore_perl_version,
152 'debug=s' => \%debug,
153 'test-only=s' => \$tst_only,
154 'codespell!' => \$codespell,
155 'codespellfile=s' => \$codespellfile,
162 $fix = 1 if ($fix_inplace);
163 $check_orig = $check;
167 if ($^V && $^V lt $minimum_perl_version) {
168 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
169 if (!$ignore_perl_version) {
175 print "$P: no input files\n";
179 sub hash_save_array_words {
180 my ($hashRef, $arrayRef) = @_;
182 my @array = split(/,/, join(',', @$arrayRef));
183 foreach my $word (@array) {
184 $word =~ s/\s*\n?$//g;
187 $word =~ tr/[a-z]/[A-Z]/;
189 next if ($word =~ m/^\s*#/);
190 next if ($word =~ m/^\s*$/);
196 sub hash_show_words {
197 my ($hashRef, $prefix) = @_;
199 if ($quiet == 0 && keys %$hashRef) {
200 print "NOTE: $prefix message types:";
201 foreach my $word (sort keys %$hashRef) {
208 hash_save_array_words(\%ignore_type, \@ignore);
209 hash_save_array_words(\%use_type, \@use);
212 my $dbg_possible = 0;
215 for my $key (keys %debug) {
217 eval "\${dbg_$key} = '$debug{$key}';";
221 my $rpt_cleaners = 0;
230 if (!top_of_kernel_tree($root)) {
231 die "$P: $root: --root does not point at a valid tree\n";
234 if (top_of_kernel_tree('.')) {
236 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
237 top_of_kernel_tree($1)) {
242 if (!defined $root) {
243 print "Must be run from the top-level dir. of a kernel tree\n";
248 my $emitted_corrupt = 0;
251 [A-Za-z_][A-Za-z\d_]*
252 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
254 our $Storage = qr{extern|static|asmlinkage};
266 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
267 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
268 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
269 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
270 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
272 # Notes to $Attribute:
273 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
294 ____cacheline_aligned|
295 ____cacheline_aligned_in_smp|
296 ____cacheline_internodealigned_in_smp|
300 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
301 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
302 our $Lval = qr{$Ident(?:$Member)*};
304 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
305 our $Binary = qr{(?i)0b[01]+$Int_type?};
306 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
307 our $Int = qr{[0-9]+$Int_type?};
308 our $Octal = qr{0[0-7]+$Int_type?};
309 our $String = qr{"[X\t]*"};
310 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
311 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
312 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
313 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
314 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
315 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
316 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
317 our $Arithmetic = qr{\+|-|\*|\/|%};
321 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
324 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
328 our $NonptrTypeMisordered;
329 our $NonptrTypeWithAttr;
333 our $DeclareMisordered;
335 our $NON_ASCII_UTF8 = qr{
336 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
337 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
338 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
339 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
340 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
341 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
342 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
346 [\x09\x0A\x0D\x20-\x7E] # ASCII
350 our $typeOtherOSTypedefs = qr{(?x:
351 u_(?:char|short|int|long) | # bsd
352 u(?:nchar|short|int|long) # sysv
355 our $typeTypedefs = qr{(?x:
356 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
360 our $logFunctions = qr{(?x:
361 printk(?:_ratelimited|_once|)|
362 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
363 WARN(?:_RATELIMIT|_ONCE|)|
366 seq_vprintf|seq_printf|seq_puts
369 our $signature_tags = qr{(?xi:
380 our @typeListMisordered = (
381 qr{char\s+(?:un)?signed},
382 qr{int\s+(?:(?:un)?signed\s+)?short\s},
383 qr{int\s+short(?:\s+(?:un)?signed)},
384 qr{short\s+int(?:\s+(?:un)?signed)},
385 qr{(?:un)?signed\s+int\s+short},
386 qr{short\s+(?:un)?signed},
387 qr{long\s+int\s+(?:un)?signed},
388 qr{int\s+long\s+(?:un)?signed},
389 qr{long\s+(?:un)?signed\s+int},
390 qr{int\s+(?:un)?signed\s+long},
391 qr{int\s+(?:un)?signed},
392 qr{int\s+long\s+long\s+(?:un)?signed},
393 qr{long\s+long\s+int\s+(?:un)?signed},
394 qr{long\s+long\s+(?:un)?signed\s+int},
395 qr{long\s+long\s+(?:un)?signed},
396 qr{long\s+(?:un)?signed},
401 qr{(?:(?:un)?signed\s+)?char},
402 qr{(?:(?:un)?signed\s+)?short\s+int},
403 qr{(?:(?:un)?signed\s+)?short},
404 qr{(?:(?:un)?signed\s+)?int},
405 qr{(?:(?:un)?signed\s+)?long\s+int},
406 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
407 qr{(?:(?:un)?signed\s+)?long\s+long},
408 qr{(?:(?:un)?signed\s+)?long},
417 qr{${Ident}_handler},
418 qr{${Ident}_handler_fn},
421 our @typeListWithAttr = (
423 qr{struct\s+$InitAttribute\s+$Ident},
424 qr{union\s+$InitAttribute\s+$Ident},
427 our @modifierList = (
431 our @mode_permission_funcs = (
433 ["module_param_(?:array|named|string)", 4],
434 ["module_param_array_named", 5],
435 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
436 ["proc_create(?:_data|)", 2],
437 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
440 #Create a search pattern for all these functions to speed up a loop below
441 our $mode_perms_search = "";
442 foreach my $entry (@mode_permission_funcs) {
443 $mode_perms_search .= '|' if ($mode_perms_search ne "");
444 $mode_perms_search .= $entry->[0];
447 our $mode_perms_world_writable = qr{
455 our $allowed_asm_includes = qr{(?x:
461 # memory.h: ARM has a custom one
463 # Load common spelling mistakes and build regular expression list.
467 if (open(my $spelling, '<', $spelling_file)) {
468 while (<$spelling>) {
471 $line =~ s/\s*\n?$//g;
474 next if ($line =~ m/^\s*#/);
475 next if ($line =~ m/^\s*$/);
477 my ($suspect, $fix) = split(/\|\|/, $line);
479 $spelling_fix{$suspect} = $fix;
483 warn "No typos will be found - file '$spelling_file': $!\n";
487 if (open(my $spelling, '<', $codespellfile)) {
488 while (<$spelling>) {
491 $line =~ s/\s*\n?$//g;
494 next if ($line =~ m/^\s*#/);
495 next if ($line =~ m/^\s*$/);
496 next if ($line =~ m/, disabled/i);
500 my ($suspect, $fix) = split(/->/, $line);
502 $spelling_fix{$suspect} = $fix;
506 warn "No codespell typos will be found - file '$codespellfile': $!\n";
510 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
513 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
514 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
515 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
516 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
517 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
519 (?:$typeOtherOSTypedefs\b)|
524 (?:$Modifier\s+|const\s+)*
526 (?:typeof|__typeof__)\s*\([^\)]*\)|
527 (?:$typeOtherOSTypedefs\b)|
531 (?:\s+$Modifier|\s+const)*
533 $NonptrTypeMisordered = qr{
534 (?:$Modifier\s+|const\s+)*
538 (?:\s+$Modifier|\s+const)*
540 $NonptrTypeWithAttr = qr{
541 (?:$Modifier\s+|const\s+)*
543 (?:typeof|__typeof__)\s*\([^\)]*\)|
545 (?:$typeOtherOSTypedefs\b)|
548 (?:\s+$Modifier|\s+const)*
552 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
553 (?:\s+$Inline|\s+$Modifier)*
555 $TypeMisordered = qr{
556 $NonptrTypeMisordered
557 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
558 (?:\s+$Inline|\s+$Modifier)*
560 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
561 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
565 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
567 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
568 # requires at least perl version v5.10.0
569 # Any use must be runtime checked with $^V
571 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
572 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
573 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
575 our $declaration_macros = qr{(?x:
576 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
577 (?:$Storage\s+)?LIST_HEAD\s*\(|
578 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
583 return "" if (!defined($string));
585 while ($string =~ /^\s*\(.*\)\s*$/) {
586 $string =~ s@^\s*\(\s*@@;
587 $string =~ s@\s*\)\s*$@@;
590 $string =~ s@\s+@ @g;
595 sub seed_camelcase_file {
598 return if (!(-f $file));
602 open(my $include_file, '<', "$file")
603 or warn "$P: Can't read '$file' $!\n";
604 my $text = <$include_file>;
605 close($include_file);
607 my @lines = split('\n', $text);
609 foreach my $line (@lines) {
610 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
611 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
613 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
615 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
621 my $camelcase_seeded = 0;
622 sub seed_camelcase_includes {
623 return if ($camelcase_seeded);
626 my $camelcase_cache = "";
627 my @include_files = ();
629 $camelcase_seeded = 1;
632 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
633 chomp $git_last_include_commit;
634 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
636 my $last_mod_date = 0;
637 $files = `find $root/include -name "*.h"`;
638 @include_files = split('\n', $files);
639 foreach my $file (@include_files) {
640 my $date = POSIX::strftime("%Y%m%d%H%M",
641 localtime((stat $file)[9]));
642 $last_mod_date = $date if ($last_mod_date < $date);
644 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
647 if ($camelcase_cache ne "" && -f $camelcase_cache) {
648 open(my $camelcase_file, '<', "$camelcase_cache")
649 or warn "$P: Can't read '$camelcase_cache' $!\n";
650 while (<$camelcase_file>) {
654 close($camelcase_file);
660 $files = `git ls-files "include/*.h"`;
661 @include_files = split('\n', $files);
664 foreach my $file (@include_files) {
665 seed_camelcase_file($file);
668 if ($camelcase_cache ne "") {
669 unlink glob ".checkpatch-camelcase.*";
670 open(my $camelcase_file, '>', "$camelcase_cache")
671 or warn "$P: Can't write '$camelcase_cache' $!\n";
672 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
673 print $camelcase_file ("$_\n");
675 close($camelcase_file);
679 sub git_commit_info {
680 my ($commit, $id, $desc) = @_;
682 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
684 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
685 $output =~ s/^\s*//gm;
686 my @lines = split("\n", $output);
688 return ($id, $desc) if ($#lines < 0);
690 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
691 # Maybe one day convert this block of bash into something that returns
692 # all matching commit ids, but it's very slow...
694 # echo "checking commits $1..."
695 # git rev-list --remotes | grep -i "^$1" |
696 # while read line ; do
697 # git log --format='%H %s' -1 $line |
698 # echo "commit $(cut -c 1-12,41-)"
700 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
702 $id = substr($lines[0], 0, 12);
703 $desc = substr($lines[0], 41);
709 $chk_signoff = 0 if ($file);
714 my @fixed_inserted = ();
715 my @fixed_deleted = ();
719 for my $filename (@ARGV) {
722 open($FILE, '-|', "diff -u /dev/null $filename") ||
723 die "$P: $filename: diff failed - $!\n";
724 } elsif ($filename eq '-') {
725 open($FILE, '<&STDIN');
727 open($FILE, '<', "$filename") ||
728 die "$P: $filename: open failed - $!\n";
730 if ($filename eq '-') {
731 $vname = 'Your patch';
740 if (!process($filename)) {
746 @fixed_inserted = ();
753 sub top_of_kernel_tree {
757 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
758 "README", "Documentation", "arch", "include", "drivers",
759 "fs", "init", "ipc", "kernel", "lib", "scripts",
762 foreach my $check (@tree_check) {
763 if (! -e $root . '/' . $check) {
771 my ($formatted_email) = @_;
777 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
780 $comment = $3 if defined $3;
781 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
783 $comment = $2 if defined $2;
784 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
786 $comment = $2 if defined $2;
787 $formatted_email =~ s/$address.*$//;
788 $name = $formatted_email;
790 $name =~ s/^\"|\"$//g;
791 # If there's a name left after stripping spaces and
792 # leading quotes, and the address doesn't have both
793 # leading and trailing angle brackets, the address
795 # "joe smith joe@smith.com" bad
796 # "joe smith <joe@smith.com" bad
797 if ($name ne "" && $address !~ /^<[^>]+>$/) {
805 $name =~ s/^\"|\"$//g;
806 $address = trim($address);
807 $address =~ s/^\<|\>$//g;
809 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
810 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
814 return ($name, $address, $comment);
818 my ($name, $address) = @_;
823 $name =~ s/^\"|\"$//g;
824 $address = trim($address);
826 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
827 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
832 $formatted_email = "$address";
834 $formatted_email = "$name <$address>";
837 return $formatted_email;
843 foreach my $path (split(/:/, $ENV{PATH})) {
844 if (-e "$path/$bin") {
855 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
856 if (-e "$path/$conf") {
857 return "$path/$conf";
869 for my $c (split(//, $str)) {
873 for (; ($n % 8) != 0; $n++) {
885 (my $res = shift) =~ tr/\t/ /c;
892 # Drop the diff line leader and expand tabs
894 $line = expand_tabs($line);
896 # Pick the indent from the front of the line.
897 my ($white) = ($line =~ /^(\s*)/);
899 return (length($line), length($white));
902 my $sanitise_quote = '';
904 sub sanitise_line_reset {
905 my ($in_comment) = @_;
908 $sanitise_quote = '*/';
910 $sanitise_quote = '';
923 # Always copy over the diff marker.
924 $res = substr($line, 0, 1);
926 for ($off = 1; $off < length($line); $off++) {
927 $c = substr($line, $off, 1);
929 # Comments we are wacking completly including the begin
930 # and end, all to $;.
931 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
932 $sanitise_quote = '*/';
934 substr($res, $off, 2, "$;$;");
938 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
939 $sanitise_quote = '';
940 substr($res, $off, 2, "$;$;");
944 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
945 $sanitise_quote = '//';
947 substr($res, $off, 2, $sanitise_quote);
952 # A \ in a string means ignore the next character.
953 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
955 substr($res, $off, 2, 'XX');
960 if ($c eq "'" || $c eq '"') {
961 if ($sanitise_quote eq '') {
962 $sanitise_quote = $c;
964 substr($res, $off, 1, $c);
966 } elsif ($sanitise_quote eq $c) {
967 $sanitise_quote = '';
971 #print "c<$c> SQ<$sanitise_quote>\n";
972 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
973 substr($res, $off, 1, $;);
974 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
975 substr($res, $off, 1, $;);
976 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
977 substr($res, $off, 1, 'X');
979 substr($res, $off, 1, $c);
983 if ($sanitise_quote eq '//') {
984 $sanitise_quote = '';
987 # The pathname on a #include may be surrounded by '<' and '>'.
988 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
989 my $clean = 'X' x length($1);
990 $res =~ s@\<.*\>@<$clean>@;
992 # The whole of a #error is a string.
993 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
994 my $clean = 'X' x length($1);
995 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1001 sub get_quoted_string {
1002 my ($line, $rawline) = @_;
1004 return "" if ($line !~ m/(\"[X\t]+\")/g);
1005 return substr($rawline, $-[0], $+[0] - $-[0]);
1008 sub ctx_statement_block {
1009 my ($linenr, $remain, $off) = @_;
1010 my $line = $linenr - 1;
1013 my $coff = $off - 1;
1027 @stack = (['', 0]) if ($#stack == -1);
1029 #warn "CSB: blk<$blk> remain<$remain>\n";
1030 # If we are about to drop off the end, pull in more
1033 for (; $remain > 0; $line++) {
1034 last if (!defined $lines[$line]);
1035 next if ($lines[$line] =~ /^-/);
1038 $blk .= $lines[$line] . "\n";
1039 $len = length($blk);
1043 # Bail if there is no further context.
1044 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1048 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1054 $c = substr($blk, $off, 1);
1055 $remainder = substr($blk, $off);
1057 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1059 # Handle nested #if/#else.
1060 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1061 push(@stack, [ $type, $level ]);
1062 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1063 ($type, $level) = @{$stack[$#stack - 1]};
1064 } elsif ($remainder =~ /^#\s*endif\b/) {
1065 ($type, $level) = @{pop(@stack)};
1068 # Statement ends at the ';' or a close '}' at the
1070 if ($level == 0 && $c eq ';') {
1074 # An else is really a conditional as long as its not else if
1075 if ($level == 0 && $coff_set == 0 &&
1076 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1077 $remainder =~ /^(else)(?:\s|{)/ &&
1078 $remainder !~ /^else\s+if\b/) {
1079 $coff = $off + length($1) - 1;
1081 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1082 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1085 if (($type eq '' || $type eq '(') && $c eq '(') {
1089 if ($type eq '(' && $c eq ')') {
1091 $type = ($level != 0)? '(' : '';
1093 if ($level == 0 && $coff < $soff) {
1096 #warn "CSB: mark coff<$coff>\n";
1099 if (($type eq '' || $type eq '{') && $c eq '{') {
1103 if ($type eq '{' && $c eq '}') {
1105 $type = ($level != 0)? '{' : '';
1108 if (substr($blk, $off + 1, 1) eq ';') {
1114 # Preprocessor commands end at the newline unless escaped.
1115 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1123 # We are truly at the end, so shuffle to the next line.
1130 my $statement = substr($blk, $soff, $off - $soff + 1);
1131 my $condition = substr($blk, $soff, $coff - $soff + 1);
1133 #warn "STATEMENT<$statement>\n";
1134 #warn "CONDITION<$condition>\n";
1136 #print "coff<$coff> soff<$off> loff<$loff>\n";
1138 return ($statement, $condition,
1139 $line, $remain + 1, $off - $loff + 1, $level);
1142 sub statement_lines {
1145 # Strip the diff line prefixes and rip blank lines at start and end.
1146 $stmt =~ s/(^|\n)./$1/g;
1150 my @stmt_lines = ($stmt =~ /\n/g);
1152 return $#stmt_lines + 2;
1155 sub statement_rawlines {
1158 my @stmt_lines = ($stmt =~ /\n/g);
1160 return $#stmt_lines + 2;
1163 sub statement_block_size {
1166 $stmt =~ s/(^|\n)./$1/g;
1172 my @stmt_lines = ($stmt =~ /\n/g);
1173 my @stmt_statements = ($stmt =~ /;/g);
1175 my $stmt_lines = $#stmt_lines + 2;
1176 my $stmt_statements = $#stmt_statements + 1;
1178 if ($stmt_lines > $stmt_statements) {
1181 return $stmt_statements;
1185 sub ctx_statement_full {
1186 my ($linenr, $remain, $off) = @_;
1187 my ($statement, $condition, $level);
1191 # Grab the first conditional/block pair.
1192 ($statement, $condition, $linenr, $remain, $off, $level) =
1193 ctx_statement_block($linenr, $remain, $off);
1194 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1195 push(@chunks, [ $condition, $statement ]);
1196 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1197 return ($level, $linenr, @chunks);
1200 # Pull in the following conditional/block pairs and see if they
1201 # could continue the statement.
1203 ($statement, $condition, $linenr, $remain, $off, $level) =
1204 ctx_statement_block($linenr, $remain, $off);
1205 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1206 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1208 push(@chunks, [ $condition, $statement ]);
1211 return ($level, $linenr, @chunks);
1215 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1217 my $start = $linenr - 1;
1224 my @stack = ($level);
1225 for ($line = $start; $remain > 0; $line++) {
1226 next if ($rawlines[$line] =~ /^-/);
1229 $blk .= $rawlines[$line];
1231 # Handle nested #if/#else.
1232 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1233 push(@stack, $level);
1234 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1235 $level = $stack[$#stack - 1];
1236 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1237 $level = pop(@stack);
1240 foreach my $c (split(//, $lines[$line])) {
1241 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1247 if ($c eq $close && $level > 0) {
1249 last if ($level == 0);
1250 } elsif ($c eq $open) {
1255 if (!$outer || $level <= 1) {
1256 push(@res, $rawlines[$line]);
1259 last if ($level == 0);
1262 return ($level, @res);
1264 sub ctx_block_outer {
1265 my ($linenr, $remain) = @_;
1267 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1271 my ($linenr, $remain) = @_;
1273 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1277 my ($linenr, $remain, $off) = @_;
1279 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1282 sub ctx_block_level {
1283 my ($linenr, $remain) = @_;
1285 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1287 sub ctx_statement_level {
1288 my ($linenr, $remain, $off) = @_;
1290 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1293 sub ctx_locate_comment {
1294 my ($first_line, $end_line) = @_;
1296 # Catch a comment on the end of the line itself.
1297 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1298 return $current_comment if (defined $current_comment);
1300 # Look through the context and try and figure out if there is a
1303 $current_comment = '';
1304 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1305 my $line = $rawlines[$linenr - 1];
1307 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1310 if ($line =~ m@/\*@) {
1313 if (!$in_comment && $current_comment ne '') {
1314 $current_comment = '';
1316 $current_comment .= $line . "\n" if ($in_comment);
1317 if ($line =~ m@\*/@) {
1322 chomp($current_comment);
1323 return($current_comment);
1325 sub ctx_has_comment {
1326 my ($first_line, $end_line) = @_;
1327 my $cmt = ctx_locate_comment($first_line, $end_line);
1329 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1330 ##print "CMMT: $cmt\n";
1332 return ($cmt ne '');
1336 my ($linenr, $cnt) = @_;
1338 my $offset = $linenr - 1;
1343 $line = $rawlines[$offset++];
1344 next if (defined($line) && $line =~ /^-/);
1356 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1359 $coded = sprintf("^%c", unpack('C', $2) + 64);
1368 my $av_preprocessor = 0;
1373 sub annotate_reset {
1374 $av_preprocessor = 0;
1376 @av_paren_type = ('E');
1377 $av_pend_colon = 'O';
1380 sub annotate_values {
1381 my ($stream, $type) = @_;
1384 my $var = '_' x length($stream);
1387 print "$stream\n" if ($dbg_values > 1);
1389 while (length($cur)) {
1390 @av_paren_type = ('E') if ($#av_paren_type < 0);
1391 print " <" . join('', @av_paren_type) .
1392 "> <$type> <$av_pending>" if ($dbg_values > 1);
1393 if ($cur =~ /^(\s+)/o) {
1394 print "WS($1)\n" if ($dbg_values > 1);
1395 if ($1 =~ /\n/ && $av_preprocessor) {
1396 $type = pop(@av_paren_type);
1397 $av_preprocessor = 0;
1400 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1401 print "CAST($1)\n" if ($dbg_values > 1);
1402 push(@av_paren_type, $type);
1405 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1406 print "DECLARE($1)\n" if ($dbg_values > 1);
1409 } elsif ($cur =~ /^($Modifier)\s*/) {
1410 print "MODIFIER($1)\n" if ($dbg_values > 1);
1413 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1414 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1415 $av_preprocessor = 1;
1416 push(@av_paren_type, $type);
1422 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1423 print "UNDEF($1)\n" if ($dbg_values > 1);
1424 $av_preprocessor = 1;
1425 push(@av_paren_type, $type);
1427 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1428 print "PRE_START($1)\n" if ($dbg_values > 1);
1429 $av_preprocessor = 1;
1431 push(@av_paren_type, $type);
1432 push(@av_paren_type, $type);
1435 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1436 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1437 $av_preprocessor = 1;
1439 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1443 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1444 print "PRE_END($1)\n" if ($dbg_values > 1);
1446 $av_preprocessor = 1;
1448 # Assume all arms of the conditional end as this
1449 # one does, and continue as if the #endif was not here.
1450 pop(@av_paren_type);
1451 push(@av_paren_type, $type);
1454 } elsif ($cur =~ /^(\\\n)/o) {
1455 print "PRECONT($1)\n" if ($dbg_values > 1);
1457 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1458 print "ATTR($1)\n" if ($dbg_values > 1);
1459 $av_pending = $type;
1462 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1463 print "SIZEOF($1)\n" if ($dbg_values > 1);
1469 } elsif ($cur =~ /^(if|while|for)\b/o) {
1470 print "COND($1)\n" if ($dbg_values > 1);
1474 } elsif ($cur =~/^(case)/o) {
1475 print "CASE($1)\n" if ($dbg_values > 1);
1476 $av_pend_colon = 'C';
1479 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1480 print "KEYWORD($1)\n" if ($dbg_values > 1);
1483 } elsif ($cur =~ /^(\()/o) {
1484 print "PAREN('$1')\n" if ($dbg_values > 1);
1485 push(@av_paren_type, $av_pending);
1489 } elsif ($cur =~ /^(\))/o) {
1490 my $new_type = pop(@av_paren_type);
1491 if ($new_type ne '_') {
1493 print "PAREN('$1') -> $type\n"
1494 if ($dbg_values > 1);
1496 print "PAREN('$1')\n" if ($dbg_values > 1);
1499 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1500 print "FUNC($1)\n" if ($dbg_values > 1);
1504 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1505 if (defined $2 && $type eq 'C' || $type eq 'T') {
1506 $av_pend_colon = 'B';
1507 } elsif ($type eq 'E') {
1508 $av_pend_colon = 'L';
1510 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1513 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1514 print "IDENT($1)\n" if ($dbg_values > 1);
1517 } elsif ($cur =~ /^($Assignment)/o) {
1518 print "ASSIGN($1)\n" if ($dbg_values > 1);
1521 } elsif ($cur =~/^(;|{|})/) {
1522 print "END($1)\n" if ($dbg_values > 1);
1524 $av_pend_colon = 'O';
1526 } elsif ($cur =~/^(,)/) {
1527 print "COMMA($1)\n" if ($dbg_values > 1);
1530 } elsif ($cur =~ /^(\?)/o) {
1531 print "QUESTION($1)\n" if ($dbg_values > 1);
1534 } elsif ($cur =~ /^(:)/o) {
1535 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1537 substr($var, length($res), 1, $av_pend_colon);
1538 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1543 $av_pend_colon = 'O';
1545 } elsif ($cur =~ /^(\[)/o) {
1546 print "CLOSE($1)\n" if ($dbg_values > 1);
1549 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1552 print "OPV($1)\n" if ($dbg_values > 1);
1559 substr($var, length($res), 1, $variant);
1562 } elsif ($cur =~ /^($Operators)/o) {
1563 print "OP($1)\n" if ($dbg_values > 1);
1564 if ($1 ne '++' && $1 ne '--') {
1568 } elsif ($cur =~ /(^.)/o) {
1569 print "C($1)\n" if ($dbg_values > 1);
1572 $cur = substr($cur, length($1));
1573 $res .= $type x length($1);
1577 return ($res, $var);
1581 my ($possible, $line) = @_;
1582 my $notPermitted = qr{(?:
1599 ^(?:typedef|struct|enum)\b
1601 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1602 if ($possible !~ $notPermitted) {
1603 # Check for modifiers.
1604 $possible =~ s/\s*$Storage\s*//g;
1605 $possible =~ s/\s*$Sparse\s*//g;
1606 if ($possible =~ /^\s*$/) {
1608 } elsif ($possible =~ /\s/) {
1609 $possible =~ s/\s*$Type\s*//g;
1610 for my $modifier (split(' ', $possible)) {
1611 if ($modifier !~ $notPermitted) {
1612 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1613 push(@modifierList, $modifier);
1618 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1619 push(@typeList, $possible);
1623 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1632 return defined $use_type{$type} if (scalar keys %use_type > 0);
1634 return !defined $ignore_type{$type};
1638 my ($level, $type, $msg) = @_;
1640 if (!show_type($type) ||
1641 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1646 $line = "$prefix$level:$type: $msg\n";
1648 $line = "$prefix$level: $msg\n";
1650 $line = (split('\n', $line))[0] . "\n" if ($terse);
1652 push(our @report, $line);
1661 sub fixup_current_range {
1662 my ($lineRef, $offset, $length) = @_;
1664 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1667 my $no = $o + $offset;
1668 my $nl = $l + $length;
1669 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1673 sub fix_inserted_deleted_lines {
1674 my ($linesRef, $insertedRef, $deletedRef) = @_;
1676 my $range_last_linenr = 0;
1677 my $delta_offset = 0;
1682 my $next_insert = 0;
1683 my $next_delete = 0;
1687 my $inserted = @{$insertedRef}[$next_insert++];
1688 my $deleted = @{$deletedRef}[$next_delete++];
1690 foreach my $old_line (@{$linesRef}) {
1692 my $line = $old_line; #don't modify the array
1693 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1695 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1696 $range_last_linenr = $new_linenr;
1697 fixup_current_range(\$line, $delta_offset, 0);
1700 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1701 $deleted = @{$deletedRef}[$next_delete++];
1703 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1706 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1707 push(@lines, ${$inserted}{'LINE'});
1708 $inserted = @{$insertedRef}[$next_insert++];
1710 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1714 push(@lines, $line);
1724 sub fix_insert_line {
1725 my ($linenr, $line) = @_;
1731 push(@fixed_inserted, $inserted);
1734 sub fix_delete_line {
1735 my ($linenr, $line) = @_;
1742 push(@fixed_deleted, $deleted);
1746 my ($type, $msg) = @_;
1748 if (report("ERROR", $type, $msg)) {
1756 my ($type, $msg) = @_;
1758 if (report("WARNING", $type, $msg)) {
1766 my ($type, $msg) = @_;
1768 if ($check && report("CHECK", $type, $msg)) {
1776 sub check_absolute_file {
1777 my ($absolute, $herecurr) = @_;
1778 my $file = $absolute;
1780 ##print "absolute<$absolute>\n";
1782 # See if any suffix of this path is a path within the tree.
1783 while ($file =~ s@^[^/]*/@@) {
1784 if (-f "$root/$file") {
1785 ##print "file<$file>\n";
1793 # It is, so see if the prefix is acceptable.
1794 my $prefix = $absolute;
1795 substr($prefix, -length($file)) = '';
1797 ##print "prefix<$prefix>\n";
1798 if ($prefix ne ".../") {
1799 WARN("USE_RELATIVE_PATH",
1800 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1807 $string =~ s/^\s+|\s+$//g;
1815 $string =~ s/^\s+//;
1823 $string =~ s/\s+$//;
1828 sub string_find_replace {
1829 my ($string, $find, $replace) = @_;
1831 $string =~ s/$find/$replace/g;
1839 my $source_indent = 8;
1840 my $max_spaces_before_tab = $source_indent - 1;
1841 my $spaces_to_tab = " " x $source_indent;
1843 #convert leading spaces to tabs
1844 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1845 #Remove spaces before a tab
1846 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1851 sub pos_last_openparen {
1856 my $opens = $line =~ tr/\(/\(/;
1857 my $closes = $line =~ tr/\)/\)/;
1859 my $last_openparen = 0;
1861 if (($opens == 0) || ($closes >= $opens)) {
1865 my $len = length($line);
1867 for ($pos = 0; $pos < $len; $pos++) {
1868 my $string = substr($line, $pos);
1869 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1870 $pos += length($1) - 1;
1871 } elsif (substr($line, $pos, 1) eq '(') {
1872 $last_openparen = $pos;
1873 } elsif (index($string, '(') == -1) {
1878 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1882 my $filename = shift;
1888 my $stashrawline="";
1899 my $in_header_lines = $file ? 0 : 1;
1900 my $in_commit_log = 0; #Scanning lines before patch
1901 my $reported_maintainer_file = 0;
1902 my $non_utf8_charset = 0;
1904 my $last_blank_line = 0;
1905 my $last_coalesced_string_linenr = -1;
1913 # Trace the real file/line as we go.
1919 my $comment_edge = 0;
1923 my $prev_values = 'E';
1926 my %suppress_ifbraces;
1927 my %suppress_whiletrailers;
1928 my %suppress_export;
1929 my $suppress_statement = 0;
1931 my %signatures = ();
1933 # Pre-scan the patch sanitizing the lines.
1934 # Pre-scan the patch looking for any __setup documentation.
1936 my @setup_docs = ();
1939 my $camelcase_file_seeded = 0;
1941 sanitise_line_reset();
1943 foreach my $rawline (@rawlines) {
1947 push(@fixed, $rawline) if ($fix);
1949 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1951 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1956 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1965 # Guestimate if this is a continuing comment. Run
1966 # the context looking for a comment "edge". If this
1967 # edge is a close comment then we must be in a comment
1971 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1972 next if (defined $rawlines[$ln - 1] &&
1973 $rawlines[$ln - 1] =~ /^-/);
1975 #print "RAW<$rawlines[$ln - 1]>\n";
1976 last if (!defined $rawlines[$ln - 1]);
1977 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1978 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1983 if (defined $edge && $edge eq '*/') {
1987 # Guestimate if this is a continuing comment. If this
1988 # is the start of a diff block and this line starts
1989 # ' *' then it is very likely a comment.
1990 if (!defined $edge &&
1991 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1996 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1997 sanitise_line_reset($in_comment);
1999 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2000 # Standardise the strings and chars within the input to
2001 # simplify matching -- only bother with positive lines.
2002 $line = sanitise_line($rawline);
2004 push(@lines, $line);
2007 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2012 #print "==>$rawline\n";
2013 #print "-->$line\n";
2015 if ($setup_docs && $line =~ /^\+/) {
2016 push(@setup_docs, $line);
2025 foreach my $line (@lines) {
2028 my $sline = $line; #copy of $line
2029 $sline =~ s/$;/ /g; #with comments as spaces
2031 my $rawline = $rawlines[$linenr - 1];
2033 #extract the line range in the file after the patch is applied
2034 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2036 $first_line = $linenr + 1;
2046 %suppress_ifbraces = ();
2047 %suppress_whiletrailers = ();
2048 %suppress_export = ();
2049 $suppress_statement = 0;
2052 # track the line number as we move through the hunk, note that
2053 # new versions of GNU diff omit the leading space on completely
2054 # blank context lines so we need to count that too.
2055 } elsif ($line =~ /^( |\+|$)/) {
2057 $realcnt-- if ($realcnt != 0);
2059 # Measure the line length and indent.
2060 ($length, $indent) = line_stats($rawline);
2062 # Track the previous line.
2063 ($prevline, $stashline) = ($stashline, $line);
2064 ($previndent, $stashindent) = ($stashindent, $indent);
2065 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2067 #warn "line<$line>\n";
2069 } elsif ($realcnt == 1) {
2073 my $hunk_line = ($realcnt != 0);
2075 #make up the handle for any error we report on this line
2076 $prefix = "$filename:$realline: " if ($emacs && $file);
2077 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2079 $here = "#$linenr: " if (!$file);
2080 $here = "#$realline: " if ($file);
2083 # extract the filename as it passes
2084 if ($line =~ /^diff --git.*?(\S+)$/) {
2086 $realfile =~ s@^([^/]*)/@@ if (!$file);
2089 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2091 $realfile =~ s@^([^/]*)/@@ if (!$file);
2095 if (!$file && $tree && $p1_prefix ne '' &&
2096 -e "$root/$p1_prefix") {
2097 WARN("PATCH_PREFIX",
2098 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2101 if ($realfile =~ m@^include/asm/@) {
2102 ERROR("MODIFIED_INCLUDE_ASM",
2103 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2109 if ($realfile =~ m@^(drivers/net/|net/)@) {
2112 $check = $check_orig;
2117 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2119 my $hereline = "$here\n$rawline\n";
2120 my $herecurr = "$here\n$rawline\n";
2121 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2123 $cnt_lines++ if ($realcnt != 0);
2125 # Check for incorrect file permissions
2126 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2127 my $permhere = $here . "FILE: $realfile\n";
2128 if ($realfile !~ m@scripts/@ &&
2129 $realfile !~ /\.(py|pl|awk|sh)$/) {
2130 ERROR("EXECUTE_PERMISSIONS",
2131 "do not set execute permissions for source files\n" . $permhere);
2135 # Check the patch for a signoff:
2136 if ($line =~ /^\s*signed-off-by:/i) {
2141 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2142 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2143 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2144 $reported_maintainer_file = 1;
2147 # Check signature styles
2148 if (!$in_header_lines &&
2149 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2150 my $space_before = $1;
2152 my $space_after = $3;
2154 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2156 if ($sign_off !~ /$signature_tags/) {
2157 WARN("BAD_SIGN_OFF",
2158 "Non-standard signature: $sign_off\n" . $herecurr);
2160 if (defined $space_before && $space_before ne "") {
2161 if (WARN("BAD_SIGN_OFF",
2162 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2164 $fixed[$fixlinenr] =
2165 "$ucfirst_sign_off $email";
2168 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2169 if (WARN("BAD_SIGN_OFF",
2170 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2172 $fixed[$fixlinenr] =
2173 "$ucfirst_sign_off $email";
2177 if (!defined $space_after || $space_after ne " ") {
2178 if (WARN("BAD_SIGN_OFF",
2179 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2181 $fixed[$fixlinenr] =
2182 "$ucfirst_sign_off $email";
2186 my ($email_name, $email_address, $comment) = parse_email($email);
2187 my $suggested_email = format_email(($email_name, $email_address));
2188 if ($suggested_email eq "") {
2189 ERROR("BAD_SIGN_OFF",
2190 "Unrecognized email address: '$email'\n" . $herecurr);
2192 my $dequoted = $suggested_email;
2193 $dequoted =~ s/^"//;
2194 $dequoted =~ s/" </ </;
2195 # Don't force email to have quotes
2196 # Allow just an angle bracketed address
2197 if ("$dequoted$comment" ne $email &&
2198 "<$email_address>$comment" ne $email &&
2199 "$suggested_email$comment" ne $email) {
2200 WARN("BAD_SIGN_OFF",
2201 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2205 # Check for duplicate signatures
2206 my $sig_nospace = $line;
2207 $sig_nospace =~ s/\s//g;
2208 $sig_nospace = lc($sig_nospace);
2209 if (defined $signatures{$sig_nospace}) {
2210 WARN("BAD_SIGN_OFF",
2211 "Duplicate signature\n" . $herecurr);
2213 $signatures{$sig_nospace} = 1;
2217 # Check email subject for common tools that don't need to be mentioned
2218 if ($in_header_lines &&
2219 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2220 WARN("EMAIL_SUBJECT",
2221 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2224 # Check for old stable address
2225 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2226 ERROR("STABLE_ADDRESS",
2227 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2230 # Check for unwanted Gerrit info
2231 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2232 ERROR("GERRIT_CHANGE_ID",
2233 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2236 # Check for git id commit length and improperly formed commit descriptions
2237 if ($in_commit_log && $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i) {
2239 my $orig_commit = lc($2);
2246 my $id = '0123456789ab';
2247 my $orig_desc = "commit description";
2248 my $description = "";
2250 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2251 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2252 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2253 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2254 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2257 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2258 defined $rawlines[$linenr] &&
2259 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2262 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2263 defined $rawlines[$linenr] &&
2264 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2265 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2267 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2268 $orig_desc .= " " . $1;
2272 ($id, $description) = git_commit_info($orig_commit,
2275 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2276 ERROR("GIT_COMMIT_ID",
2277 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2281 # Check for added, moved or deleted files
2282 if (!$reported_maintainer_file && !$in_commit_log &&
2283 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2284 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2285 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2286 (defined($1) || defined($2))))) {
2287 $reported_maintainer_file = 1;
2288 WARN("FILE_PATH_CHANGES",
2289 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2292 # Check for wrappage within a valid hunk of the file
2293 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2294 ERROR("CORRUPTED_PATCH",
2295 "patch seems to be corrupt (line wrapped?)\n" .
2296 $herecurr) if (!$emitted_corrupt++);
2299 # Check for absolute kernel paths.
2301 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2304 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2305 check_absolute_file($1, $herecurr)) {
2308 check_absolute_file($file, $herecurr);
2313 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2314 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2315 $rawline !~ m/^$UTF8*$/) {
2316 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2318 my $blank = copy_spacing($rawline);
2319 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2320 my $hereptr = "$hereline$ptr\n";
2323 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2326 # Check if it's the start of a commit log
2327 # (not a header line and we haven't seen the patch filename)
2328 if ($in_header_lines && $realfile =~ /^$/ &&
2329 !($rawline =~ /^\s+\S/ ||
2330 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2331 $in_header_lines = 0;
2335 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2336 # declined it, i.e defined some charset where it is missing.
2337 if ($in_header_lines &&
2338 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2340 $non_utf8_charset = 1;
2343 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2344 $rawline =~ /$NON_ASCII_UTF8/) {
2345 WARN("UTF8_BEFORE_PATCH",
2346 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2349 # Check for various typo / spelling mistakes
2350 if (defined($misspellings) &&
2351 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2352 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2354 my $typo_fix = $spelling_fix{lc($typo)};
2355 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2356 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2357 my $msg_type = \&WARN;
2358 $msg_type = \&CHK if ($file);
2359 if (&{$msg_type}("TYPO_SPELLING",
2360 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2362 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2367 # ignore non-hunk lines and lines being removed
2368 next if (!$hunk_line || $line =~ /^-/);
2370 #trailing whitespace
2371 if ($line =~ /^\+.*\015/) {
2372 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2373 if (ERROR("DOS_LINE_ENDINGS",
2374 "DOS line endings\n" . $herevet) &&
2376 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2378 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2379 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2380 if (ERROR("TRAILING_WHITESPACE",
2381 "trailing whitespace\n" . $herevet) &&
2383 $fixed[$fixlinenr] =~ s/\s+$//;
2389 # Check for FSF mailing addresses.
2390 if ($rawline =~ /\bwrite to the Free/i ||
2391 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2392 $rawline =~ /\b51\s+Franklin\s+St/i) {
2393 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2394 my $msg_type = \&ERROR;
2395 $msg_type = \&CHK if ($file);
2396 &{$msg_type}("FSF_MAILING_ADDRESS",
2397 "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)
2400 # check for Kconfig help text having a real description
2401 # Only applies when adding the entry originally, after that we do not have
2402 # sufficient context to determine whether it is indeed long enough.
2403 if ($realfile =~ /Kconfig/ &&
2404 $line =~ /^\+\s*config\s+/) {
2407 my $ln = $linenr + 1;
2411 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2412 $f = $lines[$ln - 1];
2413 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2414 $is_end = $lines[$ln - 1] =~ /^\+/;
2416 next if ($f =~ /^-/);
2417 last if (!$file && $f =~ /^\@\@/);
2419 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2421 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2428 next if ($f =~ /^$/);
2429 if ($f =~ /^\s*config\s/) {
2435 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2436 WARN("CONFIG_DESCRIPTION",
2437 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2439 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2442 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2443 if ($realfile =~ /Kconfig/ &&
2444 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2445 WARN("CONFIG_EXPERIMENTAL",
2446 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2449 # discourage the use of boolean for type definition attributes of Kconfig options
2450 if ($realfile =~ /Kconfig/ &&
2451 $line =~ /^\+\s*\bboolean\b/) {
2452 WARN("CONFIG_TYPE_BOOLEAN",
2453 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2456 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2457 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2460 'EXTRA_AFLAGS' => 'asflags-y',
2461 'EXTRA_CFLAGS' => 'ccflags-y',
2462 'EXTRA_CPPFLAGS' => 'cppflags-y',
2463 'EXTRA_LDFLAGS' => 'ldflags-y',
2466 WARN("DEPRECATED_VARIABLE",
2467 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2470 # check for DT compatible documentation
2471 if (defined $root &&
2472 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2473 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2475 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2477 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2478 my $vp_file = $dt_path . "vendor-prefixes.txt";
2480 foreach my $compat (@compats) {
2481 my $compat2 = $compat;
2482 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2483 my $compat3 = $compat;
2484 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2485 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2487 WARN("UNDOCUMENTED_DT_STRING",
2488 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2491 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2493 `grep -Eq "^$vendor\\b" $vp_file`;
2495 WARN("UNDOCUMENTED_DT_STRING",
2496 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2501 # check we are in a valid source file if not then ignore this hunk
2502 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2505 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2506 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2507 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2508 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2509 $length > $max_line_length)
2512 "line over $max_line_length characters\n" . $herecurr);
2515 # check for adding lines without a newline.
2516 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2517 WARN("MISSING_EOF_NEWLINE",
2518 "adding a line without newline at end of file\n" . $herecurr);
2521 # Blackfin: use hi/lo macros
2522 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2523 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2524 my $herevet = "$here\n" . cat_vet($line) . "\n";
2526 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2528 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2529 my $herevet = "$here\n" . cat_vet($line) . "\n";
2531 "use the HI() macro, not (... >> 16)\n" . $herevet);
2535 # check we are in a valid source file C or perl if not then ignore this hunk
2536 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2538 # at the beginning of a line any tabs must come first and anything
2539 # more than 8 must use tabs.
2540 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2541 $rawline =~ /^\+\s* \s*/) {
2542 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2544 if (ERROR("CODE_INDENT",
2545 "code indent should use tabs where possible\n" . $herevet) &&
2547 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2551 # check for space before tabs.
2552 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2553 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2554 if (WARN("SPACE_BEFORE_TAB",
2555 "please, no space before tabs\n" . $herevet) &&
2557 while ($fixed[$fixlinenr] =~
2558 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2559 while ($fixed[$fixlinenr] =~
2560 s/(^\+.*) +\t/$1\t/) {}
2564 # check for && or || at the start of a line
2565 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2566 CHK("LOGICAL_CONTINUATIONS",
2567 "Logical continuations should be on the previous line\n" . $hereprev);
2570 # check multi-line statement indentation matches previous line
2571 if ($^V && $^V ge 5.10.0 &&
2572 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2573 $prevline =~ /^\+(\t*)(.*)$/;
2577 my $pos = pos_last_openparen($rest);
2579 $line =~ /^(\+| )([ \t]*)/;
2582 my $goodtabindent = $oldindent .
2585 my $goodspaceindent = $oldindent . " " x $pos;
2587 if ($newindent ne $goodtabindent &&
2588 $newindent ne $goodspaceindent) {
2590 if (CHK("PARENTHESIS_ALIGNMENT",
2591 "Alignment should match open parenthesis\n" . $hereprev) &&
2592 $fix && $line =~ /^\+/) {
2593 $fixed[$fixlinenr] =~
2594 s/^\+[ \t]*/\+$goodtabindent/;
2600 # check for space after cast like "(int) foo" or "(struct foo) bar"
2601 # avoid checking a few false positives:
2602 # "sizeof(<type>)" or "__alignof__(<type>)"
2603 # function pointer declarations like "(*foo)(int) = bar;"
2604 # structure definitions like "(struct foo) { 0 };"
2605 # multiline macros that define functions
2606 # known attributes or the __attribute__ keyword
2607 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2608 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
2610 "No space is necessary after a cast\n" . $herecurr) &&
2612 $fixed[$fixlinenr] =~
2613 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2617 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2618 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2619 $rawline =~ /^\+[ \t]*\*/ &&
2621 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2622 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2625 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2626 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2627 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2628 $rawline =~ /^\+/ && #line is new
2629 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2630 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2631 "networking block comments start with * on subsequent lines\n" . $hereprev);
2634 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2635 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2636 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2637 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2638 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2639 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2640 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2643 # check for missing blank lines after struct/union declarations
2644 # with exceptions for various attributes and macros
2645 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2647 !($line =~ /^\+\s*$/ ||
2648 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2649 $line =~ /^\+\s*MODULE_/i ||
2650 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2651 $line =~ /^\+[a-z_]*init/ ||
2652 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2653 $line =~ /^\+\s*DECLARE/ ||
2654 $line =~ /^\+\s*__setup/)) {
2655 if (CHK("LINE_SPACING",
2656 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2658 fix_insert_line($fixlinenr, "\+");
2662 # check for multiple consecutive blank lines
2663 if ($prevline =~ /^[\+ ]\s*$/ &&
2664 $line =~ /^\+\s*$/ &&
2665 $last_blank_line != ($linenr - 1)) {
2666 if (CHK("LINE_SPACING",
2667 "Please don't use multiple blank lines\n" . $hereprev) &&
2669 fix_delete_line($fixlinenr, $rawline);
2672 $last_blank_line = $linenr;
2675 # check for missing blank lines after declarations
2676 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2677 # actual declarations
2678 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2679 # function pointer declarations
2680 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2681 # foo bar; where foo is some local typedef or #define
2682 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2683 # known declaration macros
2684 $prevline =~ /^\+\s+$declaration_macros/) &&
2685 # for "else if" which can look like "$Ident $Ident"
2686 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2687 # other possible extensions of declaration lines
2688 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2689 # not starting a section or a macro "\" extended line
2690 $prevline =~ /(?:\{\s*|\\)$/) &&
2691 # looks like a declaration
2692 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2693 # function pointer declarations
2694 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2695 # foo bar; where foo is some local typedef or #define
2696 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2697 # known declaration macros
2698 $sline =~ /^\+\s+$declaration_macros/ ||
2699 # start of struct or union or enum
2700 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2701 # start or end of block or continuation of declaration
2702 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2703 # bitfield continuation
2704 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2705 # other possible extensions of declaration lines
2706 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2707 # indentation of previous and current line are the same
2708 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2709 if (WARN("LINE_SPACING",
2710 "Missing a blank line after declarations\n" . $hereprev) &&
2712 fix_insert_line($fixlinenr, "\+");
2716 # check for spaces at the beginning of a line.
2718 # 1) within comments
2719 # 2) indented preprocessor commands
2721 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2722 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2723 if (WARN("LEADING_SPACE",
2724 "please, no spaces at the start of a line\n" . $herevet) &&
2726 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2730 # check we are in a valid C source file if not then ignore this hunk
2731 next if ($realfile !~ /\.(h|c)$/);
2733 # check indentation of any line with a bare else
2734 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2735 # if the previous line is a break or return and is indented 1 tab more...
2736 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2737 my $tabs = length($1) + 1;
2738 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2739 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2740 defined $lines[$linenr] &&
2741 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2742 WARN("UNNECESSARY_ELSE",
2743 "else is not generally useful after a break or return\n" . $hereprev);
2747 # check indentation of a line with a break;
2748 # if the previous line is a goto or return and is indented the same # of tabs
2749 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2751 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2752 WARN("UNNECESSARY_BREAK",
2753 "break is not useful after a goto or return\n" . $hereprev);
2757 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2758 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2759 WARN("CONFIG_EXPERIMENTAL",
2760 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2763 # check for RCS/CVS revision markers
2764 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2766 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2769 # Blackfin: don't use __builtin_bfin_[cs]sync
2770 if ($line =~ /__builtin_bfin_csync/) {
2771 my $herevet = "$here\n" . cat_vet($line) . "\n";
2773 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2775 if ($line =~ /__builtin_bfin_ssync/) {
2776 my $herevet = "$here\n" . cat_vet($line) . "\n";
2778 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2781 # check for old HOTPLUG __dev<foo> section markings
2782 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2783 WARN("HOTPLUG_SECTION",
2784 "Using $1 is unnecessary\n" . $herecurr);
2787 # Check for potential 'bare' types
2788 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2790 #print "LINE<$line>\n";
2791 if ($linenr >= $suppress_statement &&
2792 $realcnt && $sline =~ /.\s*\S/) {
2793 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2794 ctx_statement_block($linenr, $realcnt, 0);
2795 $stat =~ s/\n./\n /g;
2796 $cond =~ s/\n./\n /g;
2798 #print "linenr<$linenr> <$stat>\n";
2799 # If this statement has no statement boundaries within
2800 # it there is no point in retrying a statement scan
2801 # until we hit end of it.
2802 my $frag = $stat; $frag =~ s/;+\s*$//;
2803 if ($frag !~ /(?:{|;)/) {
2804 #print "skip<$line_nr_next>\n";
2805 $suppress_statement = $line_nr_next;
2808 # Find the real next line.
2809 $realline_next = $line_nr_next;
2810 if (defined $realline_next &&
2811 (!defined $lines[$realline_next - 1] ||
2812 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2819 # Ignore goto labels.
2820 if ($s =~ /$Ident:\*$/s) {
2822 # Ignore functions being called
2823 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2825 } elsif ($s =~ /^.\s*else\b/s) {
2827 # declarations always start with types
2828 } 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) {
2831 possible($type, "A:" . $s);
2833 # definitions in global scope can only start with types
2834 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2835 possible($1, "B:" . $s);
2838 # any (foo ... *) is a pointer cast, and foo is a type
2839 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2840 possible($1, "C:" . $s);
2843 # Check for any sort of function declaration.
2844 # int foo(something bar, other baz);
2845 # void (*store_gdt)(x86_descr_ptr *);
2846 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2847 my ($name_len) = length($1);
2850 substr($ctx, 0, $name_len + 1, '');
2851 $ctx =~ s/\)[^\)]*$//;
2853 for my $arg (split(/\s*,\s*/, $ctx)) {
2854 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2856 possible($1, "D:" . $s);
2864 # Checks which may be anchored in the context.
2867 # Check for switch () and associated case and default
2868 # statements should be at the same indent.
2869 if ($line=~/\bswitch\s*\(.*\)/) {
2872 my @ctx = ctx_block_outer($linenr, $realcnt);
2874 for my $ctx (@ctx) {
2875 my ($clen, $cindent) = line_stats($ctx);
2876 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2877 $indent != $cindent) {
2878 $err .= "$sep$ctx\n";
2885 ERROR("SWITCH_CASE_INDENT_LEVEL",
2886 "switch and case should be at the same indent\n$hereline$err");
2890 # if/while/etc brace do not go on next line, unless defining a do while loop,
2891 # or if that brace on the next line is for something else
2892 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2893 my $pre_ctx = "$1$2";
2895 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2897 if ($line =~ /^\+\t{6,}/) {
2898 WARN("DEEP_INDENTATION",
2899 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2902 my $ctx_cnt = $realcnt - $#ctx - 1;
2903 my $ctx = join("\n", @ctx);
2905 my $ctx_ln = $linenr;
2906 my $ctx_skip = $realcnt;
2908 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2909 defined $lines[$ctx_ln - 1] &&
2910 $lines[$ctx_ln - 1] =~ /^-/)) {
2911 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2912 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2916 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2917 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2919 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2921 "that open brace { should be on the previous line\n" .
2922 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2924 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2925 $ctx =~ /\)\s*\;\s*$/ &&
2926 defined $lines[$ctx_ln - 1])
2928 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2929 if ($nindent > $indent) {
2930 WARN("TRAILING_SEMICOLON",
2931 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2932 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2937 # Check relative indent for conditionals and blocks.
2938 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2939 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2940 ctx_statement_block($linenr, $realcnt, 0)
2941 if (!defined $stat);
2942 my ($s, $c) = ($stat, $cond);
2944 substr($s, 0, length($c), '');
2946 # Make sure we remove the line prefixes as we have
2947 # none on the first line, and are going to readd them
2951 # Find out how long the conditional actually is.
2952 my @newlines = ($c =~ /\n/gs);
2953 my $cond_lines = 1 + $#newlines;
2955 # We want to check the first line inside the block
2956 # starting at the end of the conditional, so remove:
2957 # 1) any blank line termination
2958 # 2) any opening brace { on end of the line
2960 my $continuation = 0;
2962 $s =~ s/^.*\bdo\b//;
2964 if ($s =~ s/^\s*\\//) {
2967 if ($s =~ s/^\s*?\n//) {
2972 # Also ignore a loop construct at the end of a
2973 # preprocessor statement.
2974 if (($prevline =~ /^.\s*#\s*define\s/ ||
2975 $prevline =~ /\\\s*$/) && $continuation == 0) {
2981 while ($cond_ptr != $cond_lines) {
2982 $cond_ptr = $cond_lines;
2984 # If we see an #else/#elif then the code
2986 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2991 # 1) blank lines, they should be at 0,
2992 # 2) preprocessor lines, and
2994 if ($continuation ||
2996 $s =~ /^\s*#\s*?/ ||
2997 $s =~ /^\s*$Ident\s*:/) {
2998 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2999 if ($s =~ s/^.*?\n//) {
3005 my (undef, $sindent) = line_stats("+" . $s);
3006 my $stat_real = raw_line($linenr, $cond_lines);
3008 # Check if either of these lines are modified, else
3009 # this is not this patch's fault.
3010 if (!defined($stat_real) ||
3011 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3014 if (defined($stat_real) && $cond_lines > 1) {
3015 $stat_real = "[...]\n$stat_real";
3018 #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";
3020 if ($check && (($sindent % 8) != 0 ||
3021 ($sindent <= $indent && $s ne ''))) {
3022 WARN("SUSPECT_CODE_INDENT",
3023 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3027 # Track the 'values' across context and added lines.
3028 my $opline = $line; $opline =~ s/^./ /;
3029 my ($curr_values, $curr_vars) =
3030 annotate_values($opline . "\n", $prev_values);
3031 $curr_values = $prev_values . $curr_values;
3033 my $outline = $opline; $outline =~ s/\t/ /g;
3034 print "$linenr > .$outline\n";
3035 print "$linenr > $curr_values\n";
3036 print "$linenr > $curr_vars\n";
3038 $prev_values = substr($curr_values, -1);
3040 #ignore lines not being added
3041 next if ($line =~ /^[^\+]/);
3043 # TEST: allow direct testing of the type matcher.
3045 if ($line =~ /^.\s*$Declare\s*$/) {
3047 "TEST: is type\n" . $herecurr);
3048 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3049 ERROR("TEST_NOT_TYPE",
3050 "TEST: is not type ($1 is)\n". $herecurr);
3054 # TEST: allow direct testing of the attribute matcher.
3056 if ($line =~ /^.\s*$Modifier\s*$/) {
3058 "TEST: is attr\n" . $herecurr);
3059 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3060 ERROR("TEST_NOT_ATTR",
3061 "TEST: is not attr ($1 is)\n". $herecurr);
3066 # check for initialisation to aggregates open brace on the next line
3067 if ($line =~ /^.\s*{/ &&
3068 $prevline =~ /(?:^|[^=])=\s*$/) {
3069 if (ERROR("OPEN_BRACE",
3070 "that open brace { should be on the previous line\n" . $hereprev) &&
3071 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3072 fix_delete_line($fixlinenr - 1, $prevrawline);
3073 fix_delete_line($fixlinenr, $rawline);
3074 my $fixedline = $prevrawline;
3075 $fixedline =~ s/\s*=\s*$/ = {/;
3076 fix_insert_line($fixlinenr, $fixedline);
3078 $fixedline =~ s/^(.\s*){\s*/$1/;
3079 fix_insert_line($fixlinenr, $fixedline);
3084 # Checks which are anchored on the added line.
3087 # check for malformed paths in #include statements (uses RAW line)
3088 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3090 if ($path =~ m{//}) {
3091 ERROR("MALFORMED_INCLUDE",
3092 "malformed #include filename\n" . $herecurr);
3094 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3095 ERROR("UAPI_INCLUDE",
3096 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3100 # no C99 // comments
3101 if ($line =~ m{//}) {
3102 if (ERROR("C99_COMMENTS",
3103 "do not use C99 // comments\n" . $herecurr) &&
3105 my $line = $fixed[$fixlinenr];
3106 if ($line =~ /\/\/(.*)$/) {
3107 my $comment = trim($1);
3108 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3112 # Remove C99 comments.
3114 $opline =~ s@//.*@@;
3116 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3117 # the whole statement.
3118 #print "APW <$lines[$realline_next - 1]>\n";
3119 if (defined $realline_next &&
3120 exists $lines[$realline_next - 1] &&
3121 !defined $suppress_export{$realline_next} &&
3122 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3123 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3124 # Handle definitions which produce identifiers with
3127 # EXPORT_SYMBOL(something_foo);
3129 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3130 $name =~ /^${Ident}_$2/) {
3131 #print "FOO C name<$name>\n";
3132 $suppress_export{$realline_next} = 1;
3134 } elsif ($stat !~ /(?:
3136 ^.DEFINE_$Ident\(\Q$name\E\)|
3137 ^.DECLARE_$Ident\(\Q$name\E\)|
3138 ^.LIST_HEAD\(\Q$name\E\)|
3139 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3140 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3142 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3143 $suppress_export{$realline_next} = 2;
3145 $suppress_export{$realline_next} = 1;
3148 if (!defined $suppress_export{$linenr} &&
3149 $prevline =~ /^.\s*$/ &&
3150 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3151 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3152 #print "FOO B <$lines[$linenr - 1]>\n";
3153 $suppress_export{$linenr} = 2;
3155 if (defined $suppress_export{$linenr} &&
3156 $suppress_export{$linenr} == 2) {
3157 WARN("EXPORT_SYMBOL",
3158 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3161 # check for global initialisers.
3162 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3163 if (ERROR("GLOBAL_INITIALISERS",
3164 "do not initialise globals to 0 or NULL\n" .
3167 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3170 # check for static initialisers.
3171 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3172 if (ERROR("INITIALISED_STATIC",
3173 "do not initialise statics to 0 or NULL\n" .
3176 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3180 # check for misordered declarations of char/short/int/long with signed/unsigned
3181 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3183 WARN("MISORDERED_TYPE",
3184 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3187 # check for static const char * arrays.
3188 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3189 WARN("STATIC_CONST_CHAR_ARRAY",
3190 "static const char * array should probably be static const char * const\n" .
3194 # check for static char foo[] = "bar" declarations.
3195 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3196 WARN("STATIC_CONST_CHAR_ARRAY",
3197 "static char array declaration should probably be static const char\n" .
3201 # check for const <foo> const where <foo> is not a pointer or array type
3202 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3204 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3206 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3207 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3209 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3213 # check for non-global char *foo[] = {"bar", ...} declarations.
3214 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3215 WARN("STATIC_CONST_CHAR_ARRAY",
3216 "char * array declaration might be better as static const\n" .
3220 # check for function declarations without arguments like "int foo()"
3221 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3222 if (ERROR("FUNCTION_WITHOUT_ARGS",
3223 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3225 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3229 # check for uses of DEFINE_PCI_DEVICE_TABLE
3230 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3231 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3232 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3234 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3238 # check for new typedefs, only function parameters and sparse annotations
3240 if ($line =~ /\btypedef\s/ &&
3241 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3242 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3243 $line !~ /\b$typeTypedefs\b/ &&
3244 $line !~ /\b$typeOtherOSTypedefs\b/ &&
3245 $line !~ /\b__bitwise(?:__|)\b/) {
3246 WARN("NEW_TYPEDEFS",
3247 "do not add new typedefs\n" . $herecurr);
3250 # * goes on variable not on type
3252 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3254 my ($ident, $from, $to) = ($1, $2, $2);
3256 # Should start with a space.
3257 $to =~ s/^(\S)/ $1/;
3258 # Should not end with a space.
3260 # '*'s should not have spaces between.
3261 while ($to =~ s/\*\s+\*/\*\*/) {
3264 ## print "1: from<$from> to<$to> ident<$ident>\n";
3266 if (ERROR("POINTER_LOCATION",
3267 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3269 my $sub_from = $ident;
3270 my $sub_to = $ident;
3271 $sub_to =~ s/\Q$from\E/$to/;
3272 $fixed[$fixlinenr] =~
3273 s@\Q$sub_from\E@$sub_to@;
3277 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3279 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3281 # Should start with a space.
3282 $to =~ s/^(\S)/ $1/;
3283 # Should not end with a space.
3285 # '*'s should not have spaces between.
3286 while ($to =~ s/\*\s+\*/\*\*/) {
3288 # Modifiers should have spaces.
3289 $to =~ s/(\b$Modifier$)/$1 /;
3291 ## print "2: from<$from> to<$to> ident<$ident>\n";
3292 if ($from ne $to && $ident !~ /^$Modifier$/) {
3293 if (ERROR("POINTER_LOCATION",
3294 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3297 my $sub_from = $match;
3298 my $sub_to = $match;
3299 $sub_to =~ s/\Q$from\E/$to/;
3300 $fixed[$fixlinenr] =~
3301 s@\Q$sub_from\E@$sub_to@;
3306 # # no BUG() or BUG_ON()
3307 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3308 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3309 # print "$herecurr";
3313 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3314 WARN("LINUX_VERSION_CODE",
3315 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3318 # check for uses of printk_ratelimit
3319 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3320 WARN("PRINTK_RATELIMITED",
3321 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3324 # printk should use KERN_* levels. Note that follow on printk's on the
3325 # same line do not need a level, so we use the current block context
3326 # to try and find and validate the current printk. In summary the current
3327 # printk includes all preceding printk's which have no newline on the end.
3328 # we assume the first bad printk is the one to report.
3329 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3331 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3332 #print "CHECK<$lines[$ln - 1]\n";
3333 # we have a preceding printk if it ends
3334 # with "\n" ignore it, else it is to blame
3335 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3336 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3343 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3344 "printk() should include KERN_ facility level\n" . $herecurr);
3348 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3350 my $level = lc($orig);
3351 $level = "warn" if ($level eq "warning");
3352 my $level2 = $level;
3353 $level2 = "dbg" if ($level eq "debug");
3354 WARN("PREFER_PR_LEVEL",
3355 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3358 if ($line =~ /\bpr_warning\s*\(/) {
3359 if (WARN("PREFER_PR_LEVEL",
3360 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3362 $fixed[$fixlinenr] =~
3363 s/\bpr_warning\b/pr_warn/;
3367 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3369 my $level = lc($orig);
3370 $level = "warn" if ($level eq "warning");
3371 $level = "dbg" if ($level eq "debug");
3372 WARN("PREFER_DEV_LEVEL",
3373 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3376 # function brace can't be on same line, except for #defines of do while,
3377 # or if closed on same line
3378 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3379 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3380 if (ERROR("OPEN_BRACE",
3381 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3383 fix_delete_line($fixlinenr, $rawline);
3384 my $fixed_line = $rawline;
3385 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3388 fix_insert_line($fixlinenr, ltrim($line1));
3389 fix_insert_line($fixlinenr, "\+{");
3390 if ($line2 !~ /^\s*$/) {
3391 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3396 # open braces for enum, union and struct go on the same line.
3397 if ($line =~ /^.\s*{/ &&
3398 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3399 if (ERROR("OPEN_BRACE",
3400 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3401 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3402 fix_delete_line($fixlinenr - 1, $prevrawline);
3403 fix_delete_line($fixlinenr, $rawline);
3404 my $fixedline = rtrim($prevrawline) . " {";
3405 fix_insert_line($fixlinenr, $fixedline);
3406 $fixedline = $rawline;
3407 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3408 if ($fixedline !~ /^\+\s*$/) {
3409 fix_insert_line($fixlinenr, $fixedline);
3414 # missing space after union, struct or enum definition
3415 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3417 "missing space after $1 definition\n" . $herecurr) &&
3419 $fixed[$fixlinenr] =~
3420 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3424 # Function pointer declarations
3425 # check spacing between type, funcptr, and args
3426 # canonical declaration is "type (*funcptr)(args...)"
3427 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3429 my $pre_pointer_space = $2;
3430 my $post_pointer_space = $3;
3432 my $post_funcname_space = $5;
3433 my $pre_args_space = $6;
3435 # the $Declare variable will capture all spaces after the type
3436 # so check it for a missing trailing missing space but pointer return types
3437 # don't need a space so don't warn for those.
3438 my $post_declare_space = "";
3439 if ($declare =~ /(\s+)$/) {
3440 $post_declare_space = $1;
3441 $declare = rtrim($declare);
3443 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3445 "missing space after return type\n" . $herecurr);
3446 $post_declare_space = " ";
3449 # unnecessary space "type (*funcptr)(args...)"
3450 # This test is not currently implemented because these declarations are
3452 # int foo(int bar, ...)
3453 # and this is form shouldn't/doesn't generate a checkpatch warning.
3455 # elsif ($declare =~ /\s{2,}$/) {
3457 # "Multiple spaces after return type\n" . $herecurr);
3460 # unnecessary space "type ( *funcptr)(args...)"
3461 if (defined $pre_pointer_space &&
3462 $pre_pointer_space =~ /^\s/) {
3464 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3467 # unnecessary space "type (* funcptr)(args...)"
3468 if (defined $post_pointer_space &&
3469 $post_pointer_space =~ /^\s/) {
3471 "Unnecessary space before function pointer name\n" . $herecurr);
3474 # unnecessary space "type (*funcptr )(args...)"
3475 if (defined $post_funcname_space &&
3476 $post_funcname_space =~ /^\s/) {
3478 "Unnecessary space after function pointer name\n" . $herecurr);
3481 # unnecessary space "type (*funcptr) (args...)"
3482 if (defined $pre_args_space &&
3483 $pre_args_space =~ /^\s/) {
3485 "Unnecessary space before function pointer arguments\n" . $herecurr);
3488 if (show_type("SPACING") && $fix) {
3489 $fixed[$fixlinenr] =~
3490 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3494 # check for spacing round square brackets; allowed:
3495 # 1. with a type on the left -- int [] a;
3496 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3497 # 3. inside a curly brace -- = { [0...10] = 5 }
3498 while ($line =~ /(.*?\s)\[/g) {
3499 my ($where, $prefix) = ($-[1], $1);
3500 if ($prefix !~ /$Type\s+$/ &&
3501 ($where != 0 || $prefix !~ /^.\s+$/) &&
3502 $prefix !~ /[{,]\s+$/) {
3503 if (ERROR("BRACKET_SPACE",
3504 "space prohibited before open square bracket '['\n" . $herecurr) &&
3506 $fixed[$fixlinenr] =~
3507 s/^(\+.*?)\s+\[/$1\[/;
3512 # check for spaces between functions and their parentheses.
3513 while ($line =~ /($Ident)\s+\(/g) {
3515 my $ctx_before = substr($line, 0, $-[1]);
3516 my $ctx = "$ctx_before$name";
3518 # Ignore those directives where spaces _are_ permitted.
3520 if|for|while|switch|return|case|
3521 volatile|__volatile__|
3522 __attribute__|format|__extension__|
3525 # cpp #define statements have non-optional spaces, ie
3526 # if there is a space between the name and the open
3527 # parenthesis it is simply not a parameter group.
3528 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3530 # cpp #elif statement condition may start with a (
3531 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3533 # If this whole things ends with a type its most
3534 # likely a typedef for a function.
3535 } elsif ($ctx =~ /$Type$/) {
3539 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3541 $fixed[$fixlinenr] =~
3542 s/\b$name\s+\(/$name\(/;
3547 # Check operator spacing.
3548 if (!($line=~/\#\s*include/)) {
3549 my $fixed_line = "";
3553 <<=|>>=|<=|>=|==|!=|
3554 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3555 =>|->|<<|>>|<|>|=|!|~|
3556 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3559 my @elements = split(/($ops|;)/, $opline);
3561 ## print("element count: <" . $#elements . ">\n");
3562 ## foreach my $el (@elements) {
3563 ## print("el: <$el>\n");
3566 my @fix_elements = ();
3569 foreach my $el (@elements) {
3570 push(@fix_elements, substr($rawline, $off, length($el)));
3571 $off += length($el);
3576 my $blank = copy_spacing($opline);
3577 my $last_after = -1;
3579 for (my $n = 0; $n < $#elements; $n += 2) {
3581 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3583 ## print("n: <$n> good: <$good>\n");
3585 $off += length($elements[$n]);
3587 # Pick up the preceding and succeeding characters.
3588 my $ca = substr($opline, 0, $off);
3590 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3591 $cc = substr($opline, $off + length($elements[$n + 1]));
3593 my $cb = "$ca$;$cc";
3596 $a = 'V' if ($elements[$n] ne '');
3597 $a = 'W' if ($elements[$n] =~ /\s$/);
3598 $a = 'C' if ($elements[$n] =~ /$;$/);
3599 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3600 $a = 'O' if ($elements[$n] eq '');
3601 $a = 'E' if ($ca =~ /^\s*$/);
3603 my $op = $elements[$n + 1];
3606 if (defined $elements[$n + 2]) {
3607 $c = 'V' if ($elements[$n + 2] ne '');
3608 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3609 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3610 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3611 $c = 'O' if ($elements[$n + 2] eq '');
3612 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3617 my $ctx = "${a}x${c}";
3619 my $at = "(ctx:$ctx)";
3621 my $ptr = substr($blank, 0, $off) . "^";
3622 my $hereptr = "$hereline$ptr\n";
3624 # Pull out the value of this operator.
3625 my $op_type = substr($curr_values, $off + 1, 1);
3627 # Get the full operator variant.
3628 my $opv = $op . substr($curr_vars, $off, 1);
3630 # Ignore operators passed as parameters.
3631 if ($op_type ne 'V' &&
3632 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3635 # } elsif ($op =~ /^$;+$/) {
3637 # ; should have either the end of line or a space or \ after it
3638 } elsif ($op eq ';') {
3639 if ($ctx !~ /.x[WEBC]/ &&
3640 $cc !~ /^\\/ && $cc !~ /^;/) {
3641 if (ERROR("SPACING",
3642 "space required after that '$op' $at\n" . $hereptr)) {
3643 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3649 } elsif ($op eq '//') {
3651 # : when part of a bitfield
3652 } elsif ($opv eq ':B') {
3653 # skip the bitfield test for now
3657 } elsif ($op eq '->') {
3658 if ($ctx =~ /Wx.|.xW/) {
3659 if (ERROR("SPACING",
3660 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3661 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3662 if (defined $fix_elements[$n + 2]) {
3663 $fix_elements[$n + 2] =~ s/^\s+//;
3669 # , must not have a space before and must have a space on the right.
3670 } elsif ($op eq ',') {
3671 my $rtrim_before = 0;
3672 my $space_after = 0;
3673 if ($ctx =~ /Wx./) {
3674 if (ERROR("SPACING",
3675 "space prohibited before that '$op' $at\n" . $hereptr)) {
3680 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3681 if (ERROR("SPACING",
3682 "space required after that '$op' $at\n" . $hereptr)) {
3688 if ($rtrim_before || $space_after) {
3689 if ($rtrim_before) {
3690 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3692 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3699 # '*' as part of a type definition -- reported already.
3700 } elsif ($opv eq '*_') {
3701 #warn "'*' is part of type\n";
3703 # unary operators should have a space before and
3704 # none after. May be left adjacent to another
3705 # unary operator, or a cast
3706 } elsif ($op eq '!' || $op eq '~' ||
3707 $opv eq '*U' || $opv eq '-U' ||
3708 $opv eq '&U' || $opv eq '&&U') {
3709 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3710 if (ERROR("SPACING",
3711 "space required before that '$op' $at\n" . $hereptr)) {
3712 if ($n != $last_after + 2) {
3713 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3718 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3719 # A unary '*' may be const
3721 } elsif ($ctx =~ /.xW/) {
3722 if (ERROR("SPACING",
3723 "space prohibited after that '$op' $at\n" . $hereptr)) {
3724 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3725 if (defined $fix_elements[$n + 2]) {
3726 $fix_elements[$n + 2] =~ s/^\s+//;
3732 # unary ++ and unary -- are allowed no space on one side.
3733 } elsif ($op eq '++' or $op eq '--') {
3734 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3735 if (ERROR("SPACING",
3736 "space required one side of that '$op' $at\n" . $hereptr)) {
3737 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3741 if ($ctx =~ /Wx[BE]/ ||
3742 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3743 if (ERROR("SPACING",
3744 "space prohibited before that '$op' $at\n" . $hereptr)) {
3745 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3749 if ($ctx =~ /ExW/) {
3750 if (ERROR("SPACING",
3751 "space prohibited after that '$op' $at\n" . $hereptr)) {
3752 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3753 if (defined $fix_elements[$n + 2]) {
3754 $fix_elements[$n + 2] =~ s/^\s+//;
3760 # << and >> may either have or not have spaces both sides
3761 } elsif ($op eq '<<' or $op eq '>>' or
3762 $op eq '&' or $op eq '^' or $op eq '|' or
3763 $op eq '+' or $op eq '-' or
3764 $op eq '*' or $op eq '/' or
3768 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
3770 "spaces preferred around that '$op' $at\n" . $hereptr)) {
3771 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3772 $fix_elements[$n + 2] =~ s/^\s+//;
3775 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
3777 "space preferred before that '$op' $at\n" . $hereptr)) {
3778 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
3782 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3783 if (ERROR("SPACING",
3784 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3785 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3786 if (defined $fix_elements[$n + 2]) {
3787 $fix_elements[$n + 2] =~ s/^\s+//;
3793 # A colon needs no spaces before when it is
3794 # terminating a case value or a label.
3795 } elsif ($opv eq ':C' || $opv eq ':L') {
3796 if ($ctx =~ /Wx./) {
3797 if (ERROR("SPACING",
3798 "space prohibited before that '$op' $at\n" . $hereptr)) {
3799 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3804 # All the others need spaces both sides.
3805 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3808 # Ignore email addresses <foo@bar>
3810 $cc =~ /^\S+\@\S+>/) ||
3812 $ca =~ /<\S+\@\S+$/))
3817 # messages are ERROR, but ?: are CHK
3819 my $msg_type = \&ERROR;
3820 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3822 if (&{$msg_type}("SPACING",
3823 "spaces required around that '$op' $at\n" . $hereptr)) {
3824 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3825 if (defined $fix_elements[$n + 2]) {
3826 $fix_elements[$n + 2] =~ s/^\s+//;
3832 $off += length($elements[$n + 1]);
3834 ## print("n: <$n> GOOD: <$good>\n");
3836 $fixed_line = $fixed_line . $good;
3839 if (($#elements % 2) == 0) {
3840 $fixed_line = $fixed_line . $fix_elements[$#elements];
3843 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3844 $fixed[$fixlinenr] = $fixed_line;
3850 # check for whitespace before a non-naked semicolon
3851 if ($line =~ /^\+.*\S\s+;\s*$/) {
3853 "space prohibited before semicolon\n" . $herecurr) &&
3855 1 while $fixed[$fixlinenr] =~
3856 s/^(\+.*\S)\s+;/$1;/;
3860 # check for multiple assignments
3861 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3862 CHK("MULTIPLE_ASSIGNMENTS",
3863 "multiple assignments should be avoided\n" . $herecurr);
3866 ## # check for multiple declarations, allowing for a function declaration
3868 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3869 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3871 ## # Remove any bracketed sections to ensure we do not
3872 ## # falsly report the parameters of functions.
3874 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3876 ## if ($ln =~ /,/) {
3877 ## WARN("MULTIPLE_DECLARATION",
3878 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3882 #need space before brace following if, while, etc
3883 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3885 if (ERROR("SPACING",
3886 "space required before the open brace '{'\n" . $herecurr) &&
3888 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3892 ## # check for blank lines before declarations
3893 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3894 ## $prevrawline =~ /^.\s*$/) {
3896 ## "No blank lines before declarations\n" . $hereprev);
3900 # closing brace should have a space following it when it has anything
3902 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3903 if (ERROR("SPACING",
3904 "space required after that close brace '}'\n" . $herecurr) &&
3906 $fixed[$fixlinenr] =~
3907 s/}((?!(?:,|;|\)))\S)/} $1/;
3911 # check spacing on square brackets
3912 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3913 if (ERROR("SPACING",
3914 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3916 $fixed[$fixlinenr] =~
3920 if ($line =~ /\s\]/) {
3921 if (ERROR("SPACING",
3922 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3924 $fixed[$fixlinenr] =~
3929 # check spacing on parentheses
3930 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3931 $line !~ /for\s*\(\s+;/) {
3932 if (ERROR("SPACING",
3933 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3935 $fixed[$fixlinenr] =~
3939 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3940 $line !~ /for\s*\(.*;\s+\)/ &&
3941 $line !~ /:\s+\)/) {
3942 if (ERROR("SPACING",
3943 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3945 $fixed[$fixlinenr] =~
3950 # check unnecessary parentheses around addressof/dereference single $Lvals
3951 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3953 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3955 if (CHK("UNNECESSARY_PARENTHESES",
3956 "Unnecessary parentheses around $var\n" . $herecurr) &&
3958 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3962 # check for unnecessary parentheses around function pointer uses
3963 # ie: (foo->bar)(); should be foo->bar();
3964 # but not "if (foo->bar) (" to avoid some false positives
3965 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3967 if (CHK("UNNECESSARY_PARENTHESES",
3968 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3970 my $var2 = deparenthesize($var);
3972 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3976 #goto labels aren't indented, allow a single space however
3977 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3978 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3979 if (WARN("INDENTED_LABEL",
3980 "labels should not be indented\n" . $herecurr) &&
3982 $fixed[$fixlinenr] =~
3987 # return is not a function
3988 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3990 if ($^V && $^V ge 5.10.0 &&
3991 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3993 $value = deparenthesize($value);
3994 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3995 ERROR("RETURN_PARENTHESES",
3996 "return is not a function, parentheses are not required\n" . $herecurr);
3998 } elsif ($spacing !~ /\s+/) {
4000 "space required before the open parenthesis '('\n" . $herecurr);
4004 # unnecessary return in a void function
4005 # at end-of-function, with the previous line a single leading tab, then return;
4006 # and the line before that not a goto label target like "out:"
4007 if ($sline =~ /^[ \+]}\s*$/ &&
4008 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4010 $lines[$linenr - 3] =~ /^[ +]/ &&
4011 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4013 "void function return statements are not generally useful\n" . $hereprev);
4016 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4017 if ($^V && $^V ge 5.10.0 &&
4018 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4019 my $openparens = $1;
4020 my $count = $openparens =~ tr@\(@\(@;
4022 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4023 my $comp = $4; #Not $1 because of $LvalOrFunc
4024 $msg = " - maybe == should be = ?" if ($comp eq "==");
4025 WARN("UNNECESSARY_PARENTHESES",
4026 "Unnecessary parentheses$msg\n" . $herecurr);
4030 # Return of what appears to be an errno should normally be negative
4031 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4033 if ($name ne 'EOF' && $name ne 'ERROR') {
4034 WARN("USE_NEGATIVE_ERRNO",
4035 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4039 # Need a space before open parenthesis after if, while etc
4040 if ($line =~ /\b(if|while|for|switch)\(/) {
4041 if (ERROR("SPACING",
4042 "space required before the open parenthesis '('\n" . $herecurr) &&
4044 $fixed[$fixlinenr] =~
4045 s/\b(if|while|for|switch)\(/$1 \(/;
4049 # Check for illegal assignment in if conditional -- and check for trailing
4050 # statements after the conditional.
4051 if ($line =~ /do\s*(?!{)/) {
4052 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4053 ctx_statement_block($linenr, $realcnt, 0)
4054 if (!defined $stat);
4055 my ($stat_next) = ctx_statement_block($line_nr_next,
4056 $remain_next, $off_next);
4057 $stat_next =~ s/\n./\n /g;
4058 ##print "stat<$stat> stat_next<$stat_next>\n";
4060 if ($stat_next =~ /^\s*while\b/) {
4061 # If the statement carries leading newlines,
4062 # then count those as offsets.
4064 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4066 statement_rawlines($whitespace) - 1;
4068 $suppress_whiletrailers{$line_nr_next +
4072 if (!defined $suppress_whiletrailers{$linenr} &&
4073 defined($stat) && defined($cond) &&
4074 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4075 my ($s, $c) = ($stat, $cond);
4077 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4078 ERROR("ASSIGN_IN_IF",
4079 "do not use assignment in if condition\n" . $herecurr);
4082 # Find out what is on the end of the line after the
4084 substr($s, 0, length($c), '');
4086 $s =~ s/$;//g; # Remove any comments
4087 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4088 $c !~ /}\s*while\s*/)
4090 # Find out how long the conditional actually is.
4091 my @newlines = ($c =~ /\n/gs);
4092 my $cond_lines = 1 + $#newlines;
4095 $stat_real = raw_line($linenr, $cond_lines)
4096 . "\n" if ($cond_lines);
4097 if (defined($stat_real) && $cond_lines > 1) {
4098 $stat_real = "[...]\n$stat_real";
4101 ERROR("TRAILING_STATEMENTS",
4102 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4106 # Check for bitwise tests written as boolean
4118 WARN("HEXADECIMAL_BOOLEAN_TEST",
4119 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4122 # if and else should not have general statements after it
4123 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4125 $s =~ s/$;//g; # Remove any comments
4126 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4127 ERROR("TRAILING_STATEMENTS",
4128 "trailing statements should be on next line\n" . $herecurr);
4131 # if should not continue a brace
4132 if ($line =~ /}\s*if\b/) {
4133 ERROR("TRAILING_STATEMENTS",
4134 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4137 # case and default should not have general statements after them
4138 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4140 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4144 ERROR("TRAILING_STATEMENTS",
4145 "trailing statements should be on next line\n" . $herecurr);
4148 # Check for }<nl>else {, these must be at the same
4149 # indent level to be relevant to each other.
4150 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4151 $previndent == $indent) {
4152 if (ERROR("ELSE_AFTER_BRACE",
4153 "else should follow close brace '}'\n" . $hereprev) &&
4154 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4155 fix_delete_line($fixlinenr - 1, $prevrawline);
4156 fix_delete_line($fixlinenr, $rawline);
4157 my $fixedline = $prevrawline;
4158 $fixedline =~ s/}\s*$//;
4159 if ($fixedline !~ /^\+\s*$/) {
4160 fix_insert_line($fixlinenr, $fixedline);
4162 $fixedline = $rawline;
4163 $fixedline =~ s/^(.\s*)else/$1} else/;
4164 fix_insert_line($fixlinenr, $fixedline);
4168 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4169 $previndent == $indent) {
4170 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4172 # Find out what is on the end of the line after the
4174 substr($s, 0, length($c), '');
4177 if ($s =~ /^\s*;/) {
4178 if (ERROR("WHILE_AFTER_BRACE",
4179 "while should follow close brace '}'\n" . $hereprev) &&
4180 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4181 fix_delete_line($fixlinenr - 1, $prevrawline);
4182 fix_delete_line($fixlinenr, $rawline);
4183 my $fixedline = $prevrawline;
4184 my $trailing = $rawline;
4185 $trailing =~ s/^\+//;
4186 $trailing = trim($trailing);
4187 $fixedline =~ s/}\s*$/} $trailing/;
4188 fix_insert_line($fixlinenr, $fixedline);
4193 #Specific variable tests
4194 while ($line =~ m{($Constant|$Lval)}g) {
4197 #gcc binary extension
4198 if ($var =~ /^$Binary$/) {
4199 if (WARN("GCC_BINARY_CONSTANT",
4200 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4202 my $hexval = sprintf("0x%x", oct($var));
4203 $fixed[$fixlinenr] =~
4204 s/\b$var\b/$hexval/;
4209 if ($var !~ /^$Constant$/ &&
4210 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4211 #Ignore Page<foo> variants
4212 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4213 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4214 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4215 #Ignore some three character SI units explicitly, like MiB and KHz
4216 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4217 while ($var =~ m{($Ident)}g) {
4219 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4221 seed_camelcase_includes();
4222 if (!$file && !$camelcase_file_seeded) {
4223 seed_camelcase_file($realfile);
4224 $camelcase_file_seeded = 1;
4227 if (!defined $camelcase{$word}) {
4228 $camelcase{$word} = 1;
4230 "Avoid CamelCase: <$word>\n" . $herecurr);
4236 #no spaces allowed after \ in define
4237 if ($line =~ /\#\s*define.*\\\s+$/) {
4238 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4239 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4241 $fixed[$fixlinenr] =~ s/\s+$//;
4245 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4246 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4248 my $checkfile = "include/linux/$file";
4249 if (-f "$root/$checkfile" &&
4250 $realfile ne $checkfile &&
4251 $1 !~ /$allowed_asm_includes/)
4253 if ($realfile =~ m{^arch/}) {
4254 CHK("ARCH_INCLUDE_LINUX",
4255 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4257 WARN("INCLUDE_LINUX",
4258 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4263 # multi-statement macros should be enclosed in a do while loop, grab the
4264 # first statement and ensure its the whole macro if its not enclosed
4265 # in a known good container
4266 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4267 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4270 my ($off, $dstat, $dcond, $rest);
4272 my $has_flow_statement = 0;
4273 my $has_arg_concat = 0;
4274 ($dstat, $dcond, $ln, $cnt, $off) =
4275 ctx_statement_block($linenr, $realcnt, 0);
4277 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4278 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4280 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4281 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4283 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4285 $dstat =~ s/\\\n.//g;
4286 $dstat =~ s/^\s*//s;
4287 $dstat =~ s/\s*$//s;
4289 # Flatten any parentheses and braces
4290 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4291 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4292 $dstat =~ s/\[[^\[\]]*\]/1/)
4296 # Flatten any obvious string concatentation.
4297 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4298 $dstat =~ s/$Ident\s*("X*")/$1/)
4302 my $exceptions = qr{
4314 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4316 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4317 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4318 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4319 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4320 $dstat !~ /$exceptions/ &&
4321 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4322 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4323 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4324 $dstat !~ /^for\s*$Constant$/ && # for (...)
4325 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4326 $dstat !~ /^do\s*{/ && # do {...
4327 $dstat !~ /^\({/ && # ({...
4328 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4331 my $herectx = $here . "\n";
4332 my $cnt = statement_rawlines($ctx);
4334 for (my $n = 0; $n < $cnt; $n++) {
4335 $herectx .= raw_line($linenr, $n) . "\n";
4338 if ($dstat =~ /;/) {
4339 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4340 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4342 ERROR("COMPLEX_MACRO",
4343 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4347 # check for macros with flow control, but without ## concatenation
4348 # ## concatenation is commonly a macro that defines a function so ignore those
4349 if ($has_flow_statement && !$has_arg_concat) {
4350 my $herectx = $here . "\n";
4351 my $cnt = statement_rawlines($ctx);
4353 for (my $n = 0; $n < $cnt; $n++) {
4354 $herectx .= raw_line($linenr, $n) . "\n";
4356 WARN("MACRO_WITH_FLOW_CONTROL",
4357 "Macros with flow control statements should be avoided\n" . "$herectx");
4360 # check for line continuations outside of #defines, preprocessor #, and asm
4363 if ($prevline !~ /^..*\\$/ &&
4364 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4365 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4366 $line =~ /^\+.*\\$/) {
4367 WARN("LINE_CONTINUATIONS",
4368 "Avoid unnecessary line continuations\n" . $herecurr);
4372 # do {} while (0) macro tests:
4373 # single-statement macros do not need to be enclosed in do while (0) loop,
4374 # macro should not end with a semicolon
4375 if ($^V && $^V ge 5.10.0 &&
4376 $realfile !~ m@/vmlinux.lds.h$@ &&
4377 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4380 my ($off, $dstat, $dcond, $rest);
4382 ($dstat, $dcond, $ln, $cnt, $off) =
4383 ctx_statement_block($linenr, $realcnt, 0);
4386 $dstat =~ s/\\\n.//g;
4389 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4394 my $cnt = statement_rawlines($ctx);
4395 my $herectx = $here . "\n";
4397 for (my $n = 0; $n < $cnt; $n++) {
4398 $herectx .= raw_line($linenr, $n) . "\n";
4401 if (($stmts =~ tr/;/;/) == 1 &&
4402 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4403 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4404 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4406 if (defined $semis && $semis ne "") {
4407 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4408 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4410 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4412 my $cnt = statement_rawlines($ctx);
4413 my $herectx = $here . "\n";
4415 for (my $n = 0; $n < $cnt; $n++) {
4416 $herectx .= raw_line($linenr, $n) . "\n";
4419 WARN("TRAILING_SEMICOLON",
4420 "macros should not use a trailing semicolon\n" . "$herectx");
4424 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4425 # all assignments may have only one of the following with an assignment:
4428 # VMLINUX_SYMBOL(...)
4429 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4430 WARN("MISSING_VMLINUX_SYMBOL",
4431 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4434 # check for redundant bracing round if etc
4435 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4436 my ($level, $endln, @chunks) =
4437 ctx_statement_full($linenr, $realcnt, 1);
4438 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4439 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4440 if ($#chunks > 0 && $level == 0) {
4444 my $herectx = $here . "\n";
4445 my $ln = $linenr - 1;
4446 for my $chunk (@chunks) {
4447 my ($cond, $block) = @{$chunk};
4449 # If the condition carries leading newlines, then count those as offsets.
4450 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4451 my $offset = statement_rawlines($whitespace) - 1;
4453 $allowed[$allow] = 0;
4454 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4456 # We have looked at and allowed this specific line.
4457 $suppress_ifbraces{$ln + $offset} = 1;
4459 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4460 $ln += statement_rawlines($block) - 1;
4462 substr($block, 0, length($cond), '');
4464 $seen++ if ($block =~ /^\s*{/);
4466 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4467 if (statement_lines($cond) > 1) {
4468 #print "APW: ALLOWED: cond<$cond>\n";
4469 $allowed[$allow] = 1;
4471 if ($block =~/\b(?:if|for|while)\b/) {
4472 #print "APW: ALLOWED: block<$block>\n";
4473 $allowed[$allow] = 1;
4475 if (statement_block_size($block) > 1) {
4476 #print "APW: ALLOWED: lines block<$block>\n";
4477 $allowed[$allow] = 1;
4482 my $sum_allowed = 0;
4483 foreach (@allowed) {
4486 if ($sum_allowed == 0) {
4488 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4489 } elsif ($sum_allowed != $allow &&
4492 "braces {} should be used on all arms of this statement\n" . $herectx);
4497 if (!defined $suppress_ifbraces{$linenr - 1} &&
4498 $line =~ /\b(if|while|for|else)\b/) {
4501 # Check the pre-context.
4502 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4503 #print "APW: ALLOWED: pre<$1>\n";
4507 my ($level, $endln, @chunks) =
4508 ctx_statement_full($linenr, $realcnt, $-[0]);
4510 # Check the condition.
4511 my ($cond, $block) = @{$chunks[0]};
4512 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4513 if (defined $cond) {
4514 substr($block, 0, length($cond), '');
4516 if (statement_lines($cond) > 1) {
4517 #print "APW: ALLOWED: cond<$cond>\n";
4520 if ($block =~/\b(?:if|for|while)\b/) {
4521 #print "APW: ALLOWED: block<$block>\n";
4524 if (statement_block_size($block) > 1) {
4525 #print "APW: ALLOWED: lines block<$block>\n";
4528 # Check the post-context.
4529 if (defined $chunks[1]) {
4530 my ($cond, $block) = @{$chunks[1]};
4531 if (defined $cond) {
4532 substr($block, 0, length($cond), '');
4534 if ($block =~ /^\s*\{/) {
4535 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4539 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4540 my $herectx = $here . "\n";
4541 my $cnt = statement_rawlines($block);
4543 for (my $n = 0; $n < $cnt; $n++) {
4544 $herectx .= raw_line($linenr, $n) . "\n";
4548 "braces {} are not necessary for single statement blocks\n" . $herectx);
4552 # check for unnecessary blank lines around braces
4553 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4555 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4556 $fix && $prevrawline =~ /^\+/) {
4557 fix_delete_line($fixlinenr - 1, $prevrawline);
4560 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4562 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4564 fix_delete_line($fixlinenr, $rawline);
4568 # no volatiles please
4569 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4570 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4572 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4575 # Check for user-visible strings broken across lines, which breaks the ability
4576 # to grep for the string. Make exceptions when the previous string ends in a
4577 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4578 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4579 if ($line =~ /^\+\s*"[X\t]*"/ &&
4580 $prevline =~ /"\s*$/ &&
4581 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4582 if (WARN("SPLIT_STRING",
4583 "quoted string split across lines\n" . $hereprev) &&
4585 $prevrawline =~ /^\+.*"\s*$/ &&
4586 $last_coalesced_string_linenr != $linenr - 1) {
4587 my $extracted_string = get_quoted_string($line, $rawline);
4588 my $comma_close = "";
4589 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4593 fix_delete_line($fixlinenr - 1, $prevrawline);
4594 fix_delete_line($fixlinenr, $rawline);
4595 my $fixedline = $prevrawline;
4596 $fixedline =~ s/"\s*$//;
4597 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4598 fix_insert_line($fixlinenr - 1, $fixedline);
4599 $fixedline = $rawline;
4600 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4601 if ($fixedline !~ /\+\s*$/) {
4602 fix_insert_line($fixlinenr, $fixedline);
4604 $last_coalesced_string_linenr = $linenr;
4608 # check for missing a space in a string concatenation
4609 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4610 WARN('MISSING_SPACE',
4611 "break quoted strings at a space character\n" . $hereprev);
4614 # check for spaces before a quoted newline
4615 if ($rawline =~ /^.*\".*\s\\n/) {
4616 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4617 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4619 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4624 # concatenated string without spaces between elements
4625 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4626 CHK("CONCATENATED_STRING",
4627 "Concatenated strings should use spaces between elements\n" . $herecurr);
4630 # uncoalesced string fragments
4631 if ($line =~ /"X*"\s*"/) {
4632 WARN("STRING_FRAGMENTS",
4633 "Consecutive strings are generally better as a single string\n" . $herecurr);
4636 # check for %L{u,d,i} in strings
4638 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4639 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4640 $string =~ s/%%/__/g;
4641 if ($string =~ /(?<!%)%L[udi]/) {
4643 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4648 # check for line continuations in quoted strings with odd counts of "
4649 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4650 WARN("LINE_CONTINUATIONS",
4651 "Avoid line continuations in quoted strings\n" . $herecurr);
4655 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4656 CHK("REDUNDANT_CODE",
4657 "if this code is redundant consider removing it\n" .
4661 # check for needless "if (<foo>) fn(<foo>)" uses
4662 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4663 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4664 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4666 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4670 # check for unnecessary "Out of Memory" messages
4671 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4672 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4673 (defined $1 || defined $3) &&
4676 my $testline = $lines[$linenr - 3];
4678 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4679 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4681 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4683 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4687 # check for logging functions with KERN_<LEVEL>
4688 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4689 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4691 if (WARN("UNNECESSARY_KERN_LEVEL",
4692 "Possible unnecessary $level\n" . $herecurr) &&
4694 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4698 # check for mask then right shift without a parentheses
4699 if ($^V && $^V ge 5.10.0 &&
4700 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4701 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4702 WARN("MASK_THEN_SHIFT",
4703 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4706 # check for pointer comparisons to NULL
4707 if ($^V && $^V ge 5.10.0) {
4708 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4711 $equal = "" if ($4 eq "!=");
4712 if (CHK("COMPARISON_TO_NULL",
4713 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4715 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4720 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4721 if ($line =~ /(\b$InitAttribute\b)/) {
4723 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4726 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4727 ERROR("MISPLACED_INIT",
4728 "$attr should be placed after $var\n" . $herecurr)) ||
4729 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4730 WARN("MISPLACED_INIT",
4731 "$attr should be placed after $var\n" . $herecurr))) &&
4733 $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;
4738 # check for $InitAttributeData (ie: __initdata) with const
4739 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4741 $attr =~ /($InitAttributePrefix)(.*)/;
4742 my $attr_prefix = $1;
4744 if (ERROR("INIT_ATTRIBUTE",
4745 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4747 $fixed[$fixlinenr] =~
4748 s/$InitAttributeData/${attr_prefix}initconst/;
4752 # check for $InitAttributeConst (ie: __initconst) without const
4753 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4755 if (ERROR("INIT_ATTRIBUTE",
4756 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4758 my $lead = $fixed[$fixlinenr] =~
4759 /(^\+\s*(?:static\s+))/;
4761 $lead = "$lead " if ($lead !~ /^\+$/);
4762 $lead = "${lead}const ";
4763 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4767 # don't use __constant_<foo> functions outside of include/uapi/
4768 if ($realfile !~ m@^include/uapi/@ &&
4769 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4770 my $constant_func = $1;
4771 my $func = $constant_func;
4772 $func =~ s/^__constant_//;
4773 if (WARN("CONSTANT_CONVERSION",
4774 "$constant_func should be $func\n" . $herecurr) &&
4776 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4780 # prefer usleep_range over udelay
4781 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4783 # ignore udelay's < 10, however
4784 if (! ($delay < 10) ) {
4786 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4788 if ($delay > 2000) {
4790 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4794 # warn about unexpectedly long msleep's
4795 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4798 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4802 # check for comparisons of jiffies
4803 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4804 WARN("JIFFIES_COMPARISON",
4805 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4808 # check for comparisons of get_jiffies_64()
4809 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4810 WARN("JIFFIES_COMPARISON",
4811 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4814 # warn about #ifdefs in C files
4815 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4816 # print "#ifdef in C files should be avoided\n";
4817 # print "$herecurr";
4821 # warn about spacing in #ifdefs
4822 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4823 if (ERROR("SPACING",
4824 "exactly one space required after that #$1\n" . $herecurr) &&
4826 $fixed[$fixlinenr] =~
4827 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4832 # check for spinlock_t definitions without a comment.
4833 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4834 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4836 if (!ctx_has_comment($first_line, $linenr)) {
4837 CHK("UNCOMMENTED_DEFINITION",
4838 "$1 definition without comment\n" . $herecurr);
4841 # check for memory barriers without a comment.
4842 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4843 if (!ctx_has_comment($first_line, $linenr)) {
4844 WARN("MEMORY_BARRIER",
4845 "memory barrier without comment\n" . $herecurr);
4848 # check of hardware specific defines
4849 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4851 "architecture specific defines should be avoided\n" . $herecurr);
4854 # Check that the storage class is at the beginning of a declaration
4855 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4856 WARN("STORAGE_CLASS",
4857 "storage class should be at the beginning of the declaration\n" . $herecurr)
4860 # check the location of the inline attribute, that it is between
4861 # storage class and type.
4862 if ($line =~ /\b$Type\s+$Inline\b/ ||
4863 $line =~ /\b$Inline\s+$Storage\b/) {
4864 ERROR("INLINE_LOCATION",
4865 "inline keyword should sit between storage class and type\n" . $herecurr);
4868 # Check for __inline__ and __inline, prefer inline
4869 if ($realfile !~ m@\binclude/uapi/@ &&
4870 $line =~ /\b(__inline__|__inline)\b/) {
4872 "plain inline is preferred over $1\n" . $herecurr) &&
4874 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4879 # Check for __attribute__ packed, prefer __packed
4880 if ($realfile !~ m@\binclude/uapi/@ &&
4881 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4882 WARN("PREFER_PACKED",
4883 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4886 # Check for __attribute__ aligned, prefer __aligned
4887 if ($realfile !~ m@\binclude/uapi/@ &&
4888 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4889 WARN("PREFER_ALIGNED",
4890 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4893 # Check for __attribute__ format(printf, prefer __printf
4894 if ($realfile !~ m@\binclude/uapi/@ &&
4895 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4896 if (WARN("PREFER_PRINTF",
4897 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4899 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4904 # Check for __attribute__ format(scanf, prefer __scanf
4905 if ($realfile !~ m@\binclude/uapi/@ &&
4906 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4907 if (WARN("PREFER_SCANF",
4908 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4910 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4914 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4915 if ($^V && $^V ge 5.10.0 &&
4916 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4917 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4918 $line =~ /\b__weak\b/)) {
4919 ERROR("WEAK_DECLARATION",
4920 "Using weak declarations can have unintended link defects\n" . $herecurr);
4923 # check for sizeof(&)
4924 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4925 WARN("SIZEOF_ADDRESS",
4926 "sizeof(& should be avoided\n" . $herecurr);
4929 # check for sizeof without parenthesis
4930 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4931 if (WARN("SIZEOF_PARENTHESIS",
4932 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4934 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4938 # check for struct spinlock declarations
4939 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4940 WARN("USE_SPINLOCK_T",
4941 "struct spinlock should be spinlock_t\n" . $herecurr);
4944 # check for seq_printf uses that could be seq_puts
4945 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4946 my $fmt = get_quoted_string($line, $rawline);
4949 if (WARN("PREFER_SEQ_PUTS",
4950 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4952 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4957 # Check for misused memsets
4958 if ($^V && $^V ge 5.10.0 &&
4960 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4966 if ($ms_size =~ /^(0x|)0$/i) {
4968 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4969 } elsif ($ms_size =~ /^(0x|)1$/i) {
4971 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4975 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4976 if ($^V && $^V ge 5.10.0 &&
4977 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4978 if (WARN("PREFER_ETHER_ADDR_COPY",
4979 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4981 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4985 # typecasts on min/max could be min_t/max_t
4986 if ($^V && $^V ge 5.10.0 &&
4988 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4989 if (defined $2 || defined $7) {
4991 my $cast1 = deparenthesize($2);
4993 my $cast2 = deparenthesize($7);
4997 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4998 $cast = "$cast1 or $cast2";
4999 } elsif ($cast1 ne "") {
5005 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5009 # check usleep_range arguments
5010 if ($^V && $^V ge 5.10.0 &&
5012 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5016 WARN("USLEEP_RANGE",
5017 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5018 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5020 WARN("USLEEP_RANGE",
5021 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5025 # check for naked sscanf
5026 if ($^V && $^V ge 5.10.0 &&
5028 $line =~ /\bsscanf\b/ &&
5029 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5030 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5031 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5032 my $lc = $stat =~ tr@\n@@;
5033 $lc = $lc + $linenr;
5034 my $stat_real = raw_line($linenr, 0);
5035 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5036 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5038 WARN("NAKED_SSCANF",
5039 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5042 # check for simple sscanf that should be kstrto<foo>
5043 if ($^V && $^V ge 5.10.0 &&
5045 $line =~ /\bsscanf\b/) {
5046 my $lc = $stat =~ tr@\n@@;
5047 $lc = $lc + $linenr;
5048 my $stat_real = raw_line($linenr, 0);
5049 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5050 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5052 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5054 my $count = $format =~ tr@%@%@;
5056 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5057 WARN("SSCANF_TO_KSTRTO",
5058 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5063 # check for new externs in .h files.
5064 if ($realfile =~ /\.h$/ &&
5065 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5066 if (CHK("AVOID_EXTERNS",
5067 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5069 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5073 # check for new externs in .c files.
5074 if ($realfile =~ /\.c$/ && defined $stat &&
5075 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5077 my $function_name = $1;
5078 my $paren_space = $2;
5081 if (defined $cond) {
5082 substr($s, 0, length($cond), '');
5084 if ($s =~ /^\s*;/ &&
5085 $function_name ne 'uninitialized_var')
5087 WARN("AVOID_EXTERNS",
5088 "externs should be avoided in .c files\n" . $herecurr);
5091 if ($paren_space =~ /\n/) {
5092 WARN("FUNCTION_ARGUMENTS",
5093 "arguments for function declarations should follow identifier\n" . $herecurr);
5096 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5097 $stat =~ /^.\s*extern\s+/)
5099 WARN("AVOID_EXTERNS",
5100 "externs should be avoided in .c files\n" . $herecurr);
5103 # checks for new __setup's
5104 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5107 if (!grep(/$name/, @setup_docs)) {
5108 CHK("UNDOCUMENTED_SETUP",
5109 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5113 # check for pointless casting of kmalloc return
5114 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5115 WARN("UNNECESSARY_CASTS",
5116 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5120 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5121 if ($^V && $^V ge 5.10.0 &&
5122 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5123 CHK("ALLOC_SIZEOF_STRUCT",
5124 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5127 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5128 if ($^V && $^V ge 5.10.0 &&
5129 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5133 my $newfunc = "kmalloc_array";
5134 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5137 if ($a1 =~ /^sizeof\s*\S/) {
5141 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5142 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5143 if (WARN("ALLOC_WITH_MULTIPLY",
5144 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5146 $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;
5152 # check for krealloc arg reuse
5153 if ($^V && $^V ge 5.10.0 &&
5154 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5155 WARN("KREALLOC_ARG_REUSE",
5156 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5159 # check for alloc argument mismatch
5160 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5161 WARN("ALLOC_ARRAY_ARGS",
5162 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5165 # check for multiple semicolons
5166 if ($line =~ /;\s*;\s*$/) {
5167 if (WARN("ONE_SEMICOLON",
5168 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5170 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5174 # check for #defines like: 1 << <digit> that could be BIT(digit)
5175 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5177 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5178 if (CHK("BIT_MACRO",
5179 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5181 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5185 # check for case / default statements not preceded by break/fallthrough/switch
5186 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5188 my $has_statement = 0;
5190 my $prevline = $linenr;
5191 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5193 my $rline = $rawlines[$prevline - 1];
5194 my $fline = $lines[$prevline - 1];
5195 last if ($fline =~ /^\@\@/);
5196 next if ($fline =~ /^\-/);
5197 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5198 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5199 next if ($fline =~ /^.[\s$;]*$/);
5202 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5204 if (!$has_break && $has_statement) {
5205 WARN("MISSING_BREAK",
5206 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5210 # check for switch/default statements without a break;
5211 if ($^V && $^V ge 5.10.0 &&
5213 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5215 my $herectx = $here . "\n";
5216 my $cnt = statement_rawlines($stat);
5217 for (my $n = 0; $n < $cnt; $n++) {
5218 $herectx .= raw_line($linenr, $n) . "\n";
5220 WARN("DEFAULT_NO_BREAK",
5221 "switch default: should use break\n" . $herectx);
5224 # check for gcc specific __FUNCTION__
5225 if ($line =~ /\b__FUNCTION__\b/) {
5226 if (WARN("USE_FUNC",
5227 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5229 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5233 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5234 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5236 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5239 # check for use of yield()
5240 if ($line =~ /\byield\s*\(\s*\)/) {
5242 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5245 # check for comparisons against true and false
5246 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5254 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5256 my $type = lc($otype);
5257 if ($type =~ /^(?:true|false)$/) {
5258 if (("$test" eq "==" && "$type" eq "true") ||
5259 ("$test" eq "!=" && "$type" eq "false")) {
5263 CHK("BOOL_COMPARISON",
5264 "Using comparison to $otype is error prone\n" . $herecurr);
5266 ## maybe suggesting a correct construct would better
5267 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5272 # check for semaphores initialized locked
5273 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5274 WARN("CONSIDER_COMPLETION",
5275 "consider using a completion\n" . $herecurr);
5278 # recommend kstrto* over simple_strto* and strict_strto*
5279 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5280 WARN("CONSIDER_KSTRTO",
5281 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5284 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5285 if ($line =~ /^.\s*__initcall\s*\(/) {
5286 WARN("USE_DEVICE_INITCALL",
5287 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5290 # check for various structs that are normally const (ops, kgdb, device_tree)
5291 my $const_structs = qr{
5293 address_space_operations|
5295 block_device_operations|
5300 file_lock_operations|
5310 lock_manager_operations|
5317 pipe_buf_operations|
5318 platform_hibernation_ops|
5319 platform_suspend_ops|
5324 soc_pcmcia_socket_ops|
5330 if ($line !~ /\bconst\b/ &&
5331 $line =~ /\bstruct\s+($const_structs)\b/) {
5332 WARN("CONST_STRUCT",
5333 "struct $1 should normally be const\n" .
5337 # use of NR_CPUS is usually wrong
5338 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5339 if ($line =~ /\bNR_CPUS\b/ &&
5340 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5341 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5342 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5343 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5344 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5347 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5350 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5351 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5352 ERROR("DEFINE_ARCH_HAS",
5353 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5356 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5357 if ($^V && $^V ge 5.10.0 &&
5358 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5359 WARN("LIKELY_MISUSE",
5360 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5363 # whine mightly about in_atomic
5364 if ($line =~ /\bin_atomic\s*\(/) {
5365 if ($realfile =~ m@^drivers/@) {
5367 "do not use in_atomic in drivers\n" . $herecurr);
5368 } elsif ($realfile !~ m@^kernel/@) {
5370 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5374 # check for lockdep_set_novalidate_class
5375 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5376 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5377 if ($realfile !~ m@^kernel/lockdep@ &&
5378 $realfile !~ m@^include/linux/lockdep@ &&
5379 $realfile !~ m@^drivers/base/core@) {
5381 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5385 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
5386 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
5387 WARN("EXPORTED_WORLD_WRITABLE",
5388 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5391 # Mode permission misuses where it seems decimal should be octal
5392 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5393 if ($^V && $^V ge 5.10.0 &&
5394 $line =~ /$mode_perms_search/) {
5395 foreach my $entry (@mode_permission_funcs) {
5396 my $func = $entry->[0];
5397 my $arg_pos = $entry->[1];
5402 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5404 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5405 if ($line =~ /$test/) {
5407 $val = $6 if ($skip_args ne "");
5409 if ($val !~ /^0$/ &&
5410 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5411 length($val) ne 4)) {
5412 ERROR("NON_OCTAL_PERMISSIONS",
5413 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5414 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5415 ERROR("EXPORTED_WORLD_WRITABLE",
5416 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5423 # If we have no input at all, then there is nothing to report on
5424 # so just keep quiet.
5425 if ($#rawlines == -1) {
5429 # In mailback mode only produce a report in the negative, for
5430 # things that appear to be patches.
5431 if ($mailback && ($clean == 1 || !$is_patch)) {
5435 # This is not a patch, and we are are in 'no-patch' mode so
5437 if (!$chk_patch && !$is_patch) {
5442 ERROR("NOT_UNIFIED_DIFF",
5443 "Does not appear to be a unified-diff format patch\n");
5445 if ($is_patch && $chk_signoff && $signoff == 0) {
5446 ERROR("MISSING_SIGN_OFF",
5447 "Missing Signed-off-by: line(s)\n");
5450 print report_dump();
5451 if ($summary && !($clean == 1 && $quiet == 1)) {
5452 print "$filename " if ($summary_file);
5453 print "total: $cnt_error errors, $cnt_warn warnings, " .
5454 (($check)? "$cnt_chk checks, " : "") .
5455 "$cnt_lines lines checked\n";
5456 print "\n" if ($quiet == 0);
5461 if ($^V lt 5.10.0) {
5462 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5463 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5466 # If there were whitespace errors which cleanpatch can fix
5467 # then suggest that.
5468 if ($rpt_cleaners) {
5469 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5470 print " scripts/cleanfile\n\n";
5475 hash_show_words(\%use_type, "Used");
5476 hash_show_words(\%ignore_type, "Ignored");
5478 if ($clean == 0 && $fix &&
5479 ("@rawlines" ne "@fixed" ||
5480 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5481 my $newfile = $filename;
5482 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5486 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5488 open($f, '>', $newfile)
5489 or die "$P: Can't open $newfile for write\n";
5490 foreach my $fixed_line (@fixed) {
5493 if ($linecount > 3) {
5494 $fixed_line =~ s/^\+//;
5495 print $f $fixed_line . "\n";
5498 print $f $fixed_line . "\n";
5505 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5507 Do _NOT_ trust the results written to this file.
5508 Do _NOT_ submit these changes without inspecting them for correctness.
5510 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5511 No warranties, expressed or implied...
5517 if ($clean == 1 && $quiet == 0) {
5518 print "$vname has no obvious style problems and is ready for submission.\n"
5520 if ($clean == 0 && $quiet == 0) {
5522 $vname has style problems, please review.
5524 If any of these errors are false positives, please report
5525 them to the maintainer, see CHECKPATCH in MAINTAINERS.