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 $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
351 our $typeOtherOSTypedefs = qr{(?x:
352 u_(?:char|short|int|long) | # bsd
353 u(?:nchar|short|int|long) # sysv
355 our $typeKernelTypedefs = qr{(?x:
356 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
359 our $typeTypedefs = qr{(?x:
361 $typeOtherOSTypedefs\b|
362 $typeKernelTypedefs\b
365 our $logFunctions = qr{(?x:
366 printk(?:_ratelimited|_once|)|
367 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
368 WARN(?:_RATELIMIT|_ONCE|)|
371 seq_vprintf|seq_printf|seq_puts
374 our $signature_tags = qr{(?xi:
385 our @typeListMisordered = (
386 qr{char\s+(?:un)?signed},
387 qr{int\s+(?:(?:un)?signed\s+)?short\s},
388 qr{int\s+short(?:\s+(?:un)?signed)},
389 qr{short\s+int(?:\s+(?:un)?signed)},
390 qr{(?:un)?signed\s+int\s+short},
391 qr{short\s+(?:un)?signed},
392 qr{long\s+int\s+(?:un)?signed},
393 qr{int\s+long\s+(?:un)?signed},
394 qr{long\s+(?:un)?signed\s+int},
395 qr{int\s+(?:un)?signed\s+long},
396 qr{int\s+(?:un)?signed},
397 qr{int\s+long\s+long\s+(?:un)?signed},
398 qr{long\s+long\s+int\s+(?:un)?signed},
399 qr{long\s+long\s+(?:un)?signed\s+int},
400 qr{long\s+long\s+(?:un)?signed},
401 qr{long\s+(?:un)?signed},
406 qr{(?:(?:un)?signed\s+)?char},
407 qr{(?:(?:un)?signed\s+)?short\s+int},
408 qr{(?:(?:un)?signed\s+)?short},
409 qr{(?:(?:un)?signed\s+)?int},
410 qr{(?:(?:un)?signed\s+)?long\s+int},
411 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
412 qr{(?:(?:un)?signed\s+)?long\s+long},
413 qr{(?:(?:un)?signed\s+)?long},
422 qr{${Ident}_handler},
423 qr{${Ident}_handler_fn},
426 our @typeListFile = ();
427 our @typeListWithAttr = (
429 qr{struct\s+$InitAttribute\s+$Ident},
430 qr{union\s+$InitAttribute\s+$Ident},
433 our @modifierList = (
436 our @modifierListFile = ();
438 our @mode_permission_funcs = (
440 ["module_param_(?:array|named|string)", 4],
441 ["module_param_array_named", 5],
442 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
443 ["proc_create(?:_data|)", 2],
444 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
447 #Create a search pattern for all these functions to speed up a loop below
448 our $mode_perms_search = "";
449 foreach my $entry (@mode_permission_funcs) {
450 $mode_perms_search .= '|' if ($mode_perms_search ne "");
451 $mode_perms_search .= $entry->[0];
454 our $mode_perms_world_writable = qr{
462 our $allowed_asm_includes = qr{(?x:
468 # memory.h: ARM has a custom one
470 # Load common spelling mistakes and build regular expression list.
474 if (open(my $spelling, '<', $spelling_file)) {
475 while (<$spelling>) {
478 $line =~ s/\s*\n?$//g;
481 next if ($line =~ m/^\s*#/);
482 next if ($line =~ m/^\s*$/);
484 my ($suspect, $fix) = split(/\|\|/, $line);
486 $spelling_fix{$suspect} = $fix;
490 warn "No typos will be found - file '$spelling_file': $!\n";
494 if (open(my $spelling, '<', $codespellfile)) {
495 while (<$spelling>) {
498 $line =~ s/\s*\n?$//g;
501 next if ($line =~ m/^\s*#/);
502 next if ($line =~ m/^\s*$/);
503 next if ($line =~ m/, disabled/i);
507 my ($suspect, $fix) = split(/->/, $line);
509 $spelling_fix{$suspect} = $fix;
513 warn "No codespell typos will be found - file '$codespellfile': $!\n";
517 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
520 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
521 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
522 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
523 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
524 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
530 (?:$Modifier\s+|const\s+)*
532 (?:typeof|__typeof__)\s*\([^\)]*\)|
536 (?:\s+$Modifier|\s+const)*
538 $NonptrTypeMisordered = qr{
539 (?:$Modifier\s+|const\s+)*
543 (?:\s+$Modifier|\s+const)*
545 $NonptrTypeWithAttr = qr{
546 (?:$Modifier\s+|const\s+)*
548 (?:typeof|__typeof__)\s*\([^\)]*\)|
552 (?:\s+$Modifier|\s+const)*
556 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
557 (?:\s+$Inline|\s+$Modifier)*
559 $TypeMisordered = qr{
560 $NonptrTypeMisordered
561 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
562 (?:\s+$Inline|\s+$Modifier)*
564 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
565 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
569 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
571 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
572 # requires at least perl version v5.10.0
573 # Any use must be runtime checked with $^V
575 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
576 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
577 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
579 our $declaration_macros = qr{(?x:
580 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
581 (?:$Storage\s+)?LIST_HEAD\s*\(|
582 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
587 return "" if (!defined($string));
589 while ($string =~ /^\s*\(.*\)\s*$/) {
590 $string =~ s@^\s*\(\s*@@;
591 $string =~ s@\s*\)\s*$@@;
594 $string =~ s@\s+@ @g;
599 sub seed_camelcase_file {
602 return if (!(-f $file));
606 open(my $include_file, '<', "$file")
607 or warn "$P: Can't read '$file' $!\n";
608 my $text = <$include_file>;
609 close($include_file);
611 my @lines = split('\n', $text);
613 foreach my $line (@lines) {
614 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
615 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
617 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
619 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
625 my $camelcase_seeded = 0;
626 sub seed_camelcase_includes {
627 return if ($camelcase_seeded);
630 my $camelcase_cache = "";
631 my @include_files = ();
633 $camelcase_seeded = 1;
636 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
637 chomp $git_last_include_commit;
638 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
640 my $last_mod_date = 0;
641 $files = `find $root/include -name "*.h"`;
642 @include_files = split('\n', $files);
643 foreach my $file (@include_files) {
644 my $date = POSIX::strftime("%Y%m%d%H%M",
645 localtime((stat $file)[9]));
646 $last_mod_date = $date if ($last_mod_date < $date);
648 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
651 if ($camelcase_cache ne "" && -f $camelcase_cache) {
652 open(my $camelcase_file, '<', "$camelcase_cache")
653 or warn "$P: Can't read '$camelcase_cache' $!\n";
654 while (<$camelcase_file>) {
658 close($camelcase_file);
664 $files = `git ls-files "include/*.h"`;
665 @include_files = split('\n', $files);
668 foreach my $file (@include_files) {
669 seed_camelcase_file($file);
672 if ($camelcase_cache ne "") {
673 unlink glob ".checkpatch-camelcase.*";
674 open(my $camelcase_file, '>', "$camelcase_cache")
675 or warn "$P: Can't write '$camelcase_cache' $!\n";
676 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
677 print $camelcase_file ("$_\n");
679 close($camelcase_file);
683 sub git_commit_info {
684 my ($commit, $id, $desc) = @_;
686 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
688 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
689 $output =~ s/^\s*//gm;
690 my @lines = split("\n", $output);
692 return ($id, $desc) if ($#lines < 0);
694 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
695 # Maybe one day convert this block of bash into something that returns
696 # all matching commit ids, but it's very slow...
698 # echo "checking commits $1..."
699 # git rev-list --remotes | grep -i "^$1" |
700 # while read line ; do
701 # git log --format='%H %s' -1 $line |
702 # echo "commit $(cut -c 1-12,41-)"
704 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
706 $id = substr($lines[0], 0, 12);
707 $desc = substr($lines[0], 41);
713 $chk_signoff = 0 if ($file);
718 my @fixed_inserted = ();
719 my @fixed_deleted = ();
723 for my $filename (@ARGV) {
726 open($FILE, '-|', "diff -u /dev/null $filename") ||
727 die "$P: $filename: diff failed - $!\n";
728 } elsif ($filename eq '-') {
729 open($FILE, '<&STDIN');
731 open($FILE, '<', "$filename") ||
732 die "$P: $filename: open failed - $!\n";
734 if ($filename eq '-') {
735 $vname = 'Your patch';
744 if (!process($filename)) {
750 @fixed_inserted = ();
753 @modifierListFile = ();
760 sub top_of_kernel_tree {
764 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
765 "README", "Documentation", "arch", "include", "drivers",
766 "fs", "init", "ipc", "kernel", "lib", "scripts",
769 foreach my $check (@tree_check) {
770 if (! -e $root . '/' . $check) {
778 my ($formatted_email) = @_;
784 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
787 $comment = $3 if defined $3;
788 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
790 $comment = $2 if defined $2;
791 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
793 $comment = $2 if defined $2;
794 $formatted_email =~ s/$address.*$//;
795 $name = $formatted_email;
797 $name =~ s/^\"|\"$//g;
798 # If there's a name left after stripping spaces and
799 # leading quotes, and the address doesn't have both
800 # leading and trailing angle brackets, the address
802 # "joe smith joe@smith.com" bad
803 # "joe smith <joe@smith.com" bad
804 if ($name ne "" && $address !~ /^<[^>]+>$/) {
812 $name =~ s/^\"|\"$//g;
813 $address = trim($address);
814 $address =~ s/^\<|\>$//g;
816 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
817 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
821 return ($name, $address, $comment);
825 my ($name, $address) = @_;
830 $name =~ s/^\"|\"$//g;
831 $address = trim($address);
833 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
834 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
839 $formatted_email = "$address";
841 $formatted_email = "$name <$address>";
844 return $formatted_email;
850 foreach my $path (split(/:/, $ENV{PATH})) {
851 if (-e "$path/$bin") {
862 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
863 if (-e "$path/$conf") {
864 return "$path/$conf";
876 for my $c (split(//, $str)) {
880 for (; ($n % 8) != 0; $n++) {
892 (my $res = shift) =~ tr/\t/ /c;
899 # Drop the diff line leader and expand tabs
901 $line = expand_tabs($line);
903 # Pick the indent from the front of the line.
904 my ($white) = ($line =~ /^(\s*)/);
906 return (length($line), length($white));
909 my $sanitise_quote = '';
911 sub sanitise_line_reset {
912 my ($in_comment) = @_;
915 $sanitise_quote = '*/';
917 $sanitise_quote = '';
930 # Always copy over the diff marker.
931 $res = substr($line, 0, 1);
933 for ($off = 1; $off < length($line); $off++) {
934 $c = substr($line, $off, 1);
936 # Comments we are wacking completly including the begin
937 # and end, all to $;.
938 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
939 $sanitise_quote = '*/';
941 substr($res, $off, 2, "$;$;");
945 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
946 $sanitise_quote = '';
947 substr($res, $off, 2, "$;$;");
951 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
952 $sanitise_quote = '//';
954 substr($res, $off, 2, $sanitise_quote);
959 # A \ in a string means ignore the next character.
960 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
962 substr($res, $off, 2, 'XX');
967 if ($c eq "'" || $c eq '"') {
968 if ($sanitise_quote eq '') {
969 $sanitise_quote = $c;
971 substr($res, $off, 1, $c);
973 } elsif ($sanitise_quote eq $c) {
974 $sanitise_quote = '';
978 #print "c<$c> SQ<$sanitise_quote>\n";
979 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
980 substr($res, $off, 1, $;);
981 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
982 substr($res, $off, 1, $;);
983 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
984 substr($res, $off, 1, 'X');
986 substr($res, $off, 1, $c);
990 if ($sanitise_quote eq '//') {
991 $sanitise_quote = '';
994 # The pathname on a #include may be surrounded by '<' and '>'.
995 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
996 my $clean = 'X' x length($1);
997 $res =~ s@\<.*\>@<$clean>@;
999 # The whole of a #error is a string.
1000 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1001 my $clean = 'X' x length($1);
1002 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1008 sub get_quoted_string {
1009 my ($line, $rawline) = @_;
1011 return "" if ($line !~ m/($String)/g);
1012 return substr($rawline, $-[0], $+[0] - $-[0]);
1015 sub ctx_statement_block {
1016 my ($linenr, $remain, $off) = @_;
1017 my $line = $linenr - 1;
1020 my $coff = $off - 1;
1034 @stack = (['', 0]) if ($#stack == -1);
1036 #warn "CSB: blk<$blk> remain<$remain>\n";
1037 # If we are about to drop off the end, pull in more
1040 for (; $remain > 0; $line++) {
1041 last if (!defined $lines[$line]);
1042 next if ($lines[$line] =~ /^-/);
1045 $blk .= $lines[$line] . "\n";
1046 $len = length($blk);
1050 # Bail if there is no further context.
1051 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1055 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1061 $c = substr($blk, $off, 1);
1062 $remainder = substr($blk, $off);
1064 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1066 # Handle nested #if/#else.
1067 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1068 push(@stack, [ $type, $level ]);
1069 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1070 ($type, $level) = @{$stack[$#stack - 1]};
1071 } elsif ($remainder =~ /^#\s*endif\b/) {
1072 ($type, $level) = @{pop(@stack)};
1075 # Statement ends at the ';' or a close '}' at the
1077 if ($level == 0 && $c eq ';') {
1081 # An else is really a conditional as long as its not else if
1082 if ($level == 0 && $coff_set == 0 &&
1083 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1084 $remainder =~ /^(else)(?:\s|{)/ &&
1085 $remainder !~ /^else\s+if\b/) {
1086 $coff = $off + length($1) - 1;
1088 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1089 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1092 if (($type eq '' || $type eq '(') && $c eq '(') {
1096 if ($type eq '(' && $c eq ')') {
1098 $type = ($level != 0)? '(' : '';
1100 if ($level == 0 && $coff < $soff) {
1103 #warn "CSB: mark coff<$coff>\n";
1106 if (($type eq '' || $type eq '{') && $c eq '{') {
1110 if ($type eq '{' && $c eq '}') {
1112 $type = ($level != 0)? '{' : '';
1115 if (substr($blk, $off + 1, 1) eq ';') {
1121 # Preprocessor commands end at the newline unless escaped.
1122 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1130 # We are truly at the end, so shuffle to the next line.
1137 my $statement = substr($blk, $soff, $off - $soff + 1);
1138 my $condition = substr($blk, $soff, $coff - $soff + 1);
1140 #warn "STATEMENT<$statement>\n";
1141 #warn "CONDITION<$condition>\n";
1143 #print "coff<$coff> soff<$off> loff<$loff>\n";
1145 return ($statement, $condition,
1146 $line, $remain + 1, $off - $loff + 1, $level);
1149 sub statement_lines {
1152 # Strip the diff line prefixes and rip blank lines at start and end.
1153 $stmt =~ s/(^|\n)./$1/g;
1157 my @stmt_lines = ($stmt =~ /\n/g);
1159 return $#stmt_lines + 2;
1162 sub statement_rawlines {
1165 my @stmt_lines = ($stmt =~ /\n/g);
1167 return $#stmt_lines + 2;
1170 sub statement_block_size {
1173 $stmt =~ s/(^|\n)./$1/g;
1179 my @stmt_lines = ($stmt =~ /\n/g);
1180 my @stmt_statements = ($stmt =~ /;/g);
1182 my $stmt_lines = $#stmt_lines + 2;
1183 my $stmt_statements = $#stmt_statements + 1;
1185 if ($stmt_lines > $stmt_statements) {
1188 return $stmt_statements;
1192 sub ctx_statement_full {
1193 my ($linenr, $remain, $off) = @_;
1194 my ($statement, $condition, $level);
1198 # Grab the first conditional/block pair.
1199 ($statement, $condition, $linenr, $remain, $off, $level) =
1200 ctx_statement_block($linenr, $remain, $off);
1201 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1202 push(@chunks, [ $condition, $statement ]);
1203 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1204 return ($level, $linenr, @chunks);
1207 # Pull in the following conditional/block pairs and see if they
1208 # could continue the statement.
1210 ($statement, $condition, $linenr, $remain, $off, $level) =
1211 ctx_statement_block($linenr, $remain, $off);
1212 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1213 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1215 push(@chunks, [ $condition, $statement ]);
1218 return ($level, $linenr, @chunks);
1222 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1224 my $start = $linenr - 1;
1231 my @stack = ($level);
1232 for ($line = $start; $remain > 0; $line++) {
1233 next if ($rawlines[$line] =~ /^-/);
1236 $blk .= $rawlines[$line];
1238 # Handle nested #if/#else.
1239 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1240 push(@stack, $level);
1241 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1242 $level = $stack[$#stack - 1];
1243 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1244 $level = pop(@stack);
1247 foreach my $c (split(//, $lines[$line])) {
1248 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1254 if ($c eq $close && $level > 0) {
1256 last if ($level == 0);
1257 } elsif ($c eq $open) {
1262 if (!$outer || $level <= 1) {
1263 push(@res, $rawlines[$line]);
1266 last if ($level == 0);
1269 return ($level, @res);
1271 sub ctx_block_outer {
1272 my ($linenr, $remain) = @_;
1274 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1278 my ($linenr, $remain) = @_;
1280 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1284 my ($linenr, $remain, $off) = @_;
1286 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1289 sub ctx_block_level {
1290 my ($linenr, $remain) = @_;
1292 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1294 sub ctx_statement_level {
1295 my ($linenr, $remain, $off) = @_;
1297 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1300 sub ctx_locate_comment {
1301 my ($first_line, $end_line) = @_;
1303 # Catch a comment on the end of the line itself.
1304 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1305 return $current_comment if (defined $current_comment);
1307 # Look through the context and try and figure out if there is a
1310 $current_comment = '';
1311 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1312 my $line = $rawlines[$linenr - 1];
1314 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1317 if ($line =~ m@/\*@) {
1320 if (!$in_comment && $current_comment ne '') {
1321 $current_comment = '';
1323 $current_comment .= $line . "\n" if ($in_comment);
1324 if ($line =~ m@\*/@) {
1329 chomp($current_comment);
1330 return($current_comment);
1332 sub ctx_has_comment {
1333 my ($first_line, $end_line) = @_;
1334 my $cmt = ctx_locate_comment($first_line, $end_line);
1336 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1337 ##print "CMMT: $cmt\n";
1339 return ($cmt ne '');
1343 my ($linenr, $cnt) = @_;
1345 my $offset = $linenr - 1;
1350 $line = $rawlines[$offset++];
1351 next if (defined($line) && $line =~ /^-/);
1363 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1366 $coded = sprintf("^%c", unpack('C', $2) + 64);
1375 my $av_preprocessor = 0;
1380 sub annotate_reset {
1381 $av_preprocessor = 0;
1383 @av_paren_type = ('E');
1384 $av_pend_colon = 'O';
1387 sub annotate_values {
1388 my ($stream, $type) = @_;
1391 my $var = '_' x length($stream);
1394 print "$stream\n" if ($dbg_values > 1);
1396 while (length($cur)) {
1397 @av_paren_type = ('E') if ($#av_paren_type < 0);
1398 print " <" . join('', @av_paren_type) .
1399 "> <$type> <$av_pending>" if ($dbg_values > 1);
1400 if ($cur =~ /^(\s+)/o) {
1401 print "WS($1)\n" if ($dbg_values > 1);
1402 if ($1 =~ /\n/ && $av_preprocessor) {
1403 $type = pop(@av_paren_type);
1404 $av_preprocessor = 0;
1407 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1408 print "CAST($1)\n" if ($dbg_values > 1);
1409 push(@av_paren_type, $type);
1412 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1413 print "DECLARE($1)\n" if ($dbg_values > 1);
1416 } elsif ($cur =~ /^($Modifier)\s*/) {
1417 print "MODIFIER($1)\n" if ($dbg_values > 1);
1420 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1421 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1422 $av_preprocessor = 1;
1423 push(@av_paren_type, $type);
1429 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1430 print "UNDEF($1)\n" if ($dbg_values > 1);
1431 $av_preprocessor = 1;
1432 push(@av_paren_type, $type);
1434 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1435 print "PRE_START($1)\n" if ($dbg_values > 1);
1436 $av_preprocessor = 1;
1438 push(@av_paren_type, $type);
1439 push(@av_paren_type, $type);
1442 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1443 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1444 $av_preprocessor = 1;
1446 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1450 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1451 print "PRE_END($1)\n" if ($dbg_values > 1);
1453 $av_preprocessor = 1;
1455 # Assume all arms of the conditional end as this
1456 # one does, and continue as if the #endif was not here.
1457 pop(@av_paren_type);
1458 push(@av_paren_type, $type);
1461 } elsif ($cur =~ /^(\\\n)/o) {
1462 print "PRECONT($1)\n" if ($dbg_values > 1);
1464 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1465 print "ATTR($1)\n" if ($dbg_values > 1);
1466 $av_pending = $type;
1469 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1470 print "SIZEOF($1)\n" if ($dbg_values > 1);
1476 } elsif ($cur =~ /^(if|while|for)\b/o) {
1477 print "COND($1)\n" if ($dbg_values > 1);
1481 } elsif ($cur =~/^(case)/o) {
1482 print "CASE($1)\n" if ($dbg_values > 1);
1483 $av_pend_colon = 'C';
1486 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1487 print "KEYWORD($1)\n" if ($dbg_values > 1);
1490 } elsif ($cur =~ /^(\()/o) {
1491 print "PAREN('$1')\n" if ($dbg_values > 1);
1492 push(@av_paren_type, $av_pending);
1496 } elsif ($cur =~ /^(\))/o) {
1497 my $new_type = pop(@av_paren_type);
1498 if ($new_type ne '_') {
1500 print "PAREN('$1') -> $type\n"
1501 if ($dbg_values > 1);
1503 print "PAREN('$1')\n" if ($dbg_values > 1);
1506 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1507 print "FUNC($1)\n" if ($dbg_values > 1);
1511 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1512 if (defined $2 && $type eq 'C' || $type eq 'T') {
1513 $av_pend_colon = 'B';
1514 } elsif ($type eq 'E') {
1515 $av_pend_colon = 'L';
1517 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1520 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1521 print "IDENT($1)\n" if ($dbg_values > 1);
1524 } elsif ($cur =~ /^($Assignment)/o) {
1525 print "ASSIGN($1)\n" if ($dbg_values > 1);
1528 } elsif ($cur =~/^(;|{|})/) {
1529 print "END($1)\n" if ($dbg_values > 1);
1531 $av_pend_colon = 'O';
1533 } elsif ($cur =~/^(,)/) {
1534 print "COMMA($1)\n" if ($dbg_values > 1);
1537 } elsif ($cur =~ /^(\?)/o) {
1538 print "QUESTION($1)\n" if ($dbg_values > 1);
1541 } elsif ($cur =~ /^(:)/o) {
1542 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1544 substr($var, length($res), 1, $av_pend_colon);
1545 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1550 $av_pend_colon = 'O';
1552 } elsif ($cur =~ /^(\[)/o) {
1553 print "CLOSE($1)\n" if ($dbg_values > 1);
1556 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1559 print "OPV($1)\n" if ($dbg_values > 1);
1566 substr($var, length($res), 1, $variant);
1569 } elsif ($cur =~ /^($Operators)/o) {
1570 print "OP($1)\n" if ($dbg_values > 1);
1571 if ($1 ne '++' && $1 ne '--') {
1575 } elsif ($cur =~ /(^.)/o) {
1576 print "C($1)\n" if ($dbg_values > 1);
1579 $cur = substr($cur, length($1));
1580 $res .= $type x length($1);
1584 return ($res, $var);
1588 my ($possible, $line) = @_;
1589 my $notPermitted = qr{(?:
1606 ^(?:typedef|struct|enum)\b
1608 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1609 if ($possible !~ $notPermitted) {
1610 # Check for modifiers.
1611 $possible =~ s/\s*$Storage\s*//g;
1612 $possible =~ s/\s*$Sparse\s*//g;
1613 if ($possible =~ /^\s*$/) {
1615 } elsif ($possible =~ /\s/) {
1616 $possible =~ s/\s*$Type\s*//g;
1617 for my $modifier (split(' ', $possible)) {
1618 if ($modifier !~ $notPermitted) {
1619 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1620 push(@modifierListFile, $modifier);
1625 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1626 push(@typeListFile, $possible);
1630 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1639 return defined $use_type{$type} if (scalar keys %use_type > 0);
1641 return !defined $ignore_type{$type};
1645 my ($level, $type, $msg) = @_;
1647 if (!show_type($type) ||
1648 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1653 $line = "$prefix$level:$type: $msg\n";
1655 $line = "$prefix$level: $msg\n";
1657 $line = (split('\n', $line))[0] . "\n" if ($terse);
1659 push(our @report, $line);
1668 sub fixup_current_range {
1669 my ($lineRef, $offset, $length) = @_;
1671 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1674 my $no = $o + $offset;
1675 my $nl = $l + $length;
1676 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1680 sub fix_inserted_deleted_lines {
1681 my ($linesRef, $insertedRef, $deletedRef) = @_;
1683 my $range_last_linenr = 0;
1684 my $delta_offset = 0;
1689 my $next_insert = 0;
1690 my $next_delete = 0;
1694 my $inserted = @{$insertedRef}[$next_insert++];
1695 my $deleted = @{$deletedRef}[$next_delete++];
1697 foreach my $old_line (@{$linesRef}) {
1699 my $line = $old_line; #don't modify the array
1700 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
1702 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1703 $range_last_linenr = $new_linenr;
1704 fixup_current_range(\$line, $delta_offset, 0);
1707 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1708 $deleted = @{$deletedRef}[$next_delete++];
1710 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1713 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1714 push(@lines, ${$inserted}{'LINE'});
1715 $inserted = @{$insertedRef}[$next_insert++];
1717 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1721 push(@lines, $line);
1731 sub fix_insert_line {
1732 my ($linenr, $line) = @_;
1738 push(@fixed_inserted, $inserted);
1741 sub fix_delete_line {
1742 my ($linenr, $line) = @_;
1749 push(@fixed_deleted, $deleted);
1753 my ($type, $msg) = @_;
1755 if (report("ERROR", $type, $msg)) {
1763 my ($type, $msg) = @_;
1765 if (report("WARNING", $type, $msg)) {
1773 my ($type, $msg) = @_;
1775 if ($check && report("CHECK", $type, $msg)) {
1783 sub check_absolute_file {
1784 my ($absolute, $herecurr) = @_;
1785 my $file = $absolute;
1787 ##print "absolute<$absolute>\n";
1789 # See if any suffix of this path is a path within the tree.
1790 while ($file =~ s@^[^/]*/@@) {
1791 if (-f "$root/$file") {
1792 ##print "file<$file>\n";
1800 # It is, so see if the prefix is acceptable.
1801 my $prefix = $absolute;
1802 substr($prefix, -length($file)) = '';
1804 ##print "prefix<$prefix>\n";
1805 if ($prefix ne ".../") {
1806 WARN("USE_RELATIVE_PATH",
1807 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1814 $string =~ s/^\s+|\s+$//g;
1822 $string =~ s/^\s+//;
1830 $string =~ s/\s+$//;
1835 sub string_find_replace {
1836 my ($string, $find, $replace) = @_;
1838 $string =~ s/$find/$replace/g;
1846 my $source_indent = 8;
1847 my $max_spaces_before_tab = $source_indent - 1;
1848 my $spaces_to_tab = " " x $source_indent;
1850 #convert leading spaces to tabs
1851 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1852 #Remove spaces before a tab
1853 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1858 sub pos_last_openparen {
1863 my $opens = $line =~ tr/\(/\(/;
1864 my $closes = $line =~ tr/\)/\)/;
1866 my $last_openparen = 0;
1868 if (($opens == 0) || ($closes >= $opens)) {
1872 my $len = length($line);
1874 for ($pos = 0; $pos < $len; $pos++) {
1875 my $string = substr($line, $pos);
1876 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1877 $pos += length($1) - 1;
1878 } elsif (substr($line, $pos, 1) eq '(') {
1879 $last_openparen = $pos;
1880 } elsif (index($string, '(') == -1) {
1885 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1889 my $filename = shift;
1895 my $stashrawline="";
1906 my $in_header_lines = $file ? 0 : 1;
1907 my $in_commit_log = 0; #Scanning lines before patch
1908 my $commit_log_long_line = 0;
1909 my $reported_maintainer_file = 0;
1910 my $non_utf8_charset = 0;
1912 my $last_blank_line = 0;
1913 my $last_coalesced_string_linenr = -1;
1921 # Trace the real file/line as we go.
1927 my $comment_edge = 0;
1931 my $prev_values = 'E';
1934 my %suppress_ifbraces;
1935 my %suppress_whiletrailers;
1936 my %suppress_export;
1937 my $suppress_statement = 0;
1939 my %signatures = ();
1941 # Pre-scan the patch sanitizing the lines.
1942 # Pre-scan the patch looking for any __setup documentation.
1944 my @setup_docs = ();
1947 my $camelcase_file_seeded = 0;
1949 sanitise_line_reset();
1951 foreach my $rawline (@rawlines) {
1955 push(@fixed, $rawline) if ($fix);
1957 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1959 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1964 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1973 # Guestimate if this is a continuing comment. Run
1974 # the context looking for a comment "edge". If this
1975 # edge is a close comment then we must be in a comment
1979 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1980 next if (defined $rawlines[$ln - 1] &&
1981 $rawlines[$ln - 1] =~ /^-/);
1983 #print "RAW<$rawlines[$ln - 1]>\n";
1984 last if (!defined $rawlines[$ln - 1]);
1985 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1986 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1991 if (defined $edge && $edge eq '*/') {
1995 # Guestimate if this is a continuing comment. If this
1996 # is the start of a diff block and this line starts
1997 # ' *' then it is very likely a comment.
1998 if (!defined $edge &&
1999 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2004 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2005 sanitise_line_reset($in_comment);
2007 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2008 # Standardise the strings and chars within the input to
2009 # simplify matching -- only bother with positive lines.
2010 $line = sanitise_line($rawline);
2012 push(@lines, $line);
2015 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2020 #print "==>$rawline\n";
2021 #print "-->$line\n";
2023 if ($setup_docs && $line =~ /^\+/) {
2024 push(@setup_docs, $line);
2033 foreach my $line (@lines) {
2036 my $sline = $line; #copy of $line
2037 $sline =~ s/$;/ /g; #with comments as spaces
2039 my $rawline = $rawlines[$linenr - 1];
2041 #extract the line range in the file after the patch is applied
2042 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2044 $first_line = $linenr + 1;
2054 %suppress_ifbraces = ();
2055 %suppress_whiletrailers = ();
2056 %suppress_export = ();
2057 $suppress_statement = 0;
2060 # track the line number as we move through the hunk, note that
2061 # new versions of GNU diff omit the leading space on completely
2062 # blank context lines so we need to count that too.
2063 } elsif ($line =~ /^( |\+|$)/) {
2065 $realcnt-- if ($realcnt != 0);
2067 # Measure the line length and indent.
2068 ($length, $indent) = line_stats($rawline);
2070 # Track the previous line.
2071 ($prevline, $stashline) = ($stashline, $line);
2072 ($previndent, $stashindent) = ($stashindent, $indent);
2073 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2075 #warn "line<$line>\n";
2077 } elsif ($realcnt == 1) {
2081 my $hunk_line = ($realcnt != 0);
2083 #make up the handle for any error we report on this line
2084 $prefix = "$filename:$realline: " if ($emacs && $file);
2085 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2087 $here = "#$linenr: " if (!$file);
2088 $here = "#$realline: " if ($file);
2091 # extract the filename as it passes
2092 if ($line =~ /^diff --git.*?(\S+)$/) {
2094 $realfile =~ s@^([^/]*)/@@ if (!$file);
2097 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2099 $realfile =~ s@^([^/]*)/@@ if (!$file);
2103 if (!$file && $tree && $p1_prefix ne '' &&
2104 -e "$root/$p1_prefix") {
2105 WARN("PATCH_PREFIX",
2106 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2109 if ($realfile =~ m@^include/asm/@) {
2110 ERROR("MODIFIED_INCLUDE_ASM",
2111 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2117 if ($realfile =~ m@^(drivers/net/|net/)@) {
2120 $check = $check_orig;
2125 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2127 my $hereline = "$here\n$rawline\n";
2128 my $herecurr = "$here\n$rawline\n";
2129 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2131 $cnt_lines++ if ($realcnt != 0);
2133 # Check for incorrect file permissions
2134 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2135 my $permhere = $here . "FILE: $realfile\n";
2136 if ($realfile !~ m@scripts/@ &&
2137 $realfile !~ /\.(py|pl|awk|sh)$/) {
2138 ERROR("EXECUTE_PERMISSIONS",
2139 "do not set execute permissions for source files\n" . $permhere);
2143 # Check the patch for a signoff:
2144 if ($line =~ /^\s*signed-off-by:/i) {
2149 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2150 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2151 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2152 $reported_maintainer_file = 1;
2155 # Check signature styles
2156 if (!$in_header_lines &&
2157 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2158 my $space_before = $1;
2160 my $space_after = $3;
2162 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2164 if ($sign_off !~ /$signature_tags/) {
2165 WARN("BAD_SIGN_OFF",
2166 "Non-standard signature: $sign_off\n" . $herecurr);
2168 if (defined $space_before && $space_before ne "") {
2169 if (WARN("BAD_SIGN_OFF",
2170 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2172 $fixed[$fixlinenr] =
2173 "$ucfirst_sign_off $email";
2176 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2177 if (WARN("BAD_SIGN_OFF",
2178 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2180 $fixed[$fixlinenr] =
2181 "$ucfirst_sign_off $email";
2185 if (!defined $space_after || $space_after ne " ") {
2186 if (WARN("BAD_SIGN_OFF",
2187 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2189 $fixed[$fixlinenr] =
2190 "$ucfirst_sign_off $email";
2194 my ($email_name, $email_address, $comment) = parse_email($email);
2195 my $suggested_email = format_email(($email_name, $email_address));
2196 if ($suggested_email eq "") {
2197 ERROR("BAD_SIGN_OFF",
2198 "Unrecognized email address: '$email'\n" . $herecurr);
2200 my $dequoted = $suggested_email;
2201 $dequoted =~ s/^"//;
2202 $dequoted =~ s/" </ </;
2203 # Don't force email to have quotes
2204 # Allow just an angle bracketed address
2205 if ("$dequoted$comment" ne $email &&
2206 "<$email_address>$comment" ne $email &&
2207 "$suggested_email$comment" ne $email) {
2208 WARN("BAD_SIGN_OFF",
2209 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2213 # Check for duplicate signatures
2214 my $sig_nospace = $line;
2215 $sig_nospace =~ s/\s//g;
2216 $sig_nospace = lc($sig_nospace);
2217 if (defined $signatures{$sig_nospace}) {
2218 WARN("BAD_SIGN_OFF",
2219 "Duplicate signature\n" . $herecurr);
2221 $signatures{$sig_nospace} = 1;
2225 # Check email subject for common tools that don't need to be mentioned
2226 if ($in_header_lines &&
2227 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2228 WARN("EMAIL_SUBJECT",
2229 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2232 # Check for old stable address
2233 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2234 ERROR("STABLE_ADDRESS",
2235 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2238 # Check for unwanted Gerrit info
2239 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2240 ERROR("GERRIT_CHANGE_ID",
2241 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2244 # Check for line lengths > 75 in commit log, warn once
2245 if ($in_commit_log && !$commit_log_long_line &&
2246 length($line) > 75) {
2247 WARN("COMMIT_LOG_LONG_LINE",
2248 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2249 $commit_log_long_line = 1;
2252 # Check for git id commit length and improperly formed commit descriptions
2253 if ($in_commit_log && $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i) {
2255 my $orig_commit = lc($2);
2262 my $id = '0123456789ab';
2263 my $orig_desc = "commit description";
2264 my $description = "";
2266 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2267 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2268 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2269 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2270 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2273 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2274 defined $rawlines[$linenr] &&
2275 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2278 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2279 defined $rawlines[$linenr] &&
2280 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2281 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2283 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2284 $orig_desc .= " " . $1;
2288 ($id, $description) = git_commit_info($orig_commit,
2291 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2292 ERROR("GIT_COMMIT_ID",
2293 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2297 # Check for added, moved or deleted files
2298 if (!$reported_maintainer_file && !$in_commit_log &&
2299 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2300 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2301 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2302 (defined($1) || defined($2))))) {
2303 $reported_maintainer_file = 1;
2304 WARN("FILE_PATH_CHANGES",
2305 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2308 # Check for wrappage within a valid hunk of the file
2309 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2310 ERROR("CORRUPTED_PATCH",
2311 "patch seems to be corrupt (line wrapped?)\n" .
2312 $herecurr) if (!$emitted_corrupt++);
2315 # Check for absolute kernel paths.
2317 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2320 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2321 check_absolute_file($1, $herecurr)) {
2324 check_absolute_file($file, $herecurr);
2329 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2330 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2331 $rawline !~ m/^$UTF8*$/) {
2332 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2334 my $blank = copy_spacing($rawline);
2335 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2336 my $hereptr = "$hereline$ptr\n";
2339 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2342 # Check if it's the start of a commit log
2343 # (not a header line and we haven't seen the patch filename)
2344 if ($in_header_lines && $realfile =~ /^$/ &&
2345 !($rawline =~ /^\s+\S/ ||
2346 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2347 $in_header_lines = 0;
2351 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2352 # declined it, i.e defined some charset where it is missing.
2353 if ($in_header_lines &&
2354 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2356 $non_utf8_charset = 1;
2359 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2360 $rawline =~ /$NON_ASCII_UTF8/) {
2361 WARN("UTF8_BEFORE_PATCH",
2362 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2365 # Check for various typo / spelling mistakes
2366 if (defined($misspellings) &&
2367 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2368 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2370 my $typo_fix = $spelling_fix{lc($typo)};
2371 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2372 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2373 my $msg_type = \&WARN;
2374 $msg_type = \&CHK if ($file);
2375 if (&{$msg_type}("TYPO_SPELLING",
2376 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2378 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2383 # ignore non-hunk lines and lines being removed
2384 next if (!$hunk_line || $line =~ /^-/);
2386 #trailing whitespace
2387 if ($line =~ /^\+.*\015/) {
2388 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2389 if (ERROR("DOS_LINE_ENDINGS",
2390 "DOS line endings\n" . $herevet) &&
2392 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2394 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2395 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2396 if (ERROR("TRAILING_WHITESPACE",
2397 "trailing whitespace\n" . $herevet) &&
2399 $fixed[$fixlinenr] =~ s/\s+$//;
2405 # Check for FSF mailing addresses.
2406 if ($rawline =~ /\bwrite to the Free/i ||
2407 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2408 $rawline =~ /\b51\s+Franklin\s+St/i) {
2409 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2410 my $msg_type = \&ERROR;
2411 $msg_type = \&CHK if ($file);
2412 &{$msg_type}("FSF_MAILING_ADDRESS",
2413 "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)
2416 # check for Kconfig help text having a real description
2417 # Only applies when adding the entry originally, after that we do not have
2418 # sufficient context to determine whether it is indeed long enough.
2419 if ($realfile =~ /Kconfig/ &&
2420 $line =~ /^\+\s*config\s+/) {
2423 my $ln = $linenr + 1;
2427 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2428 $f = $lines[$ln - 1];
2429 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2430 $is_end = $lines[$ln - 1] =~ /^\+/;
2432 next if ($f =~ /^-/);
2433 last if (!$file && $f =~ /^\@\@/);
2435 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2437 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2444 next if ($f =~ /^$/);
2445 if ($f =~ /^\s*config\s/) {
2451 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2452 WARN("CONFIG_DESCRIPTION",
2453 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2455 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2458 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2459 if ($realfile =~ /Kconfig/ &&
2460 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2461 WARN("CONFIG_EXPERIMENTAL",
2462 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2465 # discourage the use of boolean for type definition attributes of Kconfig options
2466 if ($realfile =~ /Kconfig/ &&
2467 $line =~ /^\+\s*\bboolean\b/) {
2468 WARN("CONFIG_TYPE_BOOLEAN",
2469 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2472 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2473 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2476 'EXTRA_AFLAGS' => 'asflags-y',
2477 'EXTRA_CFLAGS' => 'ccflags-y',
2478 'EXTRA_CPPFLAGS' => 'cppflags-y',
2479 'EXTRA_LDFLAGS' => 'ldflags-y',
2482 WARN("DEPRECATED_VARIABLE",
2483 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2486 # check for DT compatible documentation
2487 if (defined $root &&
2488 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2489 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2491 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2493 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2494 my $vp_file = $dt_path . "vendor-prefixes.txt";
2496 foreach my $compat (@compats) {
2497 my $compat2 = $compat;
2498 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2499 my $compat3 = $compat;
2500 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2501 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2503 WARN("UNDOCUMENTED_DT_STRING",
2504 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2507 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2509 `grep -Eq "^$vendor\\b" $vp_file`;
2511 WARN("UNDOCUMENTED_DT_STRING",
2512 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2517 # check we are in a valid source file if not then ignore this hunk
2518 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2520 # line length limit (with some exclusions)
2522 # There are a few types of lines that may extend beyond $max_line_length:
2523 # logging functions like pr_info that end in a string
2524 # lines with a single string
2525 # #defines that are a single string
2527 # There are 3 different line length message types:
2528 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_linelength
2529 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
2530 # LONG_LINE all other lines longer than $max_line_length
2532 # if LONG_LINE is ignored, the other 2 types are also ignored
2535 if ($length > $max_line_length) {
2536 my $msg_type = "LONG_LINE";
2538 # Check the allowed long line types first
2540 # logging functions that end in a string that starts
2541 # before $max_line_length
2542 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2543 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2546 # lines with only strings (w/ possible termination)
2547 # #defines with only strings
2548 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2549 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
2552 # Otherwise set the alternate message types
2554 # a comment starts before $max_line_length
2555 } elsif ($line =~ /($;[\s$;]*)$/ &&
2556 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2557 $msg_type = "LONG_LINE_COMMENT"
2559 # a quoted string starts before $max_line_length
2560 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
2561 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2562 $msg_type = "LONG_LINE_STRING"
2565 if ($msg_type ne "" &&
2566 (show_type("LONG_LINE") || show_type($msg_type))) {
2568 "line over $max_line_length characters\n" . $herecurr);
2572 # check for adding lines without a newline.
2573 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2574 WARN("MISSING_EOF_NEWLINE",
2575 "adding a line without newline at end of file\n" . $herecurr);
2578 # Blackfin: use hi/lo macros
2579 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2580 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2581 my $herevet = "$here\n" . cat_vet($line) . "\n";
2583 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2585 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2586 my $herevet = "$here\n" . cat_vet($line) . "\n";
2588 "use the HI() macro, not (... >> 16)\n" . $herevet);
2592 # check we are in a valid source file C or perl if not then ignore this hunk
2593 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2595 # at the beginning of a line any tabs must come first and anything
2596 # more than 8 must use tabs.
2597 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2598 $rawline =~ /^\+\s* \s*/) {
2599 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2601 if (ERROR("CODE_INDENT",
2602 "code indent should use tabs where possible\n" . $herevet) &&
2604 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2608 # check for space before tabs.
2609 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2610 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2611 if (WARN("SPACE_BEFORE_TAB",
2612 "please, no space before tabs\n" . $herevet) &&
2614 while ($fixed[$fixlinenr] =~
2615 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2616 while ($fixed[$fixlinenr] =~
2617 s/(^\+.*) +\t/$1\t/) {}
2621 # check for && or || at the start of a line
2622 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2623 CHK("LOGICAL_CONTINUATIONS",
2624 "Logical continuations should be on the previous line\n" . $hereprev);
2627 # check multi-line statement indentation matches previous line
2628 if ($^V && $^V ge 5.10.0 &&
2629 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2630 $prevline =~ /^\+(\t*)(.*)$/;
2634 my $pos = pos_last_openparen($rest);
2636 $line =~ /^(\+| )([ \t]*)/;
2639 my $goodtabindent = $oldindent .
2642 my $goodspaceindent = $oldindent . " " x $pos;
2644 if ($newindent ne $goodtabindent &&
2645 $newindent ne $goodspaceindent) {
2647 if (CHK("PARENTHESIS_ALIGNMENT",
2648 "Alignment should match open parenthesis\n" . $hereprev) &&
2649 $fix && $line =~ /^\+/) {
2650 $fixed[$fixlinenr] =~
2651 s/^\+[ \t]*/\+$goodtabindent/;
2657 # check for space after cast like "(int) foo" or "(struct foo) bar"
2658 # avoid checking a few false positives:
2659 # "sizeof(<type>)" or "__alignof__(<type>)"
2660 # function pointer declarations like "(*foo)(int) = bar;"
2661 # structure definitions like "(struct foo) { 0 };"
2662 # multiline macros that define functions
2663 # known attributes or the __attribute__ keyword
2664 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2665 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
2667 "No space is necessary after a cast\n" . $herecurr) &&
2669 $fixed[$fixlinenr] =~
2670 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2674 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2675 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2676 $rawline =~ /^\+[ \t]*\*/ &&
2678 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2679 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2682 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2683 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2684 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2685 $rawline =~ /^\+/ && #line is new
2686 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2687 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2688 "networking block comments start with * on subsequent lines\n" . $hereprev);
2691 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2692 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2693 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2694 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2695 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2696 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2697 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2700 # check for missing blank lines after struct/union declarations
2701 # with exceptions for various attributes and macros
2702 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2704 !($line =~ /^\+\s*$/ ||
2705 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2706 $line =~ /^\+\s*MODULE_/i ||
2707 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2708 $line =~ /^\+[a-z_]*init/ ||
2709 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2710 $line =~ /^\+\s*DECLARE/ ||
2711 $line =~ /^\+\s*__setup/)) {
2712 if (CHK("LINE_SPACING",
2713 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2715 fix_insert_line($fixlinenr, "\+");
2719 # check for multiple consecutive blank lines
2720 if ($prevline =~ /^[\+ ]\s*$/ &&
2721 $line =~ /^\+\s*$/ &&
2722 $last_blank_line != ($linenr - 1)) {
2723 if (CHK("LINE_SPACING",
2724 "Please don't use multiple blank lines\n" . $hereprev) &&
2726 fix_delete_line($fixlinenr, $rawline);
2729 $last_blank_line = $linenr;
2732 # check for missing blank lines after declarations
2733 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2734 # actual declarations
2735 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2736 # function pointer declarations
2737 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2738 # foo bar; where foo is some local typedef or #define
2739 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2740 # known declaration macros
2741 $prevline =~ /^\+\s+$declaration_macros/) &&
2742 # for "else if" which can look like "$Ident $Ident"
2743 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2744 # other possible extensions of declaration lines
2745 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2746 # not starting a section or a macro "\" extended line
2747 $prevline =~ /(?:\{\s*|\\)$/) &&
2748 # looks like a declaration
2749 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2750 # function pointer declarations
2751 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2752 # foo bar; where foo is some local typedef or #define
2753 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2754 # known declaration macros
2755 $sline =~ /^\+\s+$declaration_macros/ ||
2756 # start of struct or union or enum
2757 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2758 # start or end of block or continuation of declaration
2759 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2760 # bitfield continuation
2761 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2762 # other possible extensions of declaration lines
2763 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2764 # indentation of previous and current line are the same
2765 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2766 if (WARN("LINE_SPACING",
2767 "Missing a blank line after declarations\n" . $hereprev) &&
2769 fix_insert_line($fixlinenr, "\+");
2773 # check for spaces at the beginning of a line.
2775 # 1) within comments
2776 # 2) indented preprocessor commands
2778 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2779 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2780 if (WARN("LEADING_SPACE",
2781 "please, no spaces at the start of a line\n" . $herevet) &&
2783 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2787 # check we are in a valid C source file if not then ignore this hunk
2788 next if ($realfile !~ /\.(h|c)$/);
2790 # check indentation of any line with a bare else
2791 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2792 # if the previous line is a break or return and is indented 1 tab more...
2793 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2794 my $tabs = length($1) + 1;
2795 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2796 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2797 defined $lines[$linenr] &&
2798 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2799 WARN("UNNECESSARY_ELSE",
2800 "else is not generally useful after a break or return\n" . $hereprev);
2804 # check indentation of a line with a break;
2805 # if the previous line is a goto or return and is indented the same # of tabs
2806 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2808 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2809 WARN("UNNECESSARY_BREAK",
2810 "break is not useful after a goto or return\n" . $hereprev);
2814 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2815 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2816 WARN("CONFIG_EXPERIMENTAL",
2817 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2820 # check for RCS/CVS revision markers
2821 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2823 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2826 # Blackfin: don't use __builtin_bfin_[cs]sync
2827 if ($line =~ /__builtin_bfin_csync/) {
2828 my $herevet = "$here\n" . cat_vet($line) . "\n";
2830 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2832 if ($line =~ /__builtin_bfin_ssync/) {
2833 my $herevet = "$here\n" . cat_vet($line) . "\n";
2835 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2838 # check for old HOTPLUG __dev<foo> section markings
2839 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2840 WARN("HOTPLUG_SECTION",
2841 "Using $1 is unnecessary\n" . $herecurr);
2844 # Check for potential 'bare' types
2845 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2847 #print "LINE<$line>\n";
2848 if ($linenr >= $suppress_statement &&
2849 $realcnt && $sline =~ /.\s*\S/) {
2850 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2851 ctx_statement_block($linenr, $realcnt, 0);
2852 $stat =~ s/\n./\n /g;
2853 $cond =~ s/\n./\n /g;
2855 #print "linenr<$linenr> <$stat>\n";
2856 # If this statement has no statement boundaries within
2857 # it there is no point in retrying a statement scan
2858 # until we hit end of it.
2859 my $frag = $stat; $frag =~ s/;+\s*$//;
2860 if ($frag !~ /(?:{|;)/) {
2861 #print "skip<$line_nr_next>\n";
2862 $suppress_statement = $line_nr_next;
2865 # Find the real next line.
2866 $realline_next = $line_nr_next;
2867 if (defined $realline_next &&
2868 (!defined $lines[$realline_next - 1] ||
2869 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2876 # Ignore goto labels.
2877 if ($s =~ /$Ident:\*$/s) {
2879 # Ignore functions being called
2880 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2882 } elsif ($s =~ /^.\s*else\b/s) {
2884 # declarations always start with types
2885 } 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) {
2888 possible($type, "A:" . $s);
2890 # definitions in global scope can only start with types
2891 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2892 possible($1, "B:" . $s);
2895 # any (foo ... *) is a pointer cast, and foo is a type
2896 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2897 possible($1, "C:" . $s);
2900 # Check for any sort of function declaration.
2901 # int foo(something bar, other baz);
2902 # void (*store_gdt)(x86_descr_ptr *);
2903 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2904 my ($name_len) = length($1);
2907 substr($ctx, 0, $name_len + 1, '');
2908 $ctx =~ s/\)[^\)]*$//;
2910 for my $arg (split(/\s*,\s*/, $ctx)) {
2911 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2913 possible($1, "D:" . $s);
2921 # Checks which may be anchored in the context.
2924 # Check for switch () and associated case and default
2925 # statements should be at the same indent.
2926 if ($line=~/\bswitch\s*\(.*\)/) {
2929 my @ctx = ctx_block_outer($linenr, $realcnt);
2931 for my $ctx (@ctx) {
2932 my ($clen, $cindent) = line_stats($ctx);
2933 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2934 $indent != $cindent) {
2935 $err .= "$sep$ctx\n";
2942 ERROR("SWITCH_CASE_INDENT_LEVEL",
2943 "switch and case should be at the same indent\n$hereline$err");
2947 # if/while/etc brace do not go on next line, unless defining a do while loop,
2948 # or if that brace on the next line is for something else
2949 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2950 my $pre_ctx = "$1$2";
2952 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2954 if ($line =~ /^\+\t{6,}/) {
2955 WARN("DEEP_INDENTATION",
2956 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2959 my $ctx_cnt = $realcnt - $#ctx - 1;
2960 my $ctx = join("\n", @ctx);
2962 my $ctx_ln = $linenr;
2963 my $ctx_skip = $realcnt;
2965 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2966 defined $lines[$ctx_ln - 1] &&
2967 $lines[$ctx_ln - 1] =~ /^-/)) {
2968 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2969 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2973 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2974 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2976 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2978 "that open brace { should be on the previous line\n" .
2979 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2981 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2982 $ctx =~ /\)\s*\;\s*$/ &&
2983 defined $lines[$ctx_ln - 1])
2985 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2986 if ($nindent > $indent) {
2987 WARN("TRAILING_SEMICOLON",
2988 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2989 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2994 # Check relative indent for conditionals and blocks.
2995 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2996 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2997 ctx_statement_block($linenr, $realcnt, 0)
2998 if (!defined $stat);
2999 my ($s, $c) = ($stat, $cond);
3001 substr($s, 0, length($c), '');
3003 # Make sure we remove the line prefixes as we have
3004 # none on the first line, and are going to readd them
3008 # Find out how long the conditional actually is.
3009 my @newlines = ($c =~ /\n/gs);
3010 my $cond_lines = 1 + $#newlines;
3012 # We want to check the first line inside the block
3013 # starting at the end of the conditional, so remove:
3014 # 1) any blank line termination
3015 # 2) any opening brace { on end of the line
3017 my $continuation = 0;
3019 $s =~ s/^.*\bdo\b//;
3021 if ($s =~ s/^\s*\\//) {
3024 if ($s =~ s/^\s*?\n//) {
3029 # Also ignore a loop construct at the end of a
3030 # preprocessor statement.
3031 if (($prevline =~ /^.\s*#\s*define\s/ ||
3032 $prevline =~ /\\\s*$/) && $continuation == 0) {
3038 while ($cond_ptr != $cond_lines) {
3039 $cond_ptr = $cond_lines;
3041 # If we see an #else/#elif then the code
3043 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3048 # 1) blank lines, they should be at 0,
3049 # 2) preprocessor lines, and
3051 if ($continuation ||
3053 $s =~ /^\s*#\s*?/ ||
3054 $s =~ /^\s*$Ident\s*:/) {
3055 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3056 if ($s =~ s/^.*?\n//) {
3062 my (undef, $sindent) = line_stats("+" . $s);
3063 my $stat_real = raw_line($linenr, $cond_lines);
3065 # Check if either of these lines are modified, else
3066 # this is not this patch's fault.
3067 if (!defined($stat_real) ||
3068 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3071 if (defined($stat_real) && $cond_lines > 1) {
3072 $stat_real = "[...]\n$stat_real";
3075 #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";
3077 if ($check && (($sindent % 8) != 0 ||
3078 ($sindent <= $indent && $s ne ''))) {
3079 WARN("SUSPECT_CODE_INDENT",
3080 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3084 # Track the 'values' across context and added lines.
3085 my $opline = $line; $opline =~ s/^./ /;
3086 my ($curr_values, $curr_vars) =
3087 annotate_values($opline . "\n", $prev_values);
3088 $curr_values = $prev_values . $curr_values;
3090 my $outline = $opline; $outline =~ s/\t/ /g;
3091 print "$linenr > .$outline\n";
3092 print "$linenr > $curr_values\n";
3093 print "$linenr > $curr_vars\n";
3095 $prev_values = substr($curr_values, -1);
3097 #ignore lines not being added
3098 next if ($line =~ /^[^\+]/);
3100 # TEST: allow direct testing of the type matcher.
3102 if ($line =~ /^.\s*$Declare\s*$/) {
3104 "TEST: is type\n" . $herecurr);
3105 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3106 ERROR("TEST_NOT_TYPE",
3107 "TEST: is not type ($1 is)\n". $herecurr);
3111 # TEST: allow direct testing of the attribute matcher.
3113 if ($line =~ /^.\s*$Modifier\s*$/) {
3115 "TEST: is attr\n" . $herecurr);
3116 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3117 ERROR("TEST_NOT_ATTR",
3118 "TEST: is not attr ($1 is)\n". $herecurr);
3123 # check for initialisation to aggregates open brace on the next line
3124 if ($line =~ /^.\s*{/ &&
3125 $prevline =~ /(?:^|[^=])=\s*$/) {
3126 if (ERROR("OPEN_BRACE",
3127 "that open brace { should be on the previous line\n" . $hereprev) &&
3128 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3129 fix_delete_line($fixlinenr - 1, $prevrawline);
3130 fix_delete_line($fixlinenr, $rawline);
3131 my $fixedline = $prevrawline;
3132 $fixedline =~ s/\s*=\s*$/ = {/;
3133 fix_insert_line($fixlinenr, $fixedline);
3135 $fixedline =~ s/^(.\s*){\s*/$1/;
3136 fix_insert_line($fixlinenr, $fixedline);
3141 # Checks which are anchored on the added line.
3144 # check for malformed paths in #include statements (uses RAW line)
3145 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3147 if ($path =~ m{//}) {
3148 ERROR("MALFORMED_INCLUDE",
3149 "malformed #include filename\n" . $herecurr);
3151 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3152 ERROR("UAPI_INCLUDE",
3153 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3157 # no C99 // comments
3158 if ($line =~ m{//}) {
3159 if (ERROR("C99_COMMENTS",
3160 "do not use C99 // comments\n" . $herecurr) &&
3162 my $line = $fixed[$fixlinenr];
3163 if ($line =~ /\/\/(.*)$/) {
3164 my $comment = trim($1);
3165 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3169 # Remove C99 comments.
3171 $opline =~ s@//.*@@;
3173 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3174 # the whole statement.
3175 #print "APW <$lines[$realline_next - 1]>\n";
3176 if (defined $realline_next &&
3177 exists $lines[$realline_next - 1] &&
3178 !defined $suppress_export{$realline_next} &&
3179 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3180 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3181 # Handle definitions which produce identifiers with
3184 # EXPORT_SYMBOL(something_foo);
3186 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3187 $name =~ /^${Ident}_$2/) {
3188 #print "FOO C name<$name>\n";
3189 $suppress_export{$realline_next} = 1;
3191 } elsif ($stat !~ /(?:
3193 ^.DEFINE_$Ident\(\Q$name\E\)|
3194 ^.DECLARE_$Ident\(\Q$name\E\)|
3195 ^.LIST_HEAD\(\Q$name\E\)|
3196 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3197 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3199 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3200 $suppress_export{$realline_next} = 2;
3202 $suppress_export{$realline_next} = 1;
3205 if (!defined $suppress_export{$linenr} &&
3206 $prevline =~ /^.\s*$/ &&
3207 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3208 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3209 #print "FOO B <$lines[$linenr - 1]>\n";
3210 $suppress_export{$linenr} = 2;
3212 if (defined $suppress_export{$linenr} &&
3213 $suppress_export{$linenr} == 2) {
3214 WARN("EXPORT_SYMBOL",
3215 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3218 # check for global initialisers.
3219 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*(?:0|NULL|false)\s*;/) {
3220 if (ERROR("GLOBAL_INITIALISERS",
3221 "do not initialise globals to 0 or NULL\n" .
3224 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*(0|NULL|false)\s*;/$1;/;
3227 # check for static initialisers.
3228 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3229 if (ERROR("INITIALISED_STATIC",
3230 "do not initialise statics to 0 or NULL\n" .
3233 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3237 # check for misordered declarations of char/short/int/long with signed/unsigned
3238 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3240 WARN("MISORDERED_TYPE",
3241 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3244 # check for static const char * arrays.
3245 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3246 WARN("STATIC_CONST_CHAR_ARRAY",
3247 "static const char * array should probably be static const char * const\n" .
3251 # check for static char foo[] = "bar" declarations.
3252 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3253 WARN("STATIC_CONST_CHAR_ARRAY",
3254 "static char array declaration should probably be static const char\n" .
3258 # check for const <foo> const where <foo> is not a pointer or array type
3259 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3261 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3263 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3264 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3266 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3270 # check for non-global char *foo[] = {"bar", ...} declarations.
3271 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3272 WARN("STATIC_CONST_CHAR_ARRAY",
3273 "char * array declaration might be better as static const\n" .
3277 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3278 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3280 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3282 if (WARN("ARRAY_SIZE",
3283 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3285 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3290 # check for function declarations without arguments like "int foo()"
3291 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3292 if (ERROR("FUNCTION_WITHOUT_ARGS",
3293 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3295 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3299 # check for uses of DEFINE_PCI_DEVICE_TABLE
3300 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3301 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3302 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3304 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3308 # check for new typedefs, only function parameters and sparse annotations
3310 if ($line =~ /\btypedef\s/ &&
3311 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3312 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3313 $line !~ /\b$typeTypedefs\b/ &&
3314 $line !~ /\b__bitwise(?:__|)\b/) {
3315 WARN("NEW_TYPEDEFS",
3316 "do not add new typedefs\n" . $herecurr);
3319 # * goes on variable not on type
3321 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3323 my ($ident, $from, $to) = ($1, $2, $2);
3325 # Should start with a space.
3326 $to =~ s/^(\S)/ $1/;
3327 # Should not end with a space.
3329 # '*'s should not have spaces between.
3330 while ($to =~ s/\*\s+\*/\*\*/) {
3333 ## print "1: from<$from> to<$to> ident<$ident>\n";
3335 if (ERROR("POINTER_LOCATION",
3336 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3338 my $sub_from = $ident;
3339 my $sub_to = $ident;
3340 $sub_to =~ s/\Q$from\E/$to/;
3341 $fixed[$fixlinenr] =~
3342 s@\Q$sub_from\E@$sub_to@;
3346 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3348 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3350 # Should start with a space.
3351 $to =~ s/^(\S)/ $1/;
3352 # Should not end with a space.
3354 # '*'s should not have spaces between.
3355 while ($to =~ s/\*\s+\*/\*\*/) {
3357 # Modifiers should have spaces.
3358 $to =~ s/(\b$Modifier$)/$1 /;
3360 ## print "2: from<$from> to<$to> ident<$ident>\n";
3361 if ($from ne $to && $ident !~ /^$Modifier$/) {
3362 if (ERROR("POINTER_LOCATION",
3363 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3366 my $sub_from = $match;
3367 my $sub_to = $match;
3368 $sub_to =~ s/\Q$from\E/$to/;
3369 $fixed[$fixlinenr] =~
3370 s@\Q$sub_from\E@$sub_to@;
3375 # # no BUG() or BUG_ON()
3376 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3377 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3378 # print "$herecurr";
3382 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3383 WARN("LINUX_VERSION_CODE",
3384 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3387 # check for uses of printk_ratelimit
3388 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3389 WARN("PRINTK_RATELIMITED",
3390 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3393 # printk should use KERN_* levels. Note that follow on printk's on the
3394 # same line do not need a level, so we use the current block context
3395 # to try and find and validate the current printk. In summary the current
3396 # printk includes all preceding printk's which have no newline on the end.
3397 # we assume the first bad printk is the one to report.
3398 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3400 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3401 #print "CHECK<$lines[$ln - 1]\n";
3402 # we have a preceding printk if it ends
3403 # with "\n" ignore it, else it is to blame
3404 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3405 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3412 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3413 "printk() should include KERN_ facility level\n" . $herecurr);
3417 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3419 my $level = lc($orig);
3420 $level = "warn" if ($level eq "warning");
3421 my $level2 = $level;
3422 $level2 = "dbg" if ($level eq "debug");
3423 WARN("PREFER_PR_LEVEL",
3424 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3427 if ($line =~ /\bpr_warning\s*\(/) {
3428 if (WARN("PREFER_PR_LEVEL",
3429 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3431 $fixed[$fixlinenr] =~
3432 s/\bpr_warning\b/pr_warn/;
3436 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3438 my $level = lc($orig);
3439 $level = "warn" if ($level eq "warning");
3440 $level = "dbg" if ($level eq "debug");
3441 WARN("PREFER_DEV_LEVEL",
3442 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3445 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
3446 # number of false positives, but assembly files are not checked, so at
3447 # least the arch entry code will not trigger this warning.
3448 if ($line =~ /\bENOSYS\b/) {
3450 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
3453 # function brace can't be on same line, except for #defines of do while,
3454 # or if closed on same line
3455 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3456 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3457 if (ERROR("OPEN_BRACE",
3458 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3460 fix_delete_line($fixlinenr, $rawline);
3461 my $fixed_line = $rawline;
3462 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3465 fix_insert_line($fixlinenr, ltrim($line1));
3466 fix_insert_line($fixlinenr, "\+{");
3467 if ($line2 !~ /^\s*$/) {
3468 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3473 # open braces for enum, union and struct go on the same line.
3474 if ($line =~ /^.\s*{/ &&
3475 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3476 if (ERROR("OPEN_BRACE",
3477 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3478 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3479 fix_delete_line($fixlinenr - 1, $prevrawline);
3480 fix_delete_line($fixlinenr, $rawline);
3481 my $fixedline = rtrim($prevrawline) . " {";
3482 fix_insert_line($fixlinenr, $fixedline);
3483 $fixedline = $rawline;
3484 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3485 if ($fixedline !~ /^\+\s*$/) {
3486 fix_insert_line($fixlinenr, $fixedline);
3491 # missing space after union, struct or enum definition
3492 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3494 "missing space after $1 definition\n" . $herecurr) &&
3496 $fixed[$fixlinenr] =~
3497 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3501 # Function pointer declarations
3502 # check spacing between type, funcptr, and args
3503 # canonical declaration is "type (*funcptr)(args...)"
3504 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3506 my $pre_pointer_space = $2;
3507 my $post_pointer_space = $3;
3509 my $post_funcname_space = $5;
3510 my $pre_args_space = $6;
3512 # the $Declare variable will capture all spaces after the type
3513 # so check it for a missing trailing missing space but pointer return types
3514 # don't need a space so don't warn for those.
3515 my $post_declare_space = "";
3516 if ($declare =~ /(\s+)$/) {
3517 $post_declare_space = $1;
3518 $declare = rtrim($declare);
3520 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3522 "missing space after return type\n" . $herecurr);
3523 $post_declare_space = " ";
3526 # unnecessary space "type (*funcptr)(args...)"
3527 # This test is not currently implemented because these declarations are
3529 # int foo(int bar, ...)
3530 # and this is form shouldn't/doesn't generate a checkpatch warning.
3532 # elsif ($declare =~ /\s{2,}$/) {
3534 # "Multiple spaces after return type\n" . $herecurr);
3537 # unnecessary space "type ( *funcptr)(args...)"
3538 if (defined $pre_pointer_space &&
3539 $pre_pointer_space =~ /^\s/) {
3541 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3544 # unnecessary space "type (* funcptr)(args...)"
3545 if (defined $post_pointer_space &&
3546 $post_pointer_space =~ /^\s/) {
3548 "Unnecessary space before function pointer name\n" . $herecurr);
3551 # unnecessary space "type (*funcptr )(args...)"
3552 if (defined $post_funcname_space &&
3553 $post_funcname_space =~ /^\s/) {
3555 "Unnecessary space after function pointer name\n" . $herecurr);
3558 # unnecessary space "type (*funcptr) (args...)"
3559 if (defined $pre_args_space &&
3560 $pre_args_space =~ /^\s/) {
3562 "Unnecessary space before function pointer arguments\n" . $herecurr);
3565 if (show_type("SPACING") && $fix) {
3566 $fixed[$fixlinenr] =~
3567 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3571 # check for spacing round square brackets; allowed:
3572 # 1. with a type on the left -- int [] a;
3573 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3574 # 3. inside a curly brace -- = { [0...10] = 5 }
3575 while ($line =~ /(.*?\s)\[/g) {
3576 my ($where, $prefix) = ($-[1], $1);
3577 if ($prefix !~ /$Type\s+$/ &&
3578 ($where != 0 || $prefix !~ /^.\s+$/) &&
3579 $prefix !~ /[{,]\s+$/) {
3580 if (ERROR("BRACKET_SPACE",
3581 "space prohibited before open square bracket '['\n" . $herecurr) &&
3583 $fixed[$fixlinenr] =~
3584 s/^(\+.*?)\s+\[/$1\[/;
3589 # check for spaces between functions and their parentheses.
3590 while ($line =~ /($Ident)\s+\(/g) {
3592 my $ctx_before = substr($line, 0, $-[1]);
3593 my $ctx = "$ctx_before$name";
3595 # Ignore those directives where spaces _are_ permitted.
3597 if|for|while|switch|return|case|
3598 volatile|__volatile__|
3599 __attribute__|format|__extension__|
3602 # cpp #define statements have non-optional spaces, ie
3603 # if there is a space between the name and the open
3604 # parenthesis it is simply not a parameter group.
3605 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3607 # cpp #elif statement condition may start with a (
3608 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3610 # If this whole things ends with a type its most
3611 # likely a typedef for a function.
3612 } elsif ($ctx =~ /$Type$/) {
3616 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3618 $fixed[$fixlinenr] =~
3619 s/\b$name\s+\(/$name\(/;
3624 # Check operator spacing.
3625 if (!($line=~/\#\s*include/)) {
3626 my $fixed_line = "";
3630 <<=|>>=|<=|>=|==|!=|
3631 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3632 =>|->|<<|>>|<|>|=|!|~|
3633 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3636 my @elements = split(/($ops|;)/, $opline);
3638 ## print("element count: <" . $#elements . ">\n");
3639 ## foreach my $el (@elements) {
3640 ## print("el: <$el>\n");
3643 my @fix_elements = ();
3646 foreach my $el (@elements) {
3647 push(@fix_elements, substr($rawline, $off, length($el)));
3648 $off += length($el);
3653 my $blank = copy_spacing($opline);
3654 my $last_after = -1;
3656 for (my $n = 0; $n < $#elements; $n += 2) {
3658 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3660 ## print("n: <$n> good: <$good>\n");
3662 $off += length($elements[$n]);
3664 # Pick up the preceding and succeeding characters.
3665 my $ca = substr($opline, 0, $off);
3667 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3668 $cc = substr($opline, $off + length($elements[$n + 1]));
3670 my $cb = "$ca$;$cc";
3673 $a = 'V' if ($elements[$n] ne '');
3674 $a = 'W' if ($elements[$n] =~ /\s$/);
3675 $a = 'C' if ($elements[$n] =~ /$;$/);
3676 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3677 $a = 'O' if ($elements[$n] eq '');
3678 $a = 'E' if ($ca =~ /^\s*$/);
3680 my $op = $elements[$n + 1];
3683 if (defined $elements[$n + 2]) {
3684 $c = 'V' if ($elements[$n + 2] ne '');
3685 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3686 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3687 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3688 $c = 'O' if ($elements[$n + 2] eq '');
3689 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3694 my $ctx = "${a}x${c}";
3696 my $at = "(ctx:$ctx)";
3698 my $ptr = substr($blank, 0, $off) . "^";
3699 my $hereptr = "$hereline$ptr\n";
3701 # Pull out the value of this operator.
3702 my $op_type = substr($curr_values, $off + 1, 1);
3704 # Get the full operator variant.
3705 my $opv = $op . substr($curr_vars, $off, 1);
3707 # Ignore operators passed as parameters.
3708 if ($op_type ne 'V' &&
3709 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
3712 # } elsif ($op =~ /^$;+$/) {
3714 # ; should have either the end of line or a space or \ after it
3715 } elsif ($op eq ';') {
3716 if ($ctx !~ /.x[WEBC]/ &&
3717 $cc !~ /^\\/ && $cc !~ /^;/) {
3718 if (ERROR("SPACING",
3719 "space required after that '$op' $at\n" . $hereptr)) {
3720 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3726 } elsif ($op eq '//') {
3728 # : when part of a bitfield
3729 } elsif ($opv eq ':B') {
3730 # skip the bitfield test for now
3734 } elsif ($op eq '->') {
3735 if ($ctx =~ /Wx.|.xW/) {
3736 if (ERROR("SPACING",
3737 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3738 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3739 if (defined $fix_elements[$n + 2]) {
3740 $fix_elements[$n + 2] =~ s/^\s+//;
3746 # , must not have a space before and must have a space on the right.
3747 } elsif ($op eq ',') {
3748 my $rtrim_before = 0;
3749 my $space_after = 0;
3750 if ($ctx =~ /Wx./) {
3751 if (ERROR("SPACING",
3752 "space prohibited before that '$op' $at\n" . $hereptr)) {
3757 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3758 if (ERROR("SPACING",
3759 "space required after that '$op' $at\n" . $hereptr)) {
3765 if ($rtrim_before || $space_after) {
3766 if ($rtrim_before) {
3767 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3769 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3776 # '*' as part of a type definition -- reported already.
3777 } elsif ($opv eq '*_') {
3778 #warn "'*' is part of type\n";
3780 # unary operators should have a space before and
3781 # none after. May be left adjacent to another
3782 # unary operator, or a cast
3783 } elsif ($op eq '!' || $op eq '~' ||
3784 $opv eq '*U' || $opv eq '-U' ||
3785 $opv eq '&U' || $opv eq '&&U') {
3786 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3787 if (ERROR("SPACING",
3788 "space required before that '$op' $at\n" . $hereptr)) {
3789 if ($n != $last_after + 2) {
3790 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3795 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3796 # A unary '*' may be const
3798 } elsif ($ctx =~ /.xW/) {
3799 if (ERROR("SPACING",
3800 "space prohibited after that '$op' $at\n" . $hereptr)) {
3801 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3802 if (defined $fix_elements[$n + 2]) {
3803 $fix_elements[$n + 2] =~ s/^\s+//;
3809 # unary ++ and unary -- are allowed no space on one side.
3810 } elsif ($op eq '++' or $op eq '--') {
3811 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3812 if (ERROR("SPACING",
3813 "space required one side of that '$op' $at\n" . $hereptr)) {
3814 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3818 if ($ctx =~ /Wx[BE]/ ||
3819 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3820 if (ERROR("SPACING",
3821 "space prohibited before that '$op' $at\n" . $hereptr)) {
3822 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3826 if ($ctx =~ /ExW/) {
3827 if (ERROR("SPACING",
3828 "space prohibited after that '$op' $at\n" . $hereptr)) {
3829 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3830 if (defined $fix_elements[$n + 2]) {
3831 $fix_elements[$n + 2] =~ s/^\s+//;
3837 # << and >> may either have or not have spaces both sides
3838 } elsif ($op eq '<<' or $op eq '>>' or
3839 $op eq '&' or $op eq '^' or $op eq '|' or
3840 $op eq '+' or $op eq '-' or
3841 $op eq '*' or $op eq '/' or
3845 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
3847 "spaces preferred around that '$op' $at\n" . $hereptr)) {
3848 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3849 $fix_elements[$n + 2] =~ s/^\s+//;
3852 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
3854 "space preferred before that '$op' $at\n" . $hereptr)) {
3855 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
3859 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3860 if (ERROR("SPACING",
3861 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3862 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3863 if (defined $fix_elements[$n + 2]) {
3864 $fix_elements[$n + 2] =~ s/^\s+//;
3870 # A colon needs no spaces before when it is
3871 # terminating a case value or a label.
3872 } elsif ($opv eq ':C' || $opv eq ':L') {
3873 if ($ctx =~ /Wx./) {
3874 if (ERROR("SPACING",
3875 "space prohibited before that '$op' $at\n" . $hereptr)) {
3876 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3881 # All the others need spaces both sides.
3882 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3885 # Ignore email addresses <foo@bar>
3887 $cc =~ /^\S+\@\S+>/) ||
3889 $ca =~ /<\S+\@\S+$/))
3894 # for asm volatile statements
3895 # ignore a colon with another
3896 # colon immediately before or after
3898 ($ca =~ /:$/ || $cc =~ /^:/)) {
3902 # messages are ERROR, but ?: are CHK
3904 my $msg_type = \&ERROR;
3905 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3907 if (&{$msg_type}("SPACING",
3908 "spaces required around that '$op' $at\n" . $hereptr)) {
3909 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3910 if (defined $fix_elements[$n + 2]) {
3911 $fix_elements[$n + 2] =~ s/^\s+//;
3917 $off += length($elements[$n + 1]);
3919 ## print("n: <$n> GOOD: <$good>\n");
3921 $fixed_line = $fixed_line . $good;
3924 if (($#elements % 2) == 0) {
3925 $fixed_line = $fixed_line . $fix_elements[$#elements];
3928 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3929 $fixed[$fixlinenr] = $fixed_line;
3935 # check for whitespace before a non-naked semicolon
3936 if ($line =~ /^\+.*\S\s+;\s*$/) {
3938 "space prohibited before semicolon\n" . $herecurr) &&
3940 1 while $fixed[$fixlinenr] =~
3941 s/^(\+.*\S)\s+;/$1;/;
3945 # check for multiple assignments
3946 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3947 CHK("MULTIPLE_ASSIGNMENTS",
3948 "multiple assignments should be avoided\n" . $herecurr);
3951 ## # check for multiple declarations, allowing for a function declaration
3953 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3954 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3956 ## # Remove any bracketed sections to ensure we do not
3957 ## # falsly report the parameters of functions.
3959 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3961 ## if ($ln =~ /,/) {
3962 ## WARN("MULTIPLE_DECLARATION",
3963 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3967 #need space before brace following if, while, etc
3968 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3970 if (ERROR("SPACING",
3971 "space required before the open brace '{'\n" . $herecurr) &&
3973 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3977 ## # check for blank lines before declarations
3978 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3979 ## $prevrawline =~ /^.\s*$/) {
3981 ## "No blank lines before declarations\n" . $hereprev);
3985 # closing brace should have a space following it when it has anything
3987 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3988 if (ERROR("SPACING",
3989 "space required after that close brace '}'\n" . $herecurr) &&
3991 $fixed[$fixlinenr] =~
3992 s/}((?!(?:,|;|\)))\S)/} $1/;
3996 # check spacing on square brackets
3997 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3998 if (ERROR("SPACING",
3999 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4001 $fixed[$fixlinenr] =~
4005 if ($line =~ /\s\]/) {
4006 if (ERROR("SPACING",
4007 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4009 $fixed[$fixlinenr] =~
4014 # check spacing on parentheses
4015 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4016 $line !~ /for\s*\(\s+;/) {
4017 if (ERROR("SPACING",
4018 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4020 $fixed[$fixlinenr] =~
4024 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4025 $line !~ /for\s*\(.*;\s+\)/ &&
4026 $line !~ /:\s+\)/) {
4027 if (ERROR("SPACING",
4028 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4030 $fixed[$fixlinenr] =~
4035 # check unnecessary parentheses around addressof/dereference single $Lvals
4036 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4038 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4040 if (CHK("UNNECESSARY_PARENTHESES",
4041 "Unnecessary parentheses around $var\n" . $herecurr) &&
4043 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4047 # check for unnecessary parentheses around function pointer uses
4048 # ie: (foo->bar)(); should be foo->bar();
4049 # but not "if (foo->bar) (" to avoid some false positives
4050 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4052 if (CHK("UNNECESSARY_PARENTHESES",
4053 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4055 my $var2 = deparenthesize($var);
4057 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4061 #goto labels aren't indented, allow a single space however
4062 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4063 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4064 if (WARN("INDENTED_LABEL",
4065 "labels should not be indented\n" . $herecurr) &&
4067 $fixed[$fixlinenr] =~
4072 # return is not a function
4073 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4075 if ($^V && $^V ge 5.10.0 &&
4076 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4078 $value = deparenthesize($value);
4079 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4080 ERROR("RETURN_PARENTHESES",
4081 "return is not a function, parentheses are not required\n" . $herecurr);
4083 } elsif ($spacing !~ /\s+/) {
4085 "space required before the open parenthesis '('\n" . $herecurr);
4089 # unnecessary return in a void function
4090 # at end-of-function, with the previous line a single leading tab, then return;
4091 # and the line before that not a goto label target like "out:"
4092 if ($sline =~ /^[ \+]}\s*$/ &&
4093 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4095 $lines[$linenr - 3] =~ /^[ +]/ &&
4096 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4098 "void function return statements are not generally useful\n" . $hereprev);
4101 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4102 if ($^V && $^V ge 5.10.0 &&
4103 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4104 my $openparens = $1;
4105 my $count = $openparens =~ tr@\(@\(@;
4107 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4108 my $comp = $4; #Not $1 because of $LvalOrFunc
4109 $msg = " - maybe == should be = ?" if ($comp eq "==");
4110 WARN("UNNECESSARY_PARENTHESES",
4111 "Unnecessary parentheses$msg\n" . $herecurr);
4115 # Return of what appears to be an errno should normally be negative
4116 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4118 if ($name ne 'EOF' && $name ne 'ERROR') {
4119 WARN("USE_NEGATIVE_ERRNO",
4120 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4124 # Need a space before open parenthesis after if, while etc
4125 if ($line =~ /\b(if|while|for|switch)\(/) {
4126 if (ERROR("SPACING",
4127 "space required before the open parenthesis '('\n" . $herecurr) &&
4129 $fixed[$fixlinenr] =~
4130 s/\b(if|while|for|switch)\(/$1 \(/;
4134 # Check for illegal assignment in if conditional -- and check for trailing
4135 # statements after the conditional.
4136 if ($line =~ /do\s*(?!{)/) {
4137 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4138 ctx_statement_block($linenr, $realcnt, 0)
4139 if (!defined $stat);
4140 my ($stat_next) = ctx_statement_block($line_nr_next,
4141 $remain_next, $off_next);
4142 $stat_next =~ s/\n./\n /g;
4143 ##print "stat<$stat> stat_next<$stat_next>\n";
4145 if ($stat_next =~ /^\s*while\b/) {
4146 # If the statement carries leading newlines,
4147 # then count those as offsets.
4149 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4151 statement_rawlines($whitespace) - 1;
4153 $suppress_whiletrailers{$line_nr_next +
4157 if (!defined $suppress_whiletrailers{$linenr} &&
4158 defined($stat) && defined($cond) &&
4159 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4160 my ($s, $c) = ($stat, $cond);
4162 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4163 ERROR("ASSIGN_IN_IF",
4164 "do not use assignment in if condition\n" . $herecurr);
4167 # Find out what is on the end of the line after the
4169 substr($s, 0, length($c), '');
4171 $s =~ s/$;//g; # Remove any comments
4172 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4173 $c !~ /}\s*while\s*/)
4175 # Find out how long the conditional actually is.
4176 my @newlines = ($c =~ /\n/gs);
4177 my $cond_lines = 1 + $#newlines;
4180 $stat_real = raw_line($linenr, $cond_lines)
4181 . "\n" if ($cond_lines);
4182 if (defined($stat_real) && $cond_lines > 1) {
4183 $stat_real = "[...]\n$stat_real";
4186 ERROR("TRAILING_STATEMENTS",
4187 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4191 # Check for bitwise tests written as boolean
4203 WARN("HEXADECIMAL_BOOLEAN_TEST",
4204 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4207 # if and else should not have general statements after it
4208 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4210 $s =~ s/$;//g; # Remove any comments
4211 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4212 ERROR("TRAILING_STATEMENTS",
4213 "trailing statements should be on next line\n" . $herecurr);
4216 # if should not continue a brace
4217 if ($line =~ /}\s*if\b/) {
4218 ERROR("TRAILING_STATEMENTS",
4219 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4222 # case and default should not have general statements after them
4223 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4225 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4229 ERROR("TRAILING_STATEMENTS",
4230 "trailing statements should be on next line\n" . $herecurr);
4233 # Check for }<nl>else {, these must be at the same
4234 # indent level to be relevant to each other.
4235 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4236 $previndent == $indent) {
4237 if (ERROR("ELSE_AFTER_BRACE",
4238 "else should follow close brace '}'\n" . $hereprev) &&
4239 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4240 fix_delete_line($fixlinenr - 1, $prevrawline);
4241 fix_delete_line($fixlinenr, $rawline);
4242 my $fixedline = $prevrawline;
4243 $fixedline =~ s/}\s*$//;
4244 if ($fixedline !~ /^\+\s*$/) {
4245 fix_insert_line($fixlinenr, $fixedline);
4247 $fixedline = $rawline;
4248 $fixedline =~ s/^(.\s*)else/$1} else/;
4249 fix_insert_line($fixlinenr, $fixedline);
4253 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4254 $previndent == $indent) {
4255 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4257 # Find out what is on the end of the line after the
4259 substr($s, 0, length($c), '');
4262 if ($s =~ /^\s*;/) {
4263 if (ERROR("WHILE_AFTER_BRACE",
4264 "while should follow close brace '}'\n" . $hereprev) &&
4265 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4266 fix_delete_line($fixlinenr - 1, $prevrawline);
4267 fix_delete_line($fixlinenr, $rawline);
4268 my $fixedline = $prevrawline;
4269 my $trailing = $rawline;
4270 $trailing =~ s/^\+//;
4271 $trailing = trim($trailing);
4272 $fixedline =~ s/}\s*$/} $trailing/;
4273 fix_insert_line($fixlinenr, $fixedline);
4278 #Specific variable tests
4279 while ($line =~ m{($Constant|$Lval)}g) {
4282 #gcc binary extension
4283 if ($var =~ /^$Binary$/) {
4284 if (WARN("GCC_BINARY_CONSTANT",
4285 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4287 my $hexval = sprintf("0x%x", oct($var));
4288 $fixed[$fixlinenr] =~
4289 s/\b$var\b/$hexval/;
4294 if ($var !~ /^$Constant$/ &&
4295 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4296 #Ignore Page<foo> variants
4297 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4298 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4299 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4300 #Ignore some three character SI units explicitly, like MiB and KHz
4301 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4302 while ($var =~ m{($Ident)}g) {
4304 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4306 seed_camelcase_includes();
4307 if (!$file && !$camelcase_file_seeded) {
4308 seed_camelcase_file($realfile);
4309 $camelcase_file_seeded = 1;
4312 if (!defined $camelcase{$word}) {
4313 $camelcase{$word} = 1;
4315 "Avoid CamelCase: <$word>\n" . $herecurr);
4321 #no spaces allowed after \ in define
4322 if ($line =~ /\#\s*define.*\\\s+$/) {
4323 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4324 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4326 $fixed[$fixlinenr] =~ s/\s+$//;
4330 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4331 # itself <asm/foo.h> (uses RAW line)
4332 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4334 my $checkfile = "include/linux/$file";
4335 if (-f "$root/$checkfile" &&
4336 $realfile ne $checkfile &&
4337 $1 !~ /$allowed_asm_includes/)
4339 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4340 if ($asminclude > 0) {
4341 if ($realfile =~ m{^arch/}) {
4342 CHK("ARCH_INCLUDE_LINUX",
4343 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4345 WARN("INCLUDE_LINUX",
4346 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4352 # multi-statement macros should be enclosed in a do while loop, grab the
4353 # first statement and ensure its the whole macro if its not enclosed
4354 # in a known good container
4355 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4356 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4359 my ($off, $dstat, $dcond, $rest);
4361 my $has_flow_statement = 0;
4362 my $has_arg_concat = 0;
4363 ($dstat, $dcond, $ln, $cnt, $off) =
4364 ctx_statement_block($linenr, $realcnt, 0);
4366 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4367 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4369 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4370 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4372 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4374 $dstat =~ s/\\\n.//g;
4375 $dstat =~ s/^\s*//s;
4376 $dstat =~ s/\s*$//s;
4378 # Flatten any parentheses and braces
4379 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4380 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4381 $dstat =~ s/\[[^\[\]]*\]/1/)
4385 # Flatten any obvious string concatentation.
4386 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
4387 $dstat =~ s/$Ident\s*($String)/$1/)
4391 my $exceptions = qr{
4403 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4405 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4406 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4407 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4408 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4409 $dstat !~ /$exceptions/ &&
4410 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4411 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4412 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4413 $dstat !~ /^for\s*$Constant$/ && # for (...)
4414 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4415 $dstat !~ /^do\s*{/ && # do {...
4416 $dstat !~ /^\({/ && # ({...
4417 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4420 my $herectx = $here . "\n";
4421 my $cnt = statement_rawlines($ctx);
4423 for (my $n = 0; $n < $cnt; $n++) {
4424 $herectx .= raw_line($linenr, $n) . "\n";
4427 if ($dstat =~ /;/) {
4428 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4429 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4431 ERROR("COMPLEX_MACRO",
4432 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4436 # check for macros with flow control, but without ## concatenation
4437 # ## concatenation is commonly a macro that defines a function so ignore those
4438 if ($has_flow_statement && !$has_arg_concat) {
4439 my $herectx = $here . "\n";
4440 my $cnt = statement_rawlines($ctx);
4442 for (my $n = 0; $n < $cnt; $n++) {
4443 $herectx .= raw_line($linenr, $n) . "\n";
4445 WARN("MACRO_WITH_FLOW_CONTROL",
4446 "Macros with flow control statements should be avoided\n" . "$herectx");
4449 # check for line continuations outside of #defines, preprocessor #, and asm
4452 if ($prevline !~ /^..*\\$/ &&
4453 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4454 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4455 $line =~ /^\+.*\\$/) {
4456 WARN("LINE_CONTINUATIONS",
4457 "Avoid unnecessary line continuations\n" . $herecurr);
4461 # do {} while (0) macro tests:
4462 # single-statement macros do not need to be enclosed in do while (0) loop,
4463 # macro should not end with a semicolon
4464 if ($^V && $^V ge 5.10.0 &&
4465 $realfile !~ m@/vmlinux.lds.h$@ &&
4466 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4469 my ($off, $dstat, $dcond, $rest);
4471 ($dstat, $dcond, $ln, $cnt, $off) =
4472 ctx_statement_block($linenr, $realcnt, 0);
4475 $dstat =~ s/\\\n.//g;
4478 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4483 my $cnt = statement_rawlines($ctx);
4484 my $herectx = $here . "\n";
4486 for (my $n = 0; $n < $cnt; $n++) {
4487 $herectx .= raw_line($linenr, $n) . "\n";
4490 if (($stmts =~ tr/;/;/) == 1 &&
4491 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4492 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4493 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4495 if (defined $semis && $semis ne "") {
4496 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4497 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4499 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4501 my $cnt = statement_rawlines($ctx);
4502 my $herectx = $here . "\n";
4504 for (my $n = 0; $n < $cnt; $n++) {
4505 $herectx .= raw_line($linenr, $n) . "\n";
4508 WARN("TRAILING_SEMICOLON",
4509 "macros should not use a trailing semicolon\n" . "$herectx");
4513 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4514 # all assignments may have only one of the following with an assignment:
4517 # VMLINUX_SYMBOL(...)
4518 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4519 WARN("MISSING_VMLINUX_SYMBOL",
4520 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4523 # check for redundant bracing round if etc
4524 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4525 my ($level, $endln, @chunks) =
4526 ctx_statement_full($linenr, $realcnt, 1);
4527 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4528 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4529 if ($#chunks > 0 && $level == 0) {
4533 my $herectx = $here . "\n";
4534 my $ln = $linenr - 1;
4535 for my $chunk (@chunks) {
4536 my ($cond, $block) = @{$chunk};
4538 # If the condition carries leading newlines, then count those as offsets.
4539 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4540 my $offset = statement_rawlines($whitespace) - 1;
4542 $allowed[$allow] = 0;
4543 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4545 # We have looked at and allowed this specific line.
4546 $suppress_ifbraces{$ln + $offset} = 1;
4548 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4549 $ln += statement_rawlines($block) - 1;
4551 substr($block, 0, length($cond), '');
4553 $seen++ if ($block =~ /^\s*{/);
4555 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4556 if (statement_lines($cond) > 1) {
4557 #print "APW: ALLOWED: cond<$cond>\n";
4558 $allowed[$allow] = 1;
4560 if ($block =~/\b(?:if|for|while)\b/) {
4561 #print "APW: ALLOWED: block<$block>\n";
4562 $allowed[$allow] = 1;
4564 if (statement_block_size($block) > 1) {
4565 #print "APW: ALLOWED: lines block<$block>\n";
4566 $allowed[$allow] = 1;
4571 my $sum_allowed = 0;
4572 foreach (@allowed) {
4575 if ($sum_allowed == 0) {
4577 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4578 } elsif ($sum_allowed != $allow &&
4581 "braces {} should be used on all arms of this statement\n" . $herectx);
4586 if (!defined $suppress_ifbraces{$linenr - 1} &&
4587 $line =~ /\b(if|while|for|else)\b/) {
4590 # Check the pre-context.
4591 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4592 #print "APW: ALLOWED: pre<$1>\n";
4596 my ($level, $endln, @chunks) =
4597 ctx_statement_full($linenr, $realcnt, $-[0]);
4599 # Check the condition.
4600 my ($cond, $block) = @{$chunks[0]};
4601 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4602 if (defined $cond) {
4603 substr($block, 0, length($cond), '');
4605 if (statement_lines($cond) > 1) {
4606 #print "APW: ALLOWED: cond<$cond>\n";
4609 if ($block =~/\b(?:if|for|while)\b/) {
4610 #print "APW: ALLOWED: block<$block>\n";
4613 if (statement_block_size($block) > 1) {
4614 #print "APW: ALLOWED: lines block<$block>\n";
4617 # Check the post-context.
4618 if (defined $chunks[1]) {
4619 my ($cond, $block) = @{$chunks[1]};
4620 if (defined $cond) {
4621 substr($block, 0, length($cond), '');
4623 if ($block =~ /^\s*\{/) {
4624 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4628 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4629 my $herectx = $here . "\n";
4630 my $cnt = statement_rawlines($block);
4632 for (my $n = 0; $n < $cnt; $n++) {
4633 $herectx .= raw_line($linenr, $n) . "\n";
4637 "braces {} are not necessary for single statement blocks\n" . $herectx);
4641 # check for unnecessary blank lines around braces
4642 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4644 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4645 $fix && $prevrawline =~ /^\+/) {
4646 fix_delete_line($fixlinenr - 1, $prevrawline);
4649 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4651 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4653 fix_delete_line($fixlinenr, $rawline);
4657 # no volatiles please
4658 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4659 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4661 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4664 # Check for user-visible strings broken across lines, which breaks the ability
4665 # to grep for the string. Make exceptions when the previous string ends in a
4666 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4667 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4668 if ($line =~ /^\+\s*$String/ &&
4669 $prevline =~ /"\s*$/ &&
4670 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4671 if (WARN("SPLIT_STRING",
4672 "quoted string split across lines\n" . $hereprev) &&
4674 $prevrawline =~ /^\+.*"\s*$/ &&
4675 $last_coalesced_string_linenr != $linenr - 1) {
4676 my $extracted_string = get_quoted_string($line, $rawline);
4677 my $comma_close = "";
4678 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4682 fix_delete_line($fixlinenr - 1, $prevrawline);
4683 fix_delete_line($fixlinenr, $rawline);
4684 my $fixedline = $prevrawline;
4685 $fixedline =~ s/"\s*$//;
4686 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4687 fix_insert_line($fixlinenr - 1, $fixedline);
4688 $fixedline = $rawline;
4689 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4690 if ($fixedline !~ /\+\s*$/) {
4691 fix_insert_line($fixlinenr, $fixedline);
4693 $last_coalesced_string_linenr = $linenr;
4697 # check for missing a space in a string concatenation
4698 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4699 WARN('MISSING_SPACE',
4700 "break quoted strings at a space character\n" . $hereprev);
4703 # check for spaces before a quoted newline
4704 if ($rawline =~ /^.*\".*\s\\n/) {
4705 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4706 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4708 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4713 # concatenated string without spaces between elements
4714 if ($line =~ /$String[A-Z_]/ || $line =~ /[A-Za-z0-9_]$String/) {
4715 CHK("CONCATENATED_STRING",
4716 "Concatenated strings should use spaces between elements\n" . $herecurr);
4719 # uncoalesced string fragments
4720 if ($line =~ /$String\s*"/) {
4721 WARN("STRING_FRAGMENTS",
4722 "Consecutive strings are generally better as a single string\n" . $herecurr);
4725 # check for %L{u,d,i} in strings
4727 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4728 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4729 $string =~ s/%%/__/g;
4730 if ($string =~ /(?<!%)%L[udi]/) {
4732 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4737 # check for line continuations in quoted strings with odd counts of "
4738 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4739 WARN("LINE_CONTINUATIONS",
4740 "Avoid line continuations in quoted strings\n" . $herecurr);
4744 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4745 CHK("REDUNDANT_CODE",
4746 "if this code is redundant consider removing it\n" .
4750 # check for needless "if (<foo>) fn(<foo>)" uses
4751 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4752 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4753 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4755 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4759 # check for unnecessary "Out of Memory" messages
4760 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4761 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4762 (defined $1 || defined $3) &&
4765 my $testline = $lines[$linenr - 3];
4767 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4768 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4770 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4772 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4776 # check for logging functions with KERN_<LEVEL>
4777 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4778 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4780 if (WARN("UNNECESSARY_KERN_LEVEL",
4781 "Possible unnecessary $level\n" . $herecurr) &&
4783 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4787 # check for mask then right shift without a parentheses
4788 if ($^V && $^V ge 5.10.0 &&
4789 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4790 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4791 WARN("MASK_THEN_SHIFT",
4792 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4795 # check for pointer comparisons to NULL
4796 if ($^V && $^V ge 5.10.0) {
4797 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4800 $equal = "" if ($4 eq "!=");
4801 if (CHK("COMPARISON_TO_NULL",
4802 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4804 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4809 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4810 if ($line =~ /(\b$InitAttribute\b)/) {
4812 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4815 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4816 ERROR("MISPLACED_INIT",
4817 "$attr should be placed after $var\n" . $herecurr)) ||
4818 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4819 WARN("MISPLACED_INIT",
4820 "$attr should be placed after $var\n" . $herecurr))) &&
4822 $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;
4827 # check for $InitAttributeData (ie: __initdata) with const
4828 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4830 $attr =~ /($InitAttributePrefix)(.*)/;
4831 my $attr_prefix = $1;
4833 if (ERROR("INIT_ATTRIBUTE",
4834 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4836 $fixed[$fixlinenr] =~
4837 s/$InitAttributeData/${attr_prefix}initconst/;
4841 # check for $InitAttributeConst (ie: __initconst) without const
4842 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4844 if (ERROR("INIT_ATTRIBUTE",
4845 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4847 my $lead = $fixed[$fixlinenr] =~
4848 /(^\+\s*(?:static\s+))/;
4850 $lead = "$lead " if ($lead !~ /^\+$/);
4851 $lead = "${lead}const ";
4852 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4856 # check for __read_mostly with const non-pointer (should just be const)
4857 if ($line =~ /\b__read_mostly\b/ &&
4858 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
4859 if (ERROR("CONST_READ_MOSTLY",
4860 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
4862 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
4866 # don't use __constant_<foo> functions outside of include/uapi/
4867 if ($realfile !~ m@^include/uapi/@ &&
4868 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4869 my $constant_func = $1;
4870 my $func = $constant_func;
4871 $func =~ s/^__constant_//;
4872 if (WARN("CONSTANT_CONVERSION",
4873 "$constant_func should be $func\n" . $herecurr) &&
4875 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4879 # prefer usleep_range over udelay
4880 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4882 # ignore udelay's < 10, however
4883 if (! ($delay < 10) ) {
4885 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4887 if ($delay > 2000) {
4889 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4893 # warn about unexpectedly long msleep's
4894 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4897 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4901 # check for comparisons of jiffies
4902 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4903 WARN("JIFFIES_COMPARISON",
4904 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4907 # check for comparisons of get_jiffies_64()
4908 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4909 WARN("JIFFIES_COMPARISON",
4910 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4913 # warn about #ifdefs in C files
4914 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4915 # print "#ifdef in C files should be avoided\n";
4916 # print "$herecurr";
4920 # warn about spacing in #ifdefs
4921 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4922 if (ERROR("SPACING",
4923 "exactly one space required after that #$1\n" . $herecurr) &&
4925 $fixed[$fixlinenr] =~
4926 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4931 # check for spinlock_t definitions without a comment.
4932 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4933 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4935 if (!ctx_has_comment($first_line, $linenr)) {
4936 CHK("UNCOMMENTED_DEFINITION",
4937 "$1 definition without comment\n" . $herecurr);
4940 # check for memory barriers without a comment.
4941 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4942 if (!ctx_has_comment($first_line, $linenr)) {
4943 WARN("MEMORY_BARRIER",
4944 "memory barrier without comment\n" . $herecurr);
4947 # check for waitqueue_active without a comment.
4948 if ($line =~ /\bwaitqueue_active\s*\(/) {
4949 if (!ctx_has_comment($first_line, $linenr)) {
4950 WARN("WAITQUEUE_ACTIVE",
4951 "waitqueue_active without comment\n" . $herecurr);
4954 # check of hardware specific defines
4955 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4957 "architecture specific defines should be avoided\n" . $herecurr);
4960 # Check that the storage class is at the beginning of a declaration
4961 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4962 WARN("STORAGE_CLASS",
4963 "storage class should be at the beginning of the declaration\n" . $herecurr)
4966 # check the location of the inline attribute, that it is between
4967 # storage class and type.
4968 if ($line =~ /\b$Type\s+$Inline\b/ ||
4969 $line =~ /\b$Inline\s+$Storage\b/) {
4970 ERROR("INLINE_LOCATION",
4971 "inline keyword should sit between storage class and type\n" . $herecurr);
4974 # Check for __inline__ and __inline, prefer inline
4975 if ($realfile !~ m@\binclude/uapi/@ &&
4976 $line =~ /\b(__inline__|__inline)\b/) {
4978 "plain inline is preferred over $1\n" . $herecurr) &&
4980 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4985 # Check for __attribute__ packed, prefer __packed
4986 if ($realfile !~ m@\binclude/uapi/@ &&
4987 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4988 WARN("PREFER_PACKED",
4989 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4992 # Check for __attribute__ aligned, prefer __aligned
4993 if ($realfile !~ m@\binclude/uapi/@ &&
4994 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4995 WARN("PREFER_ALIGNED",
4996 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4999 # Check for __attribute__ format(printf, prefer __printf
5000 if ($realfile !~ m@\binclude/uapi/@ &&
5001 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5002 if (WARN("PREFER_PRINTF",
5003 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5005 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5010 # Check for __attribute__ format(scanf, prefer __scanf
5011 if ($realfile !~ m@\binclude/uapi/@ &&
5012 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5013 if (WARN("PREFER_SCANF",
5014 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5016 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5020 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5021 if ($^V && $^V ge 5.10.0 &&
5022 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5023 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5024 $line =~ /\b__weak\b/)) {
5025 ERROR("WEAK_DECLARATION",
5026 "Using weak declarations can have unintended link defects\n" . $herecurr);
5029 # check for c99 types like uint8_t used outside of uapi/
5030 if ($realfile !~ m@\binclude/uapi/@ &&
5031 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5033 if ($type =~ /\b($typeC99Typedefs)\b/) {
5035 my $kernel_type = 'u';
5036 $kernel_type = 's' if ($type =~ /^_*[si]/);
5039 if (CHK("PREFER_KERNEL_TYPES",
5040 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5042 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5047 # check for sizeof(&)
5048 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5049 WARN("SIZEOF_ADDRESS",
5050 "sizeof(& should be avoided\n" . $herecurr);
5053 # check for sizeof without parenthesis
5054 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5055 if (WARN("SIZEOF_PARENTHESIS",
5056 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5058 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5062 # check for struct spinlock declarations
5063 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5064 WARN("USE_SPINLOCK_T",
5065 "struct spinlock should be spinlock_t\n" . $herecurr);
5068 # check for seq_printf uses that could be seq_puts
5069 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5070 my $fmt = get_quoted_string($line, $rawline);
5073 if (WARN("PREFER_SEQ_PUTS",
5074 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5076 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5081 # Check for misused memsets
5082 if ($^V && $^V ge 5.10.0 &&
5084 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
5090 if ($ms_size =~ /^(0x|)0$/i) {
5092 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5093 } elsif ($ms_size =~ /^(0x|)1$/i) {
5095 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5099 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5100 if ($^V && $^V ge 5.10.0 &&
5101 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
5102 if (WARN("PREFER_ETHER_ADDR_COPY",
5103 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
5105 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5109 # typecasts on min/max could be min_t/max_t
5110 if ($^V && $^V ge 5.10.0 &&
5112 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5113 if (defined $2 || defined $7) {
5115 my $cast1 = deparenthesize($2);
5117 my $cast2 = deparenthesize($7);
5121 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5122 $cast = "$cast1 or $cast2";
5123 } elsif ($cast1 ne "") {
5129 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5133 # check usleep_range arguments
5134 if ($^V && $^V ge 5.10.0 &&
5136 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5140 WARN("USLEEP_RANGE",
5141 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5142 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5144 WARN("USLEEP_RANGE",
5145 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5149 # check for naked sscanf
5150 if ($^V && $^V ge 5.10.0 &&
5152 $line =~ /\bsscanf\b/ &&
5153 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5154 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5155 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5156 my $lc = $stat =~ tr@\n@@;
5157 $lc = $lc + $linenr;
5158 my $stat_real = raw_line($linenr, 0);
5159 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5160 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5162 WARN("NAKED_SSCANF",
5163 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5166 # check for simple sscanf that should be kstrto<foo>
5167 if ($^V && $^V ge 5.10.0 &&
5169 $line =~ /\bsscanf\b/) {
5170 my $lc = $stat =~ tr@\n@@;
5171 $lc = $lc + $linenr;
5172 my $stat_real = raw_line($linenr, 0);
5173 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5174 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5176 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5178 my $count = $format =~ tr@%@%@;
5180 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5181 WARN("SSCANF_TO_KSTRTO",
5182 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5187 # check for new externs in .h files.
5188 if ($realfile =~ /\.h$/ &&
5189 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5190 if (CHK("AVOID_EXTERNS",
5191 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5193 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5197 # check for new externs in .c files.
5198 if ($realfile =~ /\.c$/ && defined $stat &&
5199 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5201 my $function_name = $1;
5202 my $paren_space = $2;
5205 if (defined $cond) {
5206 substr($s, 0, length($cond), '');
5208 if ($s =~ /^\s*;/ &&
5209 $function_name ne 'uninitialized_var')
5211 WARN("AVOID_EXTERNS",
5212 "externs should be avoided in .c files\n" . $herecurr);
5215 if ($paren_space =~ /\n/) {
5216 WARN("FUNCTION_ARGUMENTS",
5217 "arguments for function declarations should follow identifier\n" . $herecurr);
5220 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5221 $stat =~ /^.\s*extern\s+/)
5223 WARN("AVOID_EXTERNS",
5224 "externs should be avoided in .c files\n" . $herecurr);
5227 # checks for new __setup's
5228 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5231 if (!grep(/$name/, @setup_docs)) {
5232 CHK("UNDOCUMENTED_SETUP",
5233 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5237 # check for pointless casting of kmalloc return
5238 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5239 WARN("UNNECESSARY_CASTS",
5240 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5244 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5245 if ($^V && $^V ge 5.10.0 &&
5246 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5247 CHK("ALLOC_SIZEOF_STRUCT",
5248 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5251 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5252 if ($^V && $^V ge 5.10.0 &&
5253 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5257 my $newfunc = "kmalloc_array";
5258 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5261 if ($a1 =~ /^sizeof\s*\S/) {
5265 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5266 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5267 if (WARN("ALLOC_WITH_MULTIPLY",
5268 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5270 $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;
5276 # check for krealloc arg reuse
5277 if ($^V && $^V ge 5.10.0 &&
5278 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5279 WARN("KREALLOC_ARG_REUSE",
5280 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5283 # check for alloc argument mismatch
5284 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5285 WARN("ALLOC_ARRAY_ARGS",
5286 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5289 # check for multiple semicolons
5290 if ($line =~ /;\s*;\s*$/) {
5291 if (WARN("ONE_SEMICOLON",
5292 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5294 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5298 # check for #defines like: 1 << <digit> that could be BIT(digit)
5299 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5301 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5302 if (CHK("BIT_MACRO",
5303 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5305 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5309 # check for case / default statements not preceded by break/fallthrough/switch
5310 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5312 my $has_statement = 0;
5314 my $prevline = $linenr;
5315 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5317 my $rline = $rawlines[$prevline - 1];
5318 my $fline = $lines[$prevline - 1];
5319 last if ($fline =~ /^\@\@/);
5320 next if ($fline =~ /^\-/);
5321 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5322 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5323 next if ($fline =~ /^.[\s$;]*$/);
5326 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5328 if (!$has_break && $has_statement) {
5329 WARN("MISSING_BREAK",
5330 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5334 # check for switch/default statements without a break;
5335 if ($^V && $^V ge 5.10.0 &&
5337 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5339 my $herectx = $here . "\n";
5340 my $cnt = statement_rawlines($stat);
5341 for (my $n = 0; $n < $cnt; $n++) {
5342 $herectx .= raw_line($linenr, $n) . "\n";
5344 WARN("DEFAULT_NO_BREAK",
5345 "switch default: should use break\n" . $herectx);
5348 # check for gcc specific __FUNCTION__
5349 if ($line =~ /\b__FUNCTION__\b/) {
5350 if (WARN("USE_FUNC",
5351 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5353 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5357 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5358 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5360 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5363 # check for use of yield()
5364 if ($line =~ /\byield\s*\(\s*\)/) {
5366 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5369 # check for comparisons against true and false
5370 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5378 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5380 my $type = lc($otype);
5381 if ($type =~ /^(?:true|false)$/) {
5382 if (("$test" eq "==" && "$type" eq "true") ||
5383 ("$test" eq "!=" && "$type" eq "false")) {
5387 CHK("BOOL_COMPARISON",
5388 "Using comparison to $otype is error prone\n" . $herecurr);
5390 ## maybe suggesting a correct construct would better
5391 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5396 # check for semaphores initialized locked
5397 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5398 WARN("CONSIDER_COMPLETION",
5399 "consider using a completion\n" . $herecurr);
5402 # recommend kstrto* over simple_strto* and strict_strto*
5403 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5404 WARN("CONSIDER_KSTRTO",
5405 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5408 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5409 if ($line =~ /^.\s*__initcall\s*\(/) {
5410 WARN("USE_DEVICE_INITCALL",
5411 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5414 # check for various structs that are normally const (ops, kgdb, device_tree)
5415 my $const_structs = qr{
5417 address_space_operations|
5419 block_device_operations|
5424 file_lock_operations|
5434 lock_manager_operations|
5441 pipe_buf_operations|
5442 platform_hibernation_ops|
5443 platform_suspend_ops|
5448 soc_pcmcia_socket_ops|
5455 if ($line !~ /\bconst\b/ &&
5456 $line =~ /\bstruct\s+($const_structs)\b/) {
5457 WARN("CONST_STRUCT",
5458 "struct $1 should normally be const\n" .
5462 # use of NR_CPUS is usually wrong
5463 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5464 if ($line =~ /\bNR_CPUS\b/ &&
5465 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5466 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5467 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5468 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5469 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5472 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5475 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5476 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5477 ERROR("DEFINE_ARCH_HAS",
5478 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5481 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5482 if ($^V && $^V ge 5.10.0 &&
5483 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5484 WARN("LIKELY_MISUSE",
5485 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5488 # whine mightly about in_atomic
5489 if ($line =~ /\bin_atomic\s*\(/) {
5490 if ($realfile =~ m@^drivers/@) {
5492 "do not use in_atomic in drivers\n" . $herecurr);
5493 } elsif ($realfile !~ m@^kernel/@) {
5495 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5499 # check for lockdep_set_novalidate_class
5500 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5501 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5502 if ($realfile !~ m@^kernel/lockdep@ &&
5503 $realfile !~ m@^include/linux/lockdep@ &&
5504 $realfile !~ m@^drivers/base/core@) {
5506 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5510 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
5511 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
5512 WARN("EXPORTED_WORLD_WRITABLE",
5513 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5516 # Mode permission misuses where it seems decimal should be octal
5517 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5518 if ($^V && $^V ge 5.10.0 &&
5519 $line =~ /$mode_perms_search/) {
5520 foreach my $entry (@mode_permission_funcs) {
5521 my $func = $entry->[0];
5522 my $arg_pos = $entry->[1];
5527 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5529 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5530 if ($line =~ /$test/) {
5532 $val = $6 if ($skip_args ne "");
5534 if ($val !~ /^0$/ &&
5535 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5536 length($val) ne 4)) {
5537 ERROR("NON_OCTAL_PERMISSIONS",
5538 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5539 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5540 ERROR("EXPORTED_WORLD_WRITABLE",
5541 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5548 # If we have no input at all, then there is nothing to report on
5549 # so just keep quiet.
5550 if ($#rawlines == -1) {
5554 # In mailback mode only produce a report in the negative, for
5555 # things that appear to be patches.
5556 if ($mailback && ($clean == 1 || !$is_patch)) {
5560 # This is not a patch, and we are are in 'no-patch' mode so
5562 if (!$chk_patch && !$is_patch) {
5567 ERROR("NOT_UNIFIED_DIFF",
5568 "Does not appear to be a unified-diff format patch\n");
5570 if ($is_patch && $chk_signoff && $signoff == 0) {
5571 ERROR("MISSING_SIGN_OFF",
5572 "Missing Signed-off-by: line(s)\n");
5575 print report_dump();
5576 if ($summary && !($clean == 1 && $quiet == 1)) {
5577 print "$filename " if ($summary_file);
5578 print "total: $cnt_error errors, $cnt_warn warnings, " .
5579 (($check)? "$cnt_chk checks, " : "") .
5580 "$cnt_lines lines checked\n";
5581 print "\n" if ($quiet == 0);
5586 if ($^V lt 5.10.0) {
5587 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5588 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5591 # If there were whitespace errors which cleanpatch can fix
5592 # then suggest that.
5593 if ($rpt_cleaners) {
5594 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5595 print " scripts/cleanfile\n\n";
5600 hash_show_words(\%use_type, "Used");
5601 hash_show_words(\%ignore_type, "Ignored");
5603 if ($clean == 0 && $fix &&
5604 ("@rawlines" ne "@fixed" ||
5605 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5606 my $newfile = $filename;
5607 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5611 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5613 open($f, '>', $newfile)
5614 or die "$P: Can't open $newfile for write\n";
5615 foreach my $fixed_line (@fixed) {
5618 if ($linecount > 3) {
5619 $fixed_line =~ s/^\+//;
5620 print $f $fixed_line . "\n";
5623 print $f $fixed_line . "\n";
5630 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5632 Do _NOT_ trust the results written to this file.
5633 Do _NOT_ submit these changes without inspecting them for correctness.
5635 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5636 No warranties, expressed or implied...
5642 if ($clean == 1 && $quiet == 0) {
5643 print "$vname has no obvious style problems and is ready for submission.\n"
5645 if ($clean == 0 && $quiet == 0) {
5647 $vname has style problems, please review.
5649 If any of these errors are false positives, please report
5650 them to the maintainer, see CHECKPATCH in MAINTAINERS.