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 $commit_log_long_line = 0;
1902 my $reported_maintainer_file = 0;
1903 my $non_utf8_charset = 0;
1905 my $last_blank_line = 0;
1906 my $last_coalesced_string_linenr = -1;
1914 # Trace the real file/line as we go.
1920 my $comment_edge = 0;
1924 my $prev_values = 'E';
1927 my %suppress_ifbraces;
1928 my %suppress_whiletrailers;
1929 my %suppress_export;
1930 my $suppress_statement = 0;
1932 my %signatures = ();
1934 # Pre-scan the patch sanitizing the lines.
1935 # Pre-scan the patch looking for any __setup documentation.
1937 my @setup_docs = ();
1940 my $camelcase_file_seeded = 0;
1942 sanitise_line_reset();
1944 foreach my $rawline (@rawlines) {
1948 push(@fixed, $rawline) if ($fix);
1950 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1952 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1957 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1966 # Guestimate if this is a continuing comment. Run
1967 # the context looking for a comment "edge". If this
1968 # edge is a close comment then we must be in a comment
1972 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1973 next if (defined $rawlines[$ln - 1] &&
1974 $rawlines[$ln - 1] =~ /^-/);
1976 #print "RAW<$rawlines[$ln - 1]>\n";
1977 last if (!defined $rawlines[$ln - 1]);
1978 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1979 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1984 if (defined $edge && $edge eq '*/') {
1988 # Guestimate if this is a continuing comment. If this
1989 # is the start of a diff block and this line starts
1990 # ' *' then it is very likely a comment.
1991 if (!defined $edge &&
1992 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1997 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1998 sanitise_line_reset($in_comment);
2000 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2001 # Standardise the strings and chars within the input to
2002 # simplify matching -- only bother with positive lines.
2003 $line = sanitise_line($rawline);
2005 push(@lines, $line);
2008 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2013 #print "==>$rawline\n";
2014 #print "-->$line\n";
2016 if ($setup_docs && $line =~ /^\+/) {
2017 push(@setup_docs, $line);
2026 foreach my $line (@lines) {
2029 my $sline = $line; #copy of $line
2030 $sline =~ s/$;/ /g; #with comments as spaces
2032 my $rawline = $rawlines[$linenr - 1];
2034 #extract the line range in the file after the patch is applied
2035 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2037 $first_line = $linenr + 1;
2047 %suppress_ifbraces = ();
2048 %suppress_whiletrailers = ();
2049 %suppress_export = ();
2050 $suppress_statement = 0;
2053 # track the line number as we move through the hunk, note that
2054 # new versions of GNU diff omit the leading space on completely
2055 # blank context lines so we need to count that too.
2056 } elsif ($line =~ /^( |\+|$)/) {
2058 $realcnt-- if ($realcnt != 0);
2060 # Measure the line length and indent.
2061 ($length, $indent) = line_stats($rawline);
2063 # Track the previous line.
2064 ($prevline, $stashline) = ($stashline, $line);
2065 ($previndent, $stashindent) = ($stashindent, $indent);
2066 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2068 #warn "line<$line>\n";
2070 } elsif ($realcnt == 1) {
2074 my $hunk_line = ($realcnt != 0);
2076 #make up the handle for any error we report on this line
2077 $prefix = "$filename:$realline: " if ($emacs && $file);
2078 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2080 $here = "#$linenr: " if (!$file);
2081 $here = "#$realline: " if ($file);
2084 # extract the filename as it passes
2085 if ($line =~ /^diff --git.*?(\S+)$/) {
2087 $realfile =~ s@^([^/]*)/@@ if (!$file);
2090 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2092 $realfile =~ s@^([^/]*)/@@ if (!$file);
2096 if (!$file && $tree && $p1_prefix ne '' &&
2097 -e "$root/$p1_prefix") {
2098 WARN("PATCH_PREFIX",
2099 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2102 if ($realfile =~ m@^include/asm/@) {
2103 ERROR("MODIFIED_INCLUDE_ASM",
2104 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2110 if ($realfile =~ m@^(drivers/net/|net/)@) {
2113 $check = $check_orig;
2118 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2120 my $hereline = "$here\n$rawline\n";
2121 my $herecurr = "$here\n$rawline\n";
2122 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2124 $cnt_lines++ if ($realcnt != 0);
2126 # Check for incorrect file permissions
2127 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2128 my $permhere = $here . "FILE: $realfile\n";
2129 if ($realfile !~ m@scripts/@ &&
2130 $realfile !~ /\.(py|pl|awk|sh)$/) {
2131 ERROR("EXECUTE_PERMISSIONS",
2132 "do not set execute permissions for source files\n" . $permhere);
2136 # Check the patch for a signoff:
2137 if ($line =~ /^\s*signed-off-by:/i) {
2142 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2143 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2144 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2145 $reported_maintainer_file = 1;
2148 # Check signature styles
2149 if (!$in_header_lines &&
2150 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2151 my $space_before = $1;
2153 my $space_after = $3;
2155 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2157 if ($sign_off !~ /$signature_tags/) {
2158 WARN("BAD_SIGN_OFF",
2159 "Non-standard signature: $sign_off\n" . $herecurr);
2161 if (defined $space_before && $space_before ne "") {
2162 if (WARN("BAD_SIGN_OFF",
2163 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2165 $fixed[$fixlinenr] =
2166 "$ucfirst_sign_off $email";
2169 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2170 if (WARN("BAD_SIGN_OFF",
2171 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2173 $fixed[$fixlinenr] =
2174 "$ucfirst_sign_off $email";
2178 if (!defined $space_after || $space_after ne " ") {
2179 if (WARN("BAD_SIGN_OFF",
2180 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2182 $fixed[$fixlinenr] =
2183 "$ucfirst_sign_off $email";
2187 my ($email_name, $email_address, $comment) = parse_email($email);
2188 my $suggested_email = format_email(($email_name, $email_address));
2189 if ($suggested_email eq "") {
2190 ERROR("BAD_SIGN_OFF",
2191 "Unrecognized email address: '$email'\n" . $herecurr);
2193 my $dequoted = $suggested_email;
2194 $dequoted =~ s/^"//;
2195 $dequoted =~ s/" </ </;
2196 # Don't force email to have quotes
2197 # Allow just an angle bracketed address
2198 if ("$dequoted$comment" ne $email &&
2199 "<$email_address>$comment" ne $email &&
2200 "$suggested_email$comment" ne $email) {
2201 WARN("BAD_SIGN_OFF",
2202 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2206 # Check for duplicate signatures
2207 my $sig_nospace = $line;
2208 $sig_nospace =~ s/\s//g;
2209 $sig_nospace = lc($sig_nospace);
2210 if (defined $signatures{$sig_nospace}) {
2211 WARN("BAD_SIGN_OFF",
2212 "Duplicate signature\n" . $herecurr);
2214 $signatures{$sig_nospace} = 1;
2218 # Check email subject for common tools that don't need to be mentioned
2219 if ($in_header_lines &&
2220 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2221 WARN("EMAIL_SUBJECT",
2222 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2225 # Check for old stable address
2226 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2227 ERROR("STABLE_ADDRESS",
2228 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2231 # Check for unwanted Gerrit info
2232 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2233 ERROR("GERRIT_CHANGE_ID",
2234 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2237 # Check for line lengths > 75 in commit log, warn once
2238 if ($in_commit_log && !$commit_log_long_line &&
2239 length($line) > 75) {
2240 WARN("COMMIT_LOG_LONG_LINE",
2241 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2242 $commit_log_long_line = 1;
2245 # Check for git id commit length and improperly formed commit descriptions
2246 if ($in_commit_log && $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i) {
2248 my $orig_commit = lc($2);
2255 my $id = '0123456789ab';
2256 my $orig_desc = "commit description";
2257 my $description = "";
2259 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2260 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2261 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2262 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2263 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2266 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2267 defined $rawlines[$linenr] &&
2268 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2271 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2272 defined $rawlines[$linenr] &&
2273 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2274 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2276 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2277 $orig_desc .= " " . $1;
2281 ($id, $description) = git_commit_info($orig_commit,
2284 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2285 ERROR("GIT_COMMIT_ID",
2286 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2290 # Check for added, moved or deleted files
2291 if (!$reported_maintainer_file && !$in_commit_log &&
2292 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2293 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2294 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2295 (defined($1) || defined($2))))) {
2296 $reported_maintainer_file = 1;
2297 WARN("FILE_PATH_CHANGES",
2298 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2301 # Check for wrappage within a valid hunk of the file
2302 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2303 ERROR("CORRUPTED_PATCH",
2304 "patch seems to be corrupt (line wrapped?)\n" .
2305 $herecurr) if (!$emitted_corrupt++);
2308 # Check for absolute kernel paths.
2310 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2313 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2314 check_absolute_file($1, $herecurr)) {
2317 check_absolute_file($file, $herecurr);
2322 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2323 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2324 $rawline !~ m/^$UTF8*$/) {
2325 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2327 my $blank = copy_spacing($rawline);
2328 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2329 my $hereptr = "$hereline$ptr\n";
2332 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2335 # Check if it's the start of a commit log
2336 # (not a header line and we haven't seen the patch filename)
2337 if ($in_header_lines && $realfile =~ /^$/ &&
2338 !($rawline =~ /^\s+\S/ ||
2339 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2340 $in_header_lines = 0;
2344 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2345 # declined it, i.e defined some charset where it is missing.
2346 if ($in_header_lines &&
2347 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2349 $non_utf8_charset = 1;
2352 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2353 $rawline =~ /$NON_ASCII_UTF8/) {
2354 WARN("UTF8_BEFORE_PATCH",
2355 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2358 # Check for various typo / spelling mistakes
2359 if (defined($misspellings) &&
2360 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2361 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2363 my $typo_fix = $spelling_fix{lc($typo)};
2364 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2365 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2366 my $msg_type = \&WARN;
2367 $msg_type = \&CHK if ($file);
2368 if (&{$msg_type}("TYPO_SPELLING",
2369 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2371 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2376 # ignore non-hunk lines and lines being removed
2377 next if (!$hunk_line || $line =~ /^-/);
2379 #trailing whitespace
2380 if ($line =~ /^\+.*\015/) {
2381 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2382 if (ERROR("DOS_LINE_ENDINGS",
2383 "DOS line endings\n" . $herevet) &&
2385 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2387 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2388 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2389 if (ERROR("TRAILING_WHITESPACE",
2390 "trailing whitespace\n" . $herevet) &&
2392 $fixed[$fixlinenr] =~ s/\s+$//;
2398 # Check for FSF mailing addresses.
2399 if ($rawline =~ /\bwrite to the Free/i ||
2400 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2401 $rawline =~ /\b51\s+Franklin\s+St/i) {
2402 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2403 my $msg_type = \&ERROR;
2404 $msg_type = \&CHK if ($file);
2405 &{$msg_type}("FSF_MAILING_ADDRESS",
2406 "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)
2409 # check for Kconfig help text having a real description
2410 # Only applies when adding the entry originally, after that we do not have
2411 # sufficient context to determine whether it is indeed long enough.
2412 if ($realfile =~ /Kconfig/ &&
2413 $line =~ /^\+\s*config\s+/) {
2416 my $ln = $linenr + 1;
2420 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2421 $f = $lines[$ln - 1];
2422 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2423 $is_end = $lines[$ln - 1] =~ /^\+/;
2425 next if ($f =~ /^-/);
2426 last if (!$file && $f =~ /^\@\@/);
2428 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2430 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2437 next if ($f =~ /^$/);
2438 if ($f =~ /^\s*config\s/) {
2444 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2445 WARN("CONFIG_DESCRIPTION",
2446 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2448 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2451 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2452 if ($realfile =~ /Kconfig/ &&
2453 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2454 WARN("CONFIG_EXPERIMENTAL",
2455 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2458 # discourage the use of boolean for type definition attributes of Kconfig options
2459 if ($realfile =~ /Kconfig/ &&
2460 $line =~ /^\+\s*\bboolean\b/) {
2461 WARN("CONFIG_TYPE_BOOLEAN",
2462 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2465 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2466 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2469 'EXTRA_AFLAGS' => 'asflags-y',
2470 'EXTRA_CFLAGS' => 'ccflags-y',
2471 'EXTRA_CPPFLAGS' => 'cppflags-y',
2472 'EXTRA_LDFLAGS' => 'ldflags-y',
2475 WARN("DEPRECATED_VARIABLE",
2476 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2479 # check for DT compatible documentation
2480 if (defined $root &&
2481 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2482 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2484 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2486 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2487 my $vp_file = $dt_path . "vendor-prefixes.txt";
2489 foreach my $compat (@compats) {
2490 my $compat2 = $compat;
2491 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2492 my $compat3 = $compat;
2493 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2494 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2496 WARN("UNDOCUMENTED_DT_STRING",
2497 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2500 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2502 `grep -Eq "^$vendor\\b" $vp_file`;
2504 WARN("UNDOCUMENTED_DT_STRING",
2505 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2510 # check we are in a valid source file if not then ignore this hunk
2511 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2514 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2515 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2516 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?$String\s*(?:|,|\)\s*;)\s*$/ ||
2517 $line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2518 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) &&
2519 $length > $max_line_length)
2522 "line over $max_line_length characters\n" . $herecurr);
2525 # check for adding lines without a newline.
2526 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2527 WARN("MISSING_EOF_NEWLINE",
2528 "adding a line without newline at end of file\n" . $herecurr);
2531 # Blackfin: use hi/lo macros
2532 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2533 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2534 my $herevet = "$here\n" . cat_vet($line) . "\n";
2536 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2538 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2539 my $herevet = "$here\n" . cat_vet($line) . "\n";
2541 "use the HI() macro, not (... >> 16)\n" . $herevet);
2545 # check we are in a valid source file C or perl if not then ignore this hunk
2546 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2548 # at the beginning of a line any tabs must come first and anything
2549 # more than 8 must use tabs.
2550 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2551 $rawline =~ /^\+\s* \s*/) {
2552 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2554 if (ERROR("CODE_INDENT",
2555 "code indent should use tabs where possible\n" . $herevet) &&
2557 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2561 # check for space before tabs.
2562 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2563 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2564 if (WARN("SPACE_BEFORE_TAB",
2565 "please, no space before tabs\n" . $herevet) &&
2567 while ($fixed[$fixlinenr] =~
2568 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2569 while ($fixed[$fixlinenr] =~
2570 s/(^\+.*) +\t/$1\t/) {}
2574 # check for && or || at the start of a line
2575 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2576 CHK("LOGICAL_CONTINUATIONS",
2577 "Logical continuations should be on the previous line\n" . $hereprev);
2580 # check multi-line statement indentation matches previous line
2581 if ($^V && $^V ge 5.10.0 &&
2582 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2583 $prevline =~ /^\+(\t*)(.*)$/;
2587 my $pos = pos_last_openparen($rest);
2589 $line =~ /^(\+| )([ \t]*)/;
2592 my $goodtabindent = $oldindent .
2595 my $goodspaceindent = $oldindent . " " x $pos;
2597 if ($newindent ne $goodtabindent &&
2598 $newindent ne $goodspaceindent) {
2600 if (CHK("PARENTHESIS_ALIGNMENT",
2601 "Alignment should match open parenthesis\n" . $hereprev) &&
2602 $fix && $line =~ /^\+/) {
2603 $fixed[$fixlinenr] =~
2604 s/^\+[ \t]*/\+$goodtabindent/;
2610 # check for space after cast like "(int) foo" or "(struct foo) bar"
2611 # avoid checking a few false positives:
2612 # "sizeof(<type>)" or "__alignof__(<type>)"
2613 # function pointer declarations like "(*foo)(int) = bar;"
2614 # structure definitions like "(struct foo) { 0 };"
2615 # multiline macros that define functions
2616 # known attributes or the __attribute__ keyword
2617 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2618 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
2620 "No space is necessary after a cast\n" . $herecurr) &&
2622 $fixed[$fixlinenr] =~
2623 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2627 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2628 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2629 $rawline =~ /^\+[ \t]*\*/ &&
2631 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2632 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2635 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2636 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2637 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2638 $rawline =~ /^\+/ && #line is new
2639 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2640 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2641 "networking block comments start with * on subsequent lines\n" . $hereprev);
2644 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2645 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2646 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2647 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2648 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2649 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2650 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2653 # check for missing blank lines after struct/union declarations
2654 # with exceptions for various attributes and macros
2655 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2657 !($line =~ /^\+\s*$/ ||
2658 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2659 $line =~ /^\+\s*MODULE_/i ||
2660 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2661 $line =~ /^\+[a-z_]*init/ ||
2662 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2663 $line =~ /^\+\s*DECLARE/ ||
2664 $line =~ /^\+\s*__setup/)) {
2665 if (CHK("LINE_SPACING",
2666 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2668 fix_insert_line($fixlinenr, "\+");
2672 # check for multiple consecutive blank lines
2673 if ($prevline =~ /^[\+ ]\s*$/ &&
2674 $line =~ /^\+\s*$/ &&
2675 $last_blank_line != ($linenr - 1)) {
2676 if (CHK("LINE_SPACING",
2677 "Please don't use multiple blank lines\n" . $hereprev) &&
2679 fix_delete_line($fixlinenr, $rawline);
2682 $last_blank_line = $linenr;
2685 # check for missing blank lines after declarations
2686 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2687 # actual declarations
2688 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2689 # function pointer declarations
2690 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2691 # foo bar; where foo is some local typedef or #define
2692 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2693 # known declaration macros
2694 $prevline =~ /^\+\s+$declaration_macros/) &&
2695 # for "else if" which can look like "$Ident $Ident"
2696 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2697 # other possible extensions of declaration lines
2698 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2699 # not starting a section or a macro "\" extended line
2700 $prevline =~ /(?:\{\s*|\\)$/) &&
2701 # looks like a declaration
2702 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2703 # function pointer declarations
2704 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2705 # foo bar; where foo is some local typedef or #define
2706 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2707 # known declaration macros
2708 $sline =~ /^\+\s+$declaration_macros/ ||
2709 # start of struct or union or enum
2710 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2711 # start or end of block or continuation of declaration
2712 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2713 # bitfield continuation
2714 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2715 # other possible extensions of declaration lines
2716 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2717 # indentation of previous and current line are the same
2718 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2719 if (WARN("LINE_SPACING",
2720 "Missing a blank line after declarations\n" . $hereprev) &&
2722 fix_insert_line($fixlinenr, "\+");
2726 # check for spaces at the beginning of a line.
2728 # 1) within comments
2729 # 2) indented preprocessor commands
2731 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2732 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2733 if (WARN("LEADING_SPACE",
2734 "please, no spaces at the start of a line\n" . $herevet) &&
2736 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2740 # check we are in a valid C source file if not then ignore this hunk
2741 next if ($realfile !~ /\.(h|c)$/);
2743 # check indentation of any line with a bare else
2744 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2745 # if the previous line is a break or return and is indented 1 tab more...
2746 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2747 my $tabs = length($1) + 1;
2748 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2749 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2750 defined $lines[$linenr] &&
2751 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2752 WARN("UNNECESSARY_ELSE",
2753 "else is not generally useful after a break or return\n" . $hereprev);
2757 # check indentation of a line with a break;
2758 # if the previous line is a goto or return and is indented the same # of tabs
2759 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2761 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2762 WARN("UNNECESSARY_BREAK",
2763 "break is not useful after a goto or return\n" . $hereprev);
2767 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2768 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2769 WARN("CONFIG_EXPERIMENTAL",
2770 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2773 # check for RCS/CVS revision markers
2774 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2776 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2779 # Blackfin: don't use __builtin_bfin_[cs]sync
2780 if ($line =~ /__builtin_bfin_csync/) {
2781 my $herevet = "$here\n" . cat_vet($line) . "\n";
2783 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2785 if ($line =~ /__builtin_bfin_ssync/) {
2786 my $herevet = "$here\n" . cat_vet($line) . "\n";
2788 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2791 # check for old HOTPLUG __dev<foo> section markings
2792 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2793 WARN("HOTPLUG_SECTION",
2794 "Using $1 is unnecessary\n" . $herecurr);
2797 # Check for potential 'bare' types
2798 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2800 #print "LINE<$line>\n";
2801 if ($linenr >= $suppress_statement &&
2802 $realcnt && $sline =~ /.\s*\S/) {
2803 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2804 ctx_statement_block($linenr, $realcnt, 0);
2805 $stat =~ s/\n./\n /g;
2806 $cond =~ s/\n./\n /g;
2808 #print "linenr<$linenr> <$stat>\n";
2809 # If this statement has no statement boundaries within
2810 # it there is no point in retrying a statement scan
2811 # until we hit end of it.
2812 my $frag = $stat; $frag =~ s/;+\s*$//;
2813 if ($frag !~ /(?:{|;)/) {
2814 #print "skip<$line_nr_next>\n";
2815 $suppress_statement = $line_nr_next;
2818 # Find the real next line.
2819 $realline_next = $line_nr_next;
2820 if (defined $realline_next &&
2821 (!defined $lines[$realline_next - 1] ||
2822 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2829 # Ignore goto labels.
2830 if ($s =~ /$Ident:\*$/s) {
2832 # Ignore functions being called
2833 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2835 } elsif ($s =~ /^.\s*else\b/s) {
2837 # declarations always start with types
2838 } 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) {
2841 possible($type, "A:" . $s);
2843 # definitions in global scope can only start with types
2844 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2845 possible($1, "B:" . $s);
2848 # any (foo ... *) is a pointer cast, and foo is a type
2849 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2850 possible($1, "C:" . $s);
2853 # Check for any sort of function declaration.
2854 # int foo(something bar, other baz);
2855 # void (*store_gdt)(x86_descr_ptr *);
2856 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2857 my ($name_len) = length($1);
2860 substr($ctx, 0, $name_len + 1, '');
2861 $ctx =~ s/\)[^\)]*$//;
2863 for my $arg (split(/\s*,\s*/, $ctx)) {
2864 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2866 possible($1, "D:" . $s);
2874 # Checks which may be anchored in the context.
2877 # Check for switch () and associated case and default
2878 # statements should be at the same indent.
2879 if ($line=~/\bswitch\s*\(.*\)/) {
2882 my @ctx = ctx_block_outer($linenr, $realcnt);
2884 for my $ctx (@ctx) {
2885 my ($clen, $cindent) = line_stats($ctx);
2886 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2887 $indent != $cindent) {
2888 $err .= "$sep$ctx\n";
2895 ERROR("SWITCH_CASE_INDENT_LEVEL",
2896 "switch and case should be at the same indent\n$hereline$err");
2900 # if/while/etc brace do not go on next line, unless defining a do while loop,
2901 # or if that brace on the next line is for something else
2902 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2903 my $pre_ctx = "$1$2";
2905 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2907 if ($line =~ /^\+\t{6,}/) {
2908 WARN("DEEP_INDENTATION",
2909 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2912 my $ctx_cnt = $realcnt - $#ctx - 1;
2913 my $ctx = join("\n", @ctx);
2915 my $ctx_ln = $linenr;
2916 my $ctx_skip = $realcnt;
2918 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2919 defined $lines[$ctx_ln - 1] &&
2920 $lines[$ctx_ln - 1] =~ /^-/)) {
2921 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2922 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2926 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2927 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2929 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2931 "that open brace { should be on the previous line\n" .
2932 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2934 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2935 $ctx =~ /\)\s*\;\s*$/ &&
2936 defined $lines[$ctx_ln - 1])
2938 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2939 if ($nindent > $indent) {
2940 WARN("TRAILING_SEMICOLON",
2941 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2942 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2947 # Check relative indent for conditionals and blocks.
2948 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2949 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2950 ctx_statement_block($linenr, $realcnt, 0)
2951 if (!defined $stat);
2952 my ($s, $c) = ($stat, $cond);
2954 substr($s, 0, length($c), '');
2956 # Make sure we remove the line prefixes as we have
2957 # none on the first line, and are going to readd them
2961 # Find out how long the conditional actually is.
2962 my @newlines = ($c =~ /\n/gs);
2963 my $cond_lines = 1 + $#newlines;
2965 # We want to check the first line inside the block
2966 # starting at the end of the conditional, so remove:
2967 # 1) any blank line termination
2968 # 2) any opening brace { on end of the line
2970 my $continuation = 0;
2972 $s =~ s/^.*\bdo\b//;
2974 if ($s =~ s/^\s*\\//) {
2977 if ($s =~ s/^\s*?\n//) {
2982 # Also ignore a loop construct at the end of a
2983 # preprocessor statement.
2984 if (($prevline =~ /^.\s*#\s*define\s/ ||
2985 $prevline =~ /\\\s*$/) && $continuation == 0) {
2991 while ($cond_ptr != $cond_lines) {
2992 $cond_ptr = $cond_lines;
2994 # If we see an #else/#elif then the code
2996 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3001 # 1) blank lines, they should be at 0,
3002 # 2) preprocessor lines, and
3004 if ($continuation ||
3006 $s =~ /^\s*#\s*?/ ||
3007 $s =~ /^\s*$Ident\s*:/) {
3008 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3009 if ($s =~ s/^.*?\n//) {
3015 my (undef, $sindent) = line_stats("+" . $s);
3016 my $stat_real = raw_line($linenr, $cond_lines);
3018 # Check if either of these lines are modified, else
3019 # this is not this patch's fault.
3020 if (!defined($stat_real) ||
3021 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3024 if (defined($stat_real) && $cond_lines > 1) {
3025 $stat_real = "[...]\n$stat_real";
3028 #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";
3030 if ($check && (($sindent % 8) != 0 ||
3031 ($sindent <= $indent && $s ne ''))) {
3032 WARN("SUSPECT_CODE_INDENT",
3033 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3037 # Track the 'values' across context and added lines.
3038 my $opline = $line; $opline =~ s/^./ /;
3039 my ($curr_values, $curr_vars) =
3040 annotate_values($opline . "\n", $prev_values);
3041 $curr_values = $prev_values . $curr_values;
3043 my $outline = $opline; $outline =~ s/\t/ /g;
3044 print "$linenr > .$outline\n";
3045 print "$linenr > $curr_values\n";
3046 print "$linenr > $curr_vars\n";
3048 $prev_values = substr($curr_values, -1);
3050 #ignore lines not being added
3051 next if ($line =~ /^[^\+]/);
3053 # TEST: allow direct testing of the type matcher.
3055 if ($line =~ /^.\s*$Declare\s*$/) {
3057 "TEST: is type\n" . $herecurr);
3058 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3059 ERROR("TEST_NOT_TYPE",
3060 "TEST: is not type ($1 is)\n". $herecurr);
3064 # TEST: allow direct testing of the attribute matcher.
3066 if ($line =~ /^.\s*$Modifier\s*$/) {
3068 "TEST: is attr\n" . $herecurr);
3069 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3070 ERROR("TEST_NOT_ATTR",
3071 "TEST: is not attr ($1 is)\n". $herecurr);
3076 # check for initialisation to aggregates open brace on the next line
3077 if ($line =~ /^.\s*{/ &&
3078 $prevline =~ /(?:^|[^=])=\s*$/) {
3079 if (ERROR("OPEN_BRACE",
3080 "that open brace { should be on the previous line\n" . $hereprev) &&
3081 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3082 fix_delete_line($fixlinenr - 1, $prevrawline);
3083 fix_delete_line($fixlinenr, $rawline);
3084 my $fixedline = $prevrawline;
3085 $fixedline =~ s/\s*=\s*$/ = {/;
3086 fix_insert_line($fixlinenr, $fixedline);
3088 $fixedline =~ s/^(.\s*){\s*/$1/;
3089 fix_insert_line($fixlinenr, $fixedline);
3094 # Checks which are anchored on the added line.
3097 # check for malformed paths in #include statements (uses RAW line)
3098 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3100 if ($path =~ m{//}) {
3101 ERROR("MALFORMED_INCLUDE",
3102 "malformed #include filename\n" . $herecurr);
3104 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3105 ERROR("UAPI_INCLUDE",
3106 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3110 # no C99 // comments
3111 if ($line =~ m{//}) {
3112 if (ERROR("C99_COMMENTS",
3113 "do not use C99 // comments\n" . $herecurr) &&
3115 my $line = $fixed[$fixlinenr];
3116 if ($line =~ /\/\/(.*)$/) {
3117 my $comment = trim($1);
3118 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3122 # Remove C99 comments.
3124 $opline =~ s@//.*@@;
3126 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3127 # the whole statement.
3128 #print "APW <$lines[$realline_next - 1]>\n";
3129 if (defined $realline_next &&
3130 exists $lines[$realline_next - 1] &&
3131 !defined $suppress_export{$realline_next} &&
3132 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3133 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3134 # Handle definitions which produce identifiers with
3137 # EXPORT_SYMBOL(something_foo);
3139 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3140 $name =~ /^${Ident}_$2/) {
3141 #print "FOO C name<$name>\n";
3142 $suppress_export{$realline_next} = 1;
3144 } elsif ($stat !~ /(?:
3146 ^.DEFINE_$Ident\(\Q$name\E\)|
3147 ^.DECLARE_$Ident\(\Q$name\E\)|
3148 ^.LIST_HEAD\(\Q$name\E\)|
3149 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3150 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3152 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3153 $suppress_export{$realline_next} = 2;
3155 $suppress_export{$realline_next} = 1;
3158 if (!defined $suppress_export{$linenr} &&
3159 $prevline =~ /^.\s*$/ &&
3160 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3161 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3162 #print "FOO B <$lines[$linenr - 1]>\n";
3163 $suppress_export{$linenr} = 2;
3165 if (defined $suppress_export{$linenr} &&
3166 $suppress_export{$linenr} == 2) {
3167 WARN("EXPORT_SYMBOL",
3168 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3171 # check for global initialisers.
3172 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3173 if (ERROR("GLOBAL_INITIALISERS",
3174 "do not initialise globals to 0 or NULL\n" .
3177 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3180 # check for static initialisers.
3181 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3182 if (ERROR("INITIALISED_STATIC",
3183 "do not initialise statics to 0 or NULL\n" .
3186 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3190 # check for misordered declarations of char/short/int/long with signed/unsigned
3191 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3193 WARN("MISORDERED_TYPE",
3194 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3197 # check for static const char * arrays.
3198 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3199 WARN("STATIC_CONST_CHAR_ARRAY",
3200 "static const char * array should probably be static const char * const\n" .
3204 # check for static char foo[] = "bar" declarations.
3205 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3206 WARN("STATIC_CONST_CHAR_ARRAY",
3207 "static char array declaration should probably be static const char\n" .
3211 # check for const <foo> const where <foo> is not a pointer or array type
3212 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3214 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3216 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3217 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3219 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3223 # check for non-global char *foo[] = {"bar", ...} declarations.
3224 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3225 WARN("STATIC_CONST_CHAR_ARRAY",
3226 "char * array declaration might be better as static const\n" .
3230 # check for function declarations without arguments like "int foo()"
3231 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3232 if (ERROR("FUNCTION_WITHOUT_ARGS",
3233 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3235 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3239 # check for uses of DEFINE_PCI_DEVICE_TABLE
3240 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3241 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3242 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3244 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3248 # check for new typedefs, only function parameters and sparse annotations
3250 if ($line =~ /\btypedef\s/ &&
3251 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3252 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3253 $line !~ /\b$typeTypedefs\b/ &&
3254 $line !~ /\b$typeOtherOSTypedefs\b/ &&
3255 $line !~ /\b__bitwise(?:__|)\b/) {
3256 WARN("NEW_TYPEDEFS",
3257 "do not add new typedefs\n" . $herecurr);
3260 # * goes on variable not on type
3262 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3264 my ($ident, $from, $to) = ($1, $2, $2);
3266 # Should start with a space.
3267 $to =~ s/^(\S)/ $1/;
3268 # Should not end with a space.
3270 # '*'s should not have spaces between.
3271 while ($to =~ s/\*\s+\*/\*\*/) {
3274 ## print "1: from<$from> to<$to> ident<$ident>\n";
3276 if (ERROR("POINTER_LOCATION",
3277 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3279 my $sub_from = $ident;
3280 my $sub_to = $ident;
3281 $sub_to =~ s/\Q$from\E/$to/;
3282 $fixed[$fixlinenr] =~
3283 s@\Q$sub_from\E@$sub_to@;
3287 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3289 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3291 # Should start with a space.
3292 $to =~ s/^(\S)/ $1/;
3293 # Should not end with a space.
3295 # '*'s should not have spaces between.
3296 while ($to =~ s/\*\s+\*/\*\*/) {
3298 # Modifiers should have spaces.
3299 $to =~ s/(\b$Modifier$)/$1 /;
3301 ## print "2: from<$from> to<$to> ident<$ident>\n";
3302 if ($from ne $to && $ident !~ /^$Modifier$/) {
3303 if (ERROR("POINTER_LOCATION",
3304 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3307 my $sub_from = $match;
3308 my $sub_to = $match;
3309 $sub_to =~ s/\Q$from\E/$to/;
3310 $fixed[$fixlinenr] =~
3311 s@\Q$sub_from\E@$sub_to@;
3316 # # no BUG() or BUG_ON()
3317 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3318 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3319 # print "$herecurr";
3323 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3324 WARN("LINUX_VERSION_CODE",
3325 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3328 # check for uses of printk_ratelimit
3329 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3330 WARN("PRINTK_RATELIMITED",
3331 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3334 # printk should use KERN_* levels. Note that follow on printk's on the
3335 # same line do not need a level, so we use the current block context
3336 # to try and find and validate the current printk. In summary the current
3337 # printk includes all preceding printk's which have no newline on the end.
3338 # we assume the first bad printk is the one to report.
3339 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3341 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3342 #print "CHECK<$lines[$ln - 1]\n";
3343 # we have a preceding printk if it ends
3344 # with "\n" ignore it, else it is to blame
3345 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3346 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3353 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3354 "printk() should include KERN_ facility level\n" . $herecurr);
3358 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3360 my $level = lc($orig);
3361 $level = "warn" if ($level eq "warning");
3362 my $level2 = $level;
3363 $level2 = "dbg" if ($level eq "debug");
3364 WARN("PREFER_PR_LEVEL",
3365 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3368 if ($line =~ /\bpr_warning\s*\(/) {
3369 if (WARN("PREFER_PR_LEVEL",
3370 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3372 $fixed[$fixlinenr] =~
3373 s/\bpr_warning\b/pr_warn/;
3377 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3379 my $level = lc($orig);
3380 $level = "warn" if ($level eq "warning");
3381 $level = "dbg" if ($level eq "debug");
3382 WARN("PREFER_DEV_LEVEL",
3383 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3386 # function brace can't be on same line, except for #defines of do while,
3387 # or if closed on same line
3388 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3389 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3390 if (ERROR("OPEN_BRACE",
3391 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3393 fix_delete_line($fixlinenr, $rawline);
3394 my $fixed_line = $rawline;
3395 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3398 fix_insert_line($fixlinenr, ltrim($line1));
3399 fix_insert_line($fixlinenr, "\+{");
3400 if ($line2 !~ /^\s*$/) {
3401 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3406 # open braces for enum, union and struct go on the same line.
3407 if ($line =~ /^.\s*{/ &&
3408 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3409 if (ERROR("OPEN_BRACE",
3410 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3411 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3412 fix_delete_line($fixlinenr - 1, $prevrawline);
3413 fix_delete_line($fixlinenr, $rawline);
3414 my $fixedline = rtrim($prevrawline) . " {";
3415 fix_insert_line($fixlinenr, $fixedline);
3416 $fixedline = $rawline;
3417 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3418 if ($fixedline !~ /^\+\s*$/) {
3419 fix_insert_line($fixlinenr, $fixedline);
3424 # missing space after union, struct or enum definition
3425 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3427 "missing space after $1 definition\n" . $herecurr) &&
3429 $fixed[$fixlinenr] =~
3430 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3434 # Function pointer declarations
3435 # check spacing between type, funcptr, and args
3436 # canonical declaration is "type (*funcptr)(args...)"
3437 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3439 my $pre_pointer_space = $2;
3440 my $post_pointer_space = $3;
3442 my $post_funcname_space = $5;
3443 my $pre_args_space = $6;
3445 # the $Declare variable will capture all spaces after the type
3446 # so check it for a missing trailing missing space but pointer return types
3447 # don't need a space so don't warn for those.
3448 my $post_declare_space = "";
3449 if ($declare =~ /(\s+)$/) {
3450 $post_declare_space = $1;
3451 $declare = rtrim($declare);
3453 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3455 "missing space after return type\n" . $herecurr);
3456 $post_declare_space = " ";
3459 # unnecessary space "type (*funcptr)(args...)"
3460 # This test is not currently implemented because these declarations are
3462 # int foo(int bar, ...)
3463 # and this is form shouldn't/doesn't generate a checkpatch warning.
3465 # elsif ($declare =~ /\s{2,}$/) {
3467 # "Multiple spaces after return type\n" . $herecurr);
3470 # unnecessary space "type ( *funcptr)(args...)"
3471 if (defined $pre_pointer_space &&
3472 $pre_pointer_space =~ /^\s/) {
3474 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3477 # unnecessary space "type (* funcptr)(args...)"
3478 if (defined $post_pointer_space &&
3479 $post_pointer_space =~ /^\s/) {
3481 "Unnecessary space before function pointer name\n" . $herecurr);
3484 # unnecessary space "type (*funcptr )(args...)"
3485 if (defined $post_funcname_space &&
3486 $post_funcname_space =~ /^\s/) {
3488 "Unnecessary space after function pointer name\n" . $herecurr);
3491 # unnecessary space "type (*funcptr) (args...)"
3492 if (defined $pre_args_space &&
3493 $pre_args_space =~ /^\s/) {
3495 "Unnecessary space before function pointer arguments\n" . $herecurr);
3498 if (show_type("SPACING") && $fix) {
3499 $fixed[$fixlinenr] =~
3500 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3504 # check for spacing round square brackets; allowed:
3505 # 1. with a type on the left -- int [] a;
3506 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3507 # 3. inside a curly brace -- = { [0...10] = 5 }
3508 while ($line =~ /(.*?\s)\[/g) {
3509 my ($where, $prefix) = ($-[1], $1);
3510 if ($prefix !~ /$Type\s+$/ &&
3511 ($where != 0 || $prefix !~ /^.\s+$/) &&
3512 $prefix !~ /[{,]\s+$/) {
3513 if (ERROR("BRACKET_SPACE",
3514 "space prohibited before open square bracket '['\n" . $herecurr) &&
3516 $fixed[$fixlinenr] =~
3517 s/^(\+.*?)\s+\[/$1\[/;
3522 # check for spaces between functions and their parentheses.
3523 while ($line =~ /($Ident)\s+\(/g) {
3525 my $ctx_before = substr($line, 0, $-[1]);
3526 my $ctx = "$ctx_before$name";
3528 # Ignore those directives where spaces _are_ permitted.
3530 if|for|while|switch|return|case|
3531 volatile|__volatile__|
3532 __attribute__|format|__extension__|
3535 # cpp #define statements have non-optional spaces, ie
3536 # if there is a space between the name and the open
3537 # parenthesis it is simply not a parameter group.
3538 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3540 # cpp #elif statement condition may start with a (
3541 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3543 # If this whole things ends with a type its most
3544 # likely a typedef for a function.
3545 } elsif ($ctx =~ /$Type$/) {
3549 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3551 $fixed[$fixlinenr] =~
3552 s/\b$name\s+\(/$name\(/;
3557 # Check operator spacing.
3558 if (!($line=~/\#\s*include/)) {
3559 my $fixed_line = "";
3563 <<=|>>=|<=|>=|==|!=|
3564 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3565 =>|->|<<|>>|<|>|=|!|~|
3566 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3569 my @elements = split(/($ops|;)/, $opline);
3571 ## print("element count: <" . $#elements . ">\n");
3572 ## foreach my $el (@elements) {
3573 ## print("el: <$el>\n");
3576 my @fix_elements = ();
3579 foreach my $el (@elements) {
3580 push(@fix_elements, substr($rawline, $off, length($el)));
3581 $off += length($el);
3586 my $blank = copy_spacing($opline);
3587 my $last_after = -1;
3589 for (my $n = 0; $n < $#elements; $n += 2) {
3591 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3593 ## print("n: <$n> good: <$good>\n");
3595 $off += length($elements[$n]);
3597 # Pick up the preceding and succeeding characters.
3598 my $ca = substr($opline, 0, $off);
3600 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3601 $cc = substr($opline, $off + length($elements[$n + 1]));
3603 my $cb = "$ca$;$cc";
3606 $a = 'V' if ($elements[$n] ne '');
3607 $a = 'W' if ($elements[$n] =~ /\s$/);
3608 $a = 'C' if ($elements[$n] =~ /$;$/);
3609 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3610 $a = 'O' if ($elements[$n] eq '');
3611 $a = 'E' if ($ca =~ /^\s*$/);
3613 my $op = $elements[$n + 1];
3616 if (defined $elements[$n + 2]) {
3617 $c = 'V' if ($elements[$n + 2] ne '');
3618 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3619 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3620 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3621 $c = 'O' if ($elements[$n + 2] eq '');
3622 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3627 my $ctx = "${a}x${c}";
3629 my $at = "(ctx:$ctx)";
3631 my $ptr = substr($blank, 0, $off) . "^";
3632 my $hereptr = "$hereline$ptr\n";
3634 # Pull out the value of this operator.
3635 my $op_type = substr($curr_values, $off + 1, 1);
3637 # Get the full operator variant.
3638 my $opv = $op . substr($curr_vars, $off, 1);
3640 # Ignore operators passed as parameters.
3641 if ($op_type ne 'V' &&
3642 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3645 # } elsif ($op =~ /^$;+$/) {
3647 # ; should have either the end of line or a space or \ after it
3648 } elsif ($op eq ';') {
3649 if ($ctx !~ /.x[WEBC]/ &&
3650 $cc !~ /^\\/ && $cc !~ /^;/) {
3651 if (ERROR("SPACING",
3652 "space required after that '$op' $at\n" . $hereptr)) {
3653 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3659 } elsif ($op eq '//') {
3661 # : when part of a bitfield
3662 } elsif ($opv eq ':B') {
3663 # skip the bitfield test for now
3667 } elsif ($op eq '->') {
3668 if ($ctx =~ /Wx.|.xW/) {
3669 if (ERROR("SPACING",
3670 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3671 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3672 if (defined $fix_elements[$n + 2]) {
3673 $fix_elements[$n + 2] =~ s/^\s+//;
3679 # , must not have a space before and must have a space on the right.
3680 } elsif ($op eq ',') {
3681 my $rtrim_before = 0;
3682 my $space_after = 0;
3683 if ($ctx =~ /Wx./) {
3684 if (ERROR("SPACING",
3685 "space prohibited before that '$op' $at\n" . $hereptr)) {
3690 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3691 if (ERROR("SPACING",
3692 "space required after that '$op' $at\n" . $hereptr)) {
3698 if ($rtrim_before || $space_after) {
3699 if ($rtrim_before) {
3700 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3702 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3709 # '*' as part of a type definition -- reported already.
3710 } elsif ($opv eq '*_') {
3711 #warn "'*' is part of type\n";
3713 # unary operators should have a space before and
3714 # none after. May be left adjacent to another
3715 # unary operator, or a cast
3716 } elsif ($op eq '!' || $op eq '~' ||
3717 $opv eq '*U' || $opv eq '-U' ||
3718 $opv eq '&U' || $opv eq '&&U') {
3719 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3720 if (ERROR("SPACING",
3721 "space required before that '$op' $at\n" . $hereptr)) {
3722 if ($n != $last_after + 2) {
3723 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3728 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3729 # A unary '*' may be const
3731 } elsif ($ctx =~ /.xW/) {
3732 if (ERROR("SPACING",
3733 "space prohibited after that '$op' $at\n" . $hereptr)) {
3734 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3735 if (defined $fix_elements[$n + 2]) {
3736 $fix_elements[$n + 2] =~ s/^\s+//;
3742 # unary ++ and unary -- are allowed no space on one side.
3743 } elsif ($op eq '++' or $op eq '--') {
3744 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3745 if (ERROR("SPACING",
3746 "space required one side of that '$op' $at\n" . $hereptr)) {
3747 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3751 if ($ctx =~ /Wx[BE]/ ||
3752 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3753 if (ERROR("SPACING",
3754 "space prohibited before that '$op' $at\n" . $hereptr)) {
3755 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3759 if ($ctx =~ /ExW/) {
3760 if (ERROR("SPACING",
3761 "space prohibited after that '$op' $at\n" . $hereptr)) {
3762 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3763 if (defined $fix_elements[$n + 2]) {
3764 $fix_elements[$n + 2] =~ s/^\s+//;
3770 # << and >> may either have or not have spaces both sides
3771 } elsif ($op eq '<<' or $op eq '>>' or
3772 $op eq '&' or $op eq '^' or $op eq '|' or
3773 $op eq '+' or $op eq '-' or
3774 $op eq '*' or $op eq '/' or
3778 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
3780 "spaces preferred around that '$op' $at\n" . $hereptr)) {
3781 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3782 $fix_elements[$n + 2] =~ s/^\s+//;
3785 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
3787 "space preferred before that '$op' $at\n" . $hereptr)) {
3788 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
3792 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3793 if (ERROR("SPACING",
3794 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3795 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3796 if (defined $fix_elements[$n + 2]) {
3797 $fix_elements[$n + 2] =~ s/^\s+//;
3803 # A colon needs no spaces before when it is
3804 # terminating a case value or a label.
3805 } elsif ($opv eq ':C' || $opv eq ':L') {
3806 if ($ctx =~ /Wx./) {
3807 if (ERROR("SPACING",
3808 "space prohibited before that '$op' $at\n" . $hereptr)) {
3809 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3814 # All the others need spaces both sides.
3815 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3818 # Ignore email addresses <foo@bar>
3820 $cc =~ /^\S+\@\S+>/) ||
3822 $ca =~ /<\S+\@\S+$/))
3827 # messages are ERROR, but ?: are CHK
3829 my $msg_type = \&ERROR;
3830 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3832 if (&{$msg_type}("SPACING",
3833 "spaces required around that '$op' $at\n" . $hereptr)) {
3834 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3835 if (defined $fix_elements[$n + 2]) {
3836 $fix_elements[$n + 2] =~ s/^\s+//;
3842 $off += length($elements[$n + 1]);
3844 ## print("n: <$n> GOOD: <$good>\n");
3846 $fixed_line = $fixed_line . $good;
3849 if (($#elements % 2) == 0) {
3850 $fixed_line = $fixed_line . $fix_elements[$#elements];
3853 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3854 $fixed[$fixlinenr] = $fixed_line;
3860 # check for whitespace before a non-naked semicolon
3861 if ($line =~ /^\+.*\S\s+;\s*$/) {
3863 "space prohibited before semicolon\n" . $herecurr) &&
3865 1 while $fixed[$fixlinenr] =~
3866 s/^(\+.*\S)\s+;/$1;/;
3870 # check for multiple assignments
3871 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3872 CHK("MULTIPLE_ASSIGNMENTS",
3873 "multiple assignments should be avoided\n" . $herecurr);
3876 ## # check for multiple declarations, allowing for a function declaration
3878 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3879 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3881 ## # Remove any bracketed sections to ensure we do not
3882 ## # falsly report the parameters of functions.
3884 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3886 ## if ($ln =~ /,/) {
3887 ## WARN("MULTIPLE_DECLARATION",
3888 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3892 #need space before brace following if, while, etc
3893 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3895 if (ERROR("SPACING",
3896 "space required before the open brace '{'\n" . $herecurr) &&
3898 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3902 ## # check for blank lines before declarations
3903 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3904 ## $prevrawline =~ /^.\s*$/) {
3906 ## "No blank lines before declarations\n" . $hereprev);
3910 # closing brace should have a space following it when it has anything
3912 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3913 if (ERROR("SPACING",
3914 "space required after that close brace '}'\n" . $herecurr) &&
3916 $fixed[$fixlinenr] =~
3917 s/}((?!(?:,|;|\)))\S)/} $1/;
3921 # check spacing on square brackets
3922 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3923 if (ERROR("SPACING",
3924 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3926 $fixed[$fixlinenr] =~
3930 if ($line =~ /\s\]/) {
3931 if (ERROR("SPACING",
3932 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3934 $fixed[$fixlinenr] =~
3939 # check spacing on parentheses
3940 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3941 $line !~ /for\s*\(\s+;/) {
3942 if (ERROR("SPACING",
3943 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3945 $fixed[$fixlinenr] =~
3949 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3950 $line !~ /for\s*\(.*;\s+\)/ &&
3951 $line !~ /:\s+\)/) {
3952 if (ERROR("SPACING",
3953 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3955 $fixed[$fixlinenr] =~
3960 # check unnecessary parentheses around addressof/dereference single $Lvals
3961 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3963 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3965 if (CHK("UNNECESSARY_PARENTHESES",
3966 "Unnecessary parentheses around $var\n" . $herecurr) &&
3968 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3972 # check for unnecessary parentheses around function pointer uses
3973 # ie: (foo->bar)(); should be foo->bar();
3974 # but not "if (foo->bar) (" to avoid some false positives
3975 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3977 if (CHK("UNNECESSARY_PARENTHESES",
3978 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3980 my $var2 = deparenthesize($var);
3982 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3986 #goto labels aren't indented, allow a single space however
3987 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3988 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3989 if (WARN("INDENTED_LABEL",
3990 "labels should not be indented\n" . $herecurr) &&
3992 $fixed[$fixlinenr] =~
3997 # return is not a function
3998 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4000 if ($^V && $^V ge 5.10.0 &&
4001 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4003 $value = deparenthesize($value);
4004 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4005 ERROR("RETURN_PARENTHESES",
4006 "return is not a function, parentheses are not required\n" . $herecurr);
4008 } elsif ($spacing !~ /\s+/) {
4010 "space required before the open parenthesis '('\n" . $herecurr);
4014 # unnecessary return in a void function
4015 # at end-of-function, with the previous line a single leading tab, then return;
4016 # and the line before that not a goto label target like "out:"
4017 if ($sline =~ /^[ \+]}\s*$/ &&
4018 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4020 $lines[$linenr - 3] =~ /^[ +]/ &&
4021 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4023 "void function return statements are not generally useful\n" . $hereprev);
4026 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4027 if ($^V && $^V ge 5.10.0 &&
4028 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4029 my $openparens = $1;
4030 my $count = $openparens =~ tr@\(@\(@;
4032 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4033 my $comp = $4; #Not $1 because of $LvalOrFunc
4034 $msg = " - maybe == should be = ?" if ($comp eq "==");
4035 WARN("UNNECESSARY_PARENTHESES",
4036 "Unnecessary parentheses$msg\n" . $herecurr);
4040 # Return of what appears to be an errno should normally be negative
4041 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4043 if ($name ne 'EOF' && $name ne 'ERROR') {
4044 WARN("USE_NEGATIVE_ERRNO",
4045 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4049 # Need a space before open parenthesis after if, while etc
4050 if ($line =~ /\b(if|while|for|switch)\(/) {
4051 if (ERROR("SPACING",
4052 "space required before the open parenthesis '('\n" . $herecurr) &&
4054 $fixed[$fixlinenr] =~
4055 s/\b(if|while|for|switch)\(/$1 \(/;
4059 # Check for illegal assignment in if conditional -- and check for trailing
4060 # statements after the conditional.
4061 if ($line =~ /do\s*(?!{)/) {
4062 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4063 ctx_statement_block($linenr, $realcnt, 0)
4064 if (!defined $stat);
4065 my ($stat_next) = ctx_statement_block($line_nr_next,
4066 $remain_next, $off_next);
4067 $stat_next =~ s/\n./\n /g;
4068 ##print "stat<$stat> stat_next<$stat_next>\n";
4070 if ($stat_next =~ /^\s*while\b/) {
4071 # If the statement carries leading newlines,
4072 # then count those as offsets.
4074 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4076 statement_rawlines($whitespace) - 1;
4078 $suppress_whiletrailers{$line_nr_next +
4082 if (!defined $suppress_whiletrailers{$linenr} &&
4083 defined($stat) && defined($cond) &&
4084 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4085 my ($s, $c) = ($stat, $cond);
4087 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4088 ERROR("ASSIGN_IN_IF",
4089 "do not use assignment in if condition\n" . $herecurr);
4092 # Find out what is on the end of the line after the
4094 substr($s, 0, length($c), '');
4096 $s =~ s/$;//g; # Remove any comments
4097 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4098 $c !~ /}\s*while\s*/)
4100 # Find out how long the conditional actually is.
4101 my @newlines = ($c =~ /\n/gs);
4102 my $cond_lines = 1 + $#newlines;
4105 $stat_real = raw_line($linenr, $cond_lines)
4106 . "\n" if ($cond_lines);
4107 if (defined($stat_real) && $cond_lines > 1) {
4108 $stat_real = "[...]\n$stat_real";
4111 ERROR("TRAILING_STATEMENTS",
4112 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4116 # Check for bitwise tests written as boolean
4128 WARN("HEXADECIMAL_BOOLEAN_TEST",
4129 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4132 # if and else should not have general statements after it
4133 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4135 $s =~ s/$;//g; # Remove any comments
4136 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4137 ERROR("TRAILING_STATEMENTS",
4138 "trailing statements should be on next line\n" . $herecurr);
4141 # if should not continue a brace
4142 if ($line =~ /}\s*if\b/) {
4143 ERROR("TRAILING_STATEMENTS",
4144 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4147 # case and default should not have general statements after them
4148 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4150 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4154 ERROR("TRAILING_STATEMENTS",
4155 "trailing statements should be on next line\n" . $herecurr);
4158 # Check for }<nl>else {, these must be at the same
4159 # indent level to be relevant to each other.
4160 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4161 $previndent == $indent) {
4162 if (ERROR("ELSE_AFTER_BRACE",
4163 "else should follow close brace '}'\n" . $hereprev) &&
4164 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4165 fix_delete_line($fixlinenr - 1, $prevrawline);
4166 fix_delete_line($fixlinenr, $rawline);
4167 my $fixedline = $prevrawline;
4168 $fixedline =~ s/}\s*$//;
4169 if ($fixedline !~ /^\+\s*$/) {
4170 fix_insert_line($fixlinenr, $fixedline);
4172 $fixedline = $rawline;
4173 $fixedline =~ s/^(.\s*)else/$1} else/;
4174 fix_insert_line($fixlinenr, $fixedline);
4178 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4179 $previndent == $indent) {
4180 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4182 # Find out what is on the end of the line after the
4184 substr($s, 0, length($c), '');
4187 if ($s =~ /^\s*;/) {
4188 if (ERROR("WHILE_AFTER_BRACE",
4189 "while should follow close brace '}'\n" . $hereprev) &&
4190 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4191 fix_delete_line($fixlinenr - 1, $prevrawline);
4192 fix_delete_line($fixlinenr, $rawline);
4193 my $fixedline = $prevrawline;
4194 my $trailing = $rawline;
4195 $trailing =~ s/^\+//;
4196 $trailing = trim($trailing);
4197 $fixedline =~ s/}\s*$/} $trailing/;
4198 fix_insert_line($fixlinenr, $fixedline);
4203 #Specific variable tests
4204 while ($line =~ m{($Constant|$Lval)}g) {
4207 #gcc binary extension
4208 if ($var =~ /^$Binary$/) {
4209 if (WARN("GCC_BINARY_CONSTANT",
4210 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4212 my $hexval = sprintf("0x%x", oct($var));
4213 $fixed[$fixlinenr] =~
4214 s/\b$var\b/$hexval/;
4219 if ($var !~ /^$Constant$/ &&
4220 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4221 #Ignore Page<foo> variants
4222 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4223 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4224 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4225 #Ignore some three character SI units explicitly, like MiB and KHz
4226 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4227 while ($var =~ m{($Ident)}g) {
4229 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4231 seed_camelcase_includes();
4232 if (!$file && !$camelcase_file_seeded) {
4233 seed_camelcase_file($realfile);
4234 $camelcase_file_seeded = 1;
4237 if (!defined $camelcase{$word}) {
4238 $camelcase{$word} = 1;
4240 "Avoid CamelCase: <$word>\n" . $herecurr);
4246 #no spaces allowed after \ in define
4247 if ($line =~ /\#\s*define.*\\\s+$/) {
4248 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4249 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4251 $fixed[$fixlinenr] =~ s/\s+$//;
4255 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4256 # itself <asm/foo.h> (uses RAW line)
4257 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4259 my $checkfile = "include/linux/$file";
4260 if (-f "$root/$checkfile" &&
4261 $realfile ne $checkfile &&
4262 $1 !~ /$allowed_asm_includes/)
4264 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4265 if ($asminclude > 0) {
4266 if ($realfile =~ m{^arch/}) {
4267 CHK("ARCH_INCLUDE_LINUX",
4268 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4270 WARN("INCLUDE_LINUX",
4271 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4277 # multi-statement macros should be enclosed in a do while loop, grab the
4278 # first statement and ensure its the whole macro if its not enclosed
4279 # in a known good container
4280 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4281 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4284 my ($off, $dstat, $dcond, $rest);
4286 my $has_flow_statement = 0;
4287 my $has_arg_concat = 0;
4288 ($dstat, $dcond, $ln, $cnt, $off) =
4289 ctx_statement_block($linenr, $realcnt, 0);
4291 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4292 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4294 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4295 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4297 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4299 $dstat =~ s/\\\n.//g;
4300 $dstat =~ s/^\s*//s;
4301 $dstat =~ s/\s*$//s;
4303 # Flatten any parentheses and braces
4304 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4305 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4306 $dstat =~ s/\[[^\[\]]*\]/1/)
4310 # Flatten any obvious string concatentation.
4311 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4312 $dstat =~ s/$Ident\s*("X*")/$1/)
4316 my $exceptions = qr{
4328 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4330 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4331 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4332 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4333 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4334 $dstat !~ /$exceptions/ &&
4335 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4336 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4337 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4338 $dstat !~ /^for\s*$Constant$/ && # for (...)
4339 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4340 $dstat !~ /^do\s*{/ && # do {...
4341 $dstat !~ /^\({/ && # ({...
4342 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4345 my $herectx = $here . "\n";
4346 my $cnt = statement_rawlines($ctx);
4348 for (my $n = 0; $n < $cnt; $n++) {
4349 $herectx .= raw_line($linenr, $n) . "\n";
4352 if ($dstat =~ /;/) {
4353 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4354 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4356 ERROR("COMPLEX_MACRO",
4357 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4361 # check for macros with flow control, but without ## concatenation
4362 # ## concatenation is commonly a macro that defines a function so ignore those
4363 if ($has_flow_statement && !$has_arg_concat) {
4364 my $herectx = $here . "\n";
4365 my $cnt = statement_rawlines($ctx);
4367 for (my $n = 0; $n < $cnt; $n++) {
4368 $herectx .= raw_line($linenr, $n) . "\n";
4370 WARN("MACRO_WITH_FLOW_CONTROL",
4371 "Macros with flow control statements should be avoided\n" . "$herectx");
4374 # check for line continuations outside of #defines, preprocessor #, and asm
4377 if ($prevline !~ /^..*\\$/ &&
4378 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4379 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4380 $line =~ /^\+.*\\$/) {
4381 WARN("LINE_CONTINUATIONS",
4382 "Avoid unnecessary line continuations\n" . $herecurr);
4386 # do {} while (0) macro tests:
4387 # single-statement macros do not need to be enclosed in do while (0) loop,
4388 # macro should not end with a semicolon
4389 if ($^V && $^V ge 5.10.0 &&
4390 $realfile !~ m@/vmlinux.lds.h$@ &&
4391 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4394 my ($off, $dstat, $dcond, $rest);
4396 ($dstat, $dcond, $ln, $cnt, $off) =
4397 ctx_statement_block($linenr, $realcnt, 0);
4400 $dstat =~ s/\\\n.//g;
4403 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4408 my $cnt = statement_rawlines($ctx);
4409 my $herectx = $here . "\n";
4411 for (my $n = 0; $n < $cnt; $n++) {
4412 $herectx .= raw_line($linenr, $n) . "\n";
4415 if (($stmts =~ tr/;/;/) == 1 &&
4416 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4417 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4418 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4420 if (defined $semis && $semis ne "") {
4421 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4422 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4424 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4426 my $cnt = statement_rawlines($ctx);
4427 my $herectx = $here . "\n";
4429 for (my $n = 0; $n < $cnt; $n++) {
4430 $herectx .= raw_line($linenr, $n) . "\n";
4433 WARN("TRAILING_SEMICOLON",
4434 "macros should not use a trailing semicolon\n" . "$herectx");
4438 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4439 # all assignments may have only one of the following with an assignment:
4442 # VMLINUX_SYMBOL(...)
4443 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4444 WARN("MISSING_VMLINUX_SYMBOL",
4445 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4448 # check for redundant bracing round if etc
4449 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4450 my ($level, $endln, @chunks) =
4451 ctx_statement_full($linenr, $realcnt, 1);
4452 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4453 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4454 if ($#chunks > 0 && $level == 0) {
4458 my $herectx = $here . "\n";
4459 my $ln = $linenr - 1;
4460 for my $chunk (@chunks) {
4461 my ($cond, $block) = @{$chunk};
4463 # If the condition carries leading newlines, then count those as offsets.
4464 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4465 my $offset = statement_rawlines($whitespace) - 1;
4467 $allowed[$allow] = 0;
4468 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4470 # We have looked at and allowed this specific line.
4471 $suppress_ifbraces{$ln + $offset} = 1;
4473 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4474 $ln += statement_rawlines($block) - 1;
4476 substr($block, 0, length($cond), '');
4478 $seen++ if ($block =~ /^\s*{/);
4480 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4481 if (statement_lines($cond) > 1) {
4482 #print "APW: ALLOWED: cond<$cond>\n";
4483 $allowed[$allow] = 1;
4485 if ($block =~/\b(?:if|for|while)\b/) {
4486 #print "APW: ALLOWED: block<$block>\n";
4487 $allowed[$allow] = 1;
4489 if (statement_block_size($block) > 1) {
4490 #print "APW: ALLOWED: lines block<$block>\n";
4491 $allowed[$allow] = 1;
4496 my $sum_allowed = 0;
4497 foreach (@allowed) {
4500 if ($sum_allowed == 0) {
4502 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4503 } elsif ($sum_allowed != $allow &&
4506 "braces {} should be used on all arms of this statement\n" . $herectx);
4511 if (!defined $suppress_ifbraces{$linenr - 1} &&
4512 $line =~ /\b(if|while|for|else)\b/) {
4515 # Check the pre-context.
4516 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4517 #print "APW: ALLOWED: pre<$1>\n";
4521 my ($level, $endln, @chunks) =
4522 ctx_statement_full($linenr, $realcnt, $-[0]);
4524 # Check the condition.
4525 my ($cond, $block) = @{$chunks[0]};
4526 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4527 if (defined $cond) {
4528 substr($block, 0, length($cond), '');
4530 if (statement_lines($cond) > 1) {
4531 #print "APW: ALLOWED: cond<$cond>\n";
4534 if ($block =~/\b(?:if|for|while)\b/) {
4535 #print "APW: ALLOWED: block<$block>\n";
4538 if (statement_block_size($block) > 1) {
4539 #print "APW: ALLOWED: lines block<$block>\n";
4542 # Check the post-context.
4543 if (defined $chunks[1]) {
4544 my ($cond, $block) = @{$chunks[1]};
4545 if (defined $cond) {
4546 substr($block, 0, length($cond), '');
4548 if ($block =~ /^\s*\{/) {
4549 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4553 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4554 my $herectx = $here . "\n";
4555 my $cnt = statement_rawlines($block);
4557 for (my $n = 0; $n < $cnt; $n++) {
4558 $herectx .= raw_line($linenr, $n) . "\n";
4562 "braces {} are not necessary for single statement blocks\n" . $herectx);
4566 # check for unnecessary blank lines around braces
4567 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4569 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4570 $fix && $prevrawline =~ /^\+/) {
4571 fix_delete_line($fixlinenr - 1, $prevrawline);
4574 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4576 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4578 fix_delete_line($fixlinenr, $rawline);
4582 # no volatiles please
4583 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4584 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4586 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4589 # Check for user-visible strings broken across lines, which breaks the ability
4590 # to grep for the string. Make exceptions when the previous string ends in a
4591 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4592 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4593 if ($line =~ /^\+\s*"[X\t]*"/ &&
4594 $prevline =~ /"\s*$/ &&
4595 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4596 if (WARN("SPLIT_STRING",
4597 "quoted string split across lines\n" . $hereprev) &&
4599 $prevrawline =~ /^\+.*"\s*$/ &&
4600 $last_coalesced_string_linenr != $linenr - 1) {
4601 my $extracted_string = get_quoted_string($line, $rawline);
4602 my $comma_close = "";
4603 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4607 fix_delete_line($fixlinenr - 1, $prevrawline);
4608 fix_delete_line($fixlinenr, $rawline);
4609 my $fixedline = $prevrawline;
4610 $fixedline =~ s/"\s*$//;
4611 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4612 fix_insert_line($fixlinenr - 1, $fixedline);
4613 $fixedline = $rawline;
4614 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4615 if ($fixedline !~ /\+\s*$/) {
4616 fix_insert_line($fixlinenr, $fixedline);
4618 $last_coalesced_string_linenr = $linenr;
4622 # check for missing a space in a string concatenation
4623 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4624 WARN('MISSING_SPACE',
4625 "break quoted strings at a space character\n" . $hereprev);
4628 # check for spaces before a quoted newline
4629 if ($rawline =~ /^.*\".*\s\\n/) {
4630 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4631 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4633 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4638 # concatenated string without spaces between elements
4639 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4640 CHK("CONCATENATED_STRING",
4641 "Concatenated strings should use spaces between elements\n" . $herecurr);
4644 # uncoalesced string fragments
4645 if ($line =~ /"X*"\s*"/) {
4646 WARN("STRING_FRAGMENTS",
4647 "Consecutive strings are generally better as a single string\n" . $herecurr);
4650 # check for %L{u,d,i} in strings
4652 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4653 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4654 $string =~ s/%%/__/g;
4655 if ($string =~ /(?<!%)%L[udi]/) {
4657 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4662 # check for line continuations in quoted strings with odd counts of "
4663 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4664 WARN("LINE_CONTINUATIONS",
4665 "Avoid line continuations in quoted strings\n" . $herecurr);
4669 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4670 CHK("REDUNDANT_CODE",
4671 "if this code is redundant consider removing it\n" .
4675 # check for needless "if (<foo>) fn(<foo>)" uses
4676 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4677 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4678 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4680 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4684 # check for unnecessary "Out of Memory" messages
4685 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4686 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4687 (defined $1 || defined $3) &&
4690 my $testline = $lines[$linenr - 3];
4692 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4693 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4695 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4697 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4701 # check for logging functions with KERN_<LEVEL>
4702 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4703 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4705 if (WARN("UNNECESSARY_KERN_LEVEL",
4706 "Possible unnecessary $level\n" . $herecurr) &&
4708 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4712 # check for mask then right shift without a parentheses
4713 if ($^V && $^V ge 5.10.0 &&
4714 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4715 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4716 WARN("MASK_THEN_SHIFT",
4717 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4720 # check for pointer comparisons to NULL
4721 if ($^V && $^V ge 5.10.0) {
4722 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4725 $equal = "" if ($4 eq "!=");
4726 if (CHK("COMPARISON_TO_NULL",
4727 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4729 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4734 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4735 if ($line =~ /(\b$InitAttribute\b)/) {
4737 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4740 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4741 ERROR("MISPLACED_INIT",
4742 "$attr should be placed after $var\n" . $herecurr)) ||
4743 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4744 WARN("MISPLACED_INIT",
4745 "$attr should be placed after $var\n" . $herecurr))) &&
4747 $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;
4752 # check for $InitAttributeData (ie: __initdata) with const
4753 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4755 $attr =~ /($InitAttributePrefix)(.*)/;
4756 my $attr_prefix = $1;
4758 if (ERROR("INIT_ATTRIBUTE",
4759 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4761 $fixed[$fixlinenr] =~
4762 s/$InitAttributeData/${attr_prefix}initconst/;
4766 # check for $InitAttributeConst (ie: __initconst) without const
4767 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4769 if (ERROR("INIT_ATTRIBUTE",
4770 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4772 my $lead = $fixed[$fixlinenr] =~
4773 /(^\+\s*(?:static\s+))/;
4775 $lead = "$lead " if ($lead !~ /^\+$/);
4776 $lead = "${lead}const ";
4777 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4781 # don't use __constant_<foo> functions outside of include/uapi/
4782 if ($realfile !~ m@^include/uapi/@ &&
4783 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4784 my $constant_func = $1;
4785 my $func = $constant_func;
4786 $func =~ s/^__constant_//;
4787 if (WARN("CONSTANT_CONVERSION",
4788 "$constant_func should be $func\n" . $herecurr) &&
4790 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4794 # prefer usleep_range over udelay
4795 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4797 # ignore udelay's < 10, however
4798 if (! ($delay < 10) ) {
4800 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4802 if ($delay > 2000) {
4804 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4808 # warn about unexpectedly long msleep's
4809 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4812 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4816 # check for comparisons of jiffies
4817 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4818 WARN("JIFFIES_COMPARISON",
4819 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4822 # check for comparisons of get_jiffies_64()
4823 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4824 WARN("JIFFIES_COMPARISON",
4825 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4828 # warn about #ifdefs in C files
4829 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4830 # print "#ifdef in C files should be avoided\n";
4831 # print "$herecurr";
4835 # warn about spacing in #ifdefs
4836 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4837 if (ERROR("SPACING",
4838 "exactly one space required after that #$1\n" . $herecurr) &&
4840 $fixed[$fixlinenr] =~
4841 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4846 # check for spinlock_t definitions without a comment.
4847 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4848 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4850 if (!ctx_has_comment($first_line, $linenr)) {
4851 CHK("UNCOMMENTED_DEFINITION",
4852 "$1 definition without comment\n" . $herecurr);
4855 # check for memory barriers without a comment.
4856 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4857 if (!ctx_has_comment($first_line, $linenr)) {
4858 WARN("MEMORY_BARRIER",
4859 "memory barrier without comment\n" . $herecurr);
4862 # check of hardware specific defines
4863 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4865 "architecture specific defines should be avoided\n" . $herecurr);
4868 # Check that the storage class is at the beginning of a declaration
4869 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4870 WARN("STORAGE_CLASS",
4871 "storage class should be at the beginning of the declaration\n" . $herecurr)
4874 # check the location of the inline attribute, that it is between
4875 # storage class and type.
4876 if ($line =~ /\b$Type\s+$Inline\b/ ||
4877 $line =~ /\b$Inline\s+$Storage\b/) {
4878 ERROR("INLINE_LOCATION",
4879 "inline keyword should sit between storage class and type\n" . $herecurr);
4882 # Check for __inline__ and __inline, prefer inline
4883 if ($realfile !~ m@\binclude/uapi/@ &&
4884 $line =~ /\b(__inline__|__inline)\b/) {
4886 "plain inline is preferred over $1\n" . $herecurr) &&
4888 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4893 # Check for __attribute__ packed, prefer __packed
4894 if ($realfile !~ m@\binclude/uapi/@ &&
4895 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4896 WARN("PREFER_PACKED",
4897 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4900 # Check for __attribute__ aligned, prefer __aligned
4901 if ($realfile !~ m@\binclude/uapi/@ &&
4902 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4903 WARN("PREFER_ALIGNED",
4904 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4907 # Check for __attribute__ format(printf, prefer __printf
4908 if ($realfile !~ m@\binclude/uapi/@ &&
4909 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4910 if (WARN("PREFER_PRINTF",
4911 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4913 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4918 # Check for __attribute__ format(scanf, prefer __scanf
4919 if ($realfile !~ m@\binclude/uapi/@ &&
4920 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4921 if (WARN("PREFER_SCANF",
4922 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4924 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4928 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4929 if ($^V && $^V ge 5.10.0 &&
4930 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4931 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4932 $line =~ /\b__weak\b/)) {
4933 ERROR("WEAK_DECLARATION",
4934 "Using weak declarations can have unintended link defects\n" . $herecurr);
4937 # check for sizeof(&)
4938 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4939 WARN("SIZEOF_ADDRESS",
4940 "sizeof(& should be avoided\n" . $herecurr);
4943 # check for sizeof without parenthesis
4944 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4945 if (WARN("SIZEOF_PARENTHESIS",
4946 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4948 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4952 # check for struct spinlock declarations
4953 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4954 WARN("USE_SPINLOCK_T",
4955 "struct spinlock should be spinlock_t\n" . $herecurr);
4958 # check for seq_printf uses that could be seq_puts
4959 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4960 my $fmt = get_quoted_string($line, $rawline);
4963 if (WARN("PREFER_SEQ_PUTS",
4964 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4966 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4971 # Check for misused memsets
4972 if ($^V && $^V ge 5.10.0 &&
4974 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4980 if ($ms_size =~ /^(0x|)0$/i) {
4982 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4983 } elsif ($ms_size =~ /^(0x|)1$/i) {
4985 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4989 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4990 if ($^V && $^V ge 5.10.0 &&
4991 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4992 if (WARN("PREFER_ETHER_ADDR_COPY",
4993 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4995 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4999 # typecasts on min/max could be min_t/max_t
5000 if ($^V && $^V ge 5.10.0 &&
5002 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5003 if (defined $2 || defined $7) {
5005 my $cast1 = deparenthesize($2);
5007 my $cast2 = deparenthesize($7);
5011 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5012 $cast = "$cast1 or $cast2";
5013 } elsif ($cast1 ne "") {
5019 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5023 # check usleep_range arguments
5024 if ($^V && $^V ge 5.10.0 &&
5026 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5030 WARN("USLEEP_RANGE",
5031 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5032 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5034 WARN("USLEEP_RANGE",
5035 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5039 # check for naked sscanf
5040 if ($^V && $^V ge 5.10.0 &&
5042 $line =~ /\bsscanf\b/ &&
5043 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5044 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5045 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
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 WARN("NAKED_SSCANF",
5053 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5056 # check for simple sscanf that should be kstrto<foo>
5057 if ($^V && $^V ge 5.10.0 &&
5059 $line =~ /\bsscanf\b/) {
5060 my $lc = $stat =~ tr@\n@@;
5061 $lc = $lc + $linenr;
5062 my $stat_real = raw_line($linenr, 0);
5063 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5064 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5066 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5068 my $count = $format =~ tr@%@%@;
5070 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5071 WARN("SSCANF_TO_KSTRTO",
5072 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5077 # check for new externs in .h files.
5078 if ($realfile =~ /\.h$/ &&
5079 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5080 if (CHK("AVOID_EXTERNS",
5081 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5083 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5087 # check for new externs in .c files.
5088 if ($realfile =~ /\.c$/ && defined $stat &&
5089 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5091 my $function_name = $1;
5092 my $paren_space = $2;
5095 if (defined $cond) {
5096 substr($s, 0, length($cond), '');
5098 if ($s =~ /^\s*;/ &&
5099 $function_name ne 'uninitialized_var')
5101 WARN("AVOID_EXTERNS",
5102 "externs should be avoided in .c files\n" . $herecurr);
5105 if ($paren_space =~ /\n/) {
5106 WARN("FUNCTION_ARGUMENTS",
5107 "arguments for function declarations should follow identifier\n" . $herecurr);
5110 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5111 $stat =~ /^.\s*extern\s+/)
5113 WARN("AVOID_EXTERNS",
5114 "externs should be avoided in .c files\n" . $herecurr);
5117 # checks for new __setup's
5118 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5121 if (!grep(/$name/, @setup_docs)) {
5122 CHK("UNDOCUMENTED_SETUP",
5123 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5127 # check for pointless casting of kmalloc return
5128 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5129 WARN("UNNECESSARY_CASTS",
5130 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5134 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5135 if ($^V && $^V ge 5.10.0 &&
5136 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5137 CHK("ALLOC_SIZEOF_STRUCT",
5138 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5141 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5142 if ($^V && $^V ge 5.10.0 &&
5143 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5147 my $newfunc = "kmalloc_array";
5148 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5151 if ($a1 =~ /^sizeof\s*\S/) {
5155 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5156 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5157 if (WARN("ALLOC_WITH_MULTIPLY",
5158 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5160 $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;
5166 # check for krealloc arg reuse
5167 if ($^V && $^V ge 5.10.0 &&
5168 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5169 WARN("KREALLOC_ARG_REUSE",
5170 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5173 # check for alloc argument mismatch
5174 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5175 WARN("ALLOC_ARRAY_ARGS",
5176 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5179 # check for multiple semicolons
5180 if ($line =~ /;\s*;\s*$/) {
5181 if (WARN("ONE_SEMICOLON",
5182 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5184 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5188 # check for #defines like: 1 << <digit> that could be BIT(digit)
5189 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5191 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5192 if (CHK("BIT_MACRO",
5193 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5195 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5199 # check for case / default statements not preceded by break/fallthrough/switch
5200 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5202 my $has_statement = 0;
5204 my $prevline = $linenr;
5205 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5207 my $rline = $rawlines[$prevline - 1];
5208 my $fline = $lines[$prevline - 1];
5209 last if ($fline =~ /^\@\@/);
5210 next if ($fline =~ /^\-/);
5211 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5212 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5213 next if ($fline =~ /^.[\s$;]*$/);
5216 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5218 if (!$has_break && $has_statement) {
5219 WARN("MISSING_BREAK",
5220 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5224 # check for switch/default statements without a break;
5225 if ($^V && $^V ge 5.10.0 &&
5227 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5229 my $herectx = $here . "\n";
5230 my $cnt = statement_rawlines($stat);
5231 for (my $n = 0; $n < $cnt; $n++) {
5232 $herectx .= raw_line($linenr, $n) . "\n";
5234 WARN("DEFAULT_NO_BREAK",
5235 "switch default: should use break\n" . $herectx);
5238 # check for gcc specific __FUNCTION__
5239 if ($line =~ /\b__FUNCTION__\b/) {
5240 if (WARN("USE_FUNC",
5241 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5243 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5247 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5248 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5250 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5253 # check for use of yield()
5254 if ($line =~ /\byield\s*\(\s*\)/) {
5256 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5259 # check for comparisons against true and false
5260 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5268 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5270 my $type = lc($otype);
5271 if ($type =~ /^(?:true|false)$/) {
5272 if (("$test" eq "==" && "$type" eq "true") ||
5273 ("$test" eq "!=" && "$type" eq "false")) {
5277 CHK("BOOL_COMPARISON",
5278 "Using comparison to $otype is error prone\n" . $herecurr);
5280 ## maybe suggesting a correct construct would better
5281 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5286 # check for semaphores initialized locked
5287 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5288 WARN("CONSIDER_COMPLETION",
5289 "consider using a completion\n" . $herecurr);
5292 # recommend kstrto* over simple_strto* and strict_strto*
5293 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5294 WARN("CONSIDER_KSTRTO",
5295 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5298 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5299 if ($line =~ /^.\s*__initcall\s*\(/) {
5300 WARN("USE_DEVICE_INITCALL",
5301 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5304 # check for various structs that are normally const (ops, kgdb, device_tree)
5305 my $const_structs = qr{
5307 address_space_operations|
5309 block_device_operations|
5314 file_lock_operations|
5324 lock_manager_operations|
5331 pipe_buf_operations|
5332 platform_hibernation_ops|
5333 platform_suspend_ops|
5338 soc_pcmcia_socket_ops|
5344 if ($line !~ /\bconst\b/ &&
5345 $line =~ /\bstruct\s+($const_structs)\b/) {
5346 WARN("CONST_STRUCT",
5347 "struct $1 should normally be const\n" .
5351 # use of NR_CPUS is usually wrong
5352 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5353 if ($line =~ /\bNR_CPUS\b/ &&
5354 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5355 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5356 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5357 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5358 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5361 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5364 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5365 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5366 ERROR("DEFINE_ARCH_HAS",
5367 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5370 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5371 if ($^V && $^V ge 5.10.0 &&
5372 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5373 WARN("LIKELY_MISUSE",
5374 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5377 # whine mightly about in_atomic
5378 if ($line =~ /\bin_atomic\s*\(/) {
5379 if ($realfile =~ m@^drivers/@) {
5381 "do not use in_atomic in drivers\n" . $herecurr);
5382 } elsif ($realfile !~ m@^kernel/@) {
5384 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5388 # check for lockdep_set_novalidate_class
5389 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5390 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5391 if ($realfile !~ m@^kernel/lockdep@ &&
5392 $realfile !~ m@^include/linux/lockdep@ &&
5393 $realfile !~ m@^drivers/base/core@) {
5395 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5399 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
5400 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
5401 WARN("EXPORTED_WORLD_WRITABLE",
5402 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5405 # Mode permission misuses where it seems decimal should be octal
5406 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5407 if ($^V && $^V ge 5.10.0 &&
5408 $line =~ /$mode_perms_search/) {
5409 foreach my $entry (@mode_permission_funcs) {
5410 my $func = $entry->[0];
5411 my $arg_pos = $entry->[1];
5416 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5418 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5419 if ($line =~ /$test/) {
5421 $val = $6 if ($skip_args ne "");
5423 if ($val !~ /^0$/ &&
5424 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5425 length($val) ne 4)) {
5426 ERROR("NON_OCTAL_PERMISSIONS",
5427 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5428 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5429 ERROR("EXPORTED_WORLD_WRITABLE",
5430 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5437 # If we have no input at all, then there is nothing to report on
5438 # so just keep quiet.
5439 if ($#rawlines == -1) {
5443 # In mailback mode only produce a report in the negative, for
5444 # things that appear to be patches.
5445 if ($mailback && ($clean == 1 || !$is_patch)) {
5449 # This is not a patch, and we are are in 'no-patch' mode so
5451 if (!$chk_patch && !$is_patch) {
5456 ERROR("NOT_UNIFIED_DIFF",
5457 "Does not appear to be a unified-diff format patch\n");
5459 if ($is_patch && $chk_signoff && $signoff == 0) {
5460 ERROR("MISSING_SIGN_OFF",
5461 "Missing Signed-off-by: line(s)\n");
5464 print report_dump();
5465 if ($summary && !($clean == 1 && $quiet == 1)) {
5466 print "$filename " if ($summary_file);
5467 print "total: $cnt_error errors, $cnt_warn warnings, " .
5468 (($check)? "$cnt_chk checks, " : "") .
5469 "$cnt_lines lines checked\n";
5470 print "\n" if ($quiet == 0);
5475 if ($^V lt 5.10.0) {
5476 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5477 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5480 # If there were whitespace errors which cleanpatch can fix
5481 # then suggest that.
5482 if ($rpt_cleaners) {
5483 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5484 print " scripts/cleanfile\n\n";
5489 hash_show_words(\%use_type, "Used");
5490 hash_show_words(\%ignore_type, "Ignored");
5492 if ($clean == 0 && $fix &&
5493 ("@rawlines" ne "@fixed" ||
5494 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5495 my $newfile = $filename;
5496 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5500 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5502 open($f, '>', $newfile)
5503 or die "$P: Can't open $newfile for write\n";
5504 foreach my $fixed_line (@fixed) {
5507 if ($linecount > 3) {
5508 $fixed_line =~ s/^\+//;
5509 print $f $fixed_line . "\n";
5512 print $f $fixed_line . "\n";
5519 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5521 Do _NOT_ trust the results written to this file.
5522 Do _NOT_ submit these changes without inspecting them for correctness.
5524 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5525 No warranties, expressed or implied...
5531 if ($clean == 1 && $quiet == 0) {
5532 print "$vname has no obvious style problems and is ready for submission.\n"
5534 if ($clean == 0 && $quiet == 0) {
5536 $vname has style problems, please review.
5538 If any of these errors are false positives, please report
5539 them to the maintainer, see CHECKPATCH in MAINTAINERS.