2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 100;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile = "";
64 my $allow_c99_comments = 1;
70 Usage: $P [OPTION]... [FILE]...
75 --no-tree run without a kernel tree
76 --no-signoff do not check for 'Signed-off-by' line
77 --patch treat FILE as patchfile (default)
78 --emacs emacs compile window format
79 --terse one line per report
80 --showfile emit diffed file position, not input file position
81 -g, --git treat FILE as a single commit or git revision range
82 single git commit with:
86 multiple git commits with:
90 git merges are ignored
91 -f, --file treat FILE as regular source file
92 --subjective, --strict enable more subjective tests
93 --list-types list the possible message types
94 --types TYPE(,TYPE2...) show only these comma separated message types
95 --ignore TYPE(,TYPE2...) ignore various comma separated message types
96 --show-types show the specific message type in the output
97 --max-line-length=n set the maximum line length, (default $max_line_length)
98 if exceeded, warn on patches
99 requires --strict for use with --file
100 --min-conf-desc-length=n set the min description length, if shorter, warn
101 --root=PATH PATH to the kernel tree root
102 --no-summary suppress the per-file summary
103 --mailback only produce a report in case of warnings/errors
104 --summary-file include the filename in summary
105 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
106 'values', 'possible', 'type', and 'attr' (default
108 --test-only=WORD report only warnings/errors containing WORD
110 --fix EXPERIMENTAL - may create horrible results
111 If correctable single-line errors exist, create
112 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
113 with potential errors corrected to the preferred
115 --fix-inplace EXPERIMENTAL - may create horrible results
116 Is the same as --fix, but overwrites the input
117 file. It's your fault if there's no backup or git
118 --ignore-perl-version override checking of perl version. expect
120 --codespell Use the codespell dictionary for spelling/typos
121 (default:/usr/share/codespell/dictionary.txt)
122 --codespellfile Use this codespell dictionary
123 --typedefsfile Read additional types from this file
124 --color[=WHEN] Use colors 'always', 'never', or only when output
125 is a terminal ('auto'). Default is 'auto'.
126 -h, --help, --version display this help and exit
128 When FILE is - read standard input.
136 return grep { !$seen{$_}++ } @_;
146 open(my $script, '<', abs_path($P)) or
147 die "$P: Can't read '$P' $!\n";
149 my $text = <$script>;
153 # Also catch when type or level is passed through a variable
154 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
157 @types = sort(uniq(@types));
158 print("#\tMessage type\n\n");
159 foreach my $type (@types) {
160 print(++$count . "\t" . $type . "\n");
166 my $conf = which_conf($configuration_file);
169 open(my $conffile, '<', "$conf")
170 or warn "$P: Can't find a readable $configuration_file file $!\n";
172 while (<$conffile>) {
175 $line =~ s/\s*\n?$//g;
179 next if ($line =~ m/^\s*#/);
180 next if ($line =~ m/^\s*$/);
182 my @words = split(" ", $line);
183 foreach my $word (@words) {
184 last if ($word =~ m/^#/);
185 push (@conf_args, $word);
189 unshift(@ARGV, @conf_args) if @conf_args;
192 # Perl's Getopt::Long allows options to take optional arguments after a space.
193 # Prevent --color by itself from consuming other arguments
195 if ($_ eq "--color" || $_ eq "-color") {
196 $_ = "--color=$color";
201 'q|quiet+' => \$quiet,
203 'signoff!' => \$chk_signoff,
204 'patch!' => \$chk_patch,
207 'showfile!' => \$showfile,
210 'subjective!' => \$check,
211 'strict!' => \$check,
212 'ignore=s' => \@ignore,
214 'show-types!' => \$show_types,
215 'list-types!' => \$list_types,
216 'max-line-length=i' => \$max_line_length,
217 'min-conf-desc-length=i' => \$min_conf_desc_length,
219 'summary!' => \$summary,
220 'mailback!' => \$mailback,
221 'summary-file!' => \$summary_file,
223 'fix-inplace!' => \$fix_inplace,
224 'ignore-perl-version!' => \$ignore_perl_version,
225 'debug=s' => \%debug,
226 'test-only=s' => \$tst_only,
227 'codespell!' => \$codespell,
228 'codespellfile=s' => \$codespellfile,
229 'typedefsfile=s' => \$typedefsfile,
230 'color=s' => \$color,
231 'no-color' => \$color, #keep old behaviors of -nocolor
232 'nocolor' => \$color, #keep old behaviors of -nocolor
239 list_types(0) if ($list_types);
241 $fix = 1 if ($fix_inplace);
242 $check_orig = $check;
246 my $perl_version_ok = 1;
247 if ($^V && $^V lt $minimum_perl_version) {
248 $perl_version_ok = 0;
249 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
250 exit(1) if (!$ignore_perl_version);
253 #if no filenames are given, push '-' to read patch from stdin
258 if ($color =~ /^[01]$/) {
260 } elsif ($color =~ /^always$/i) {
262 } elsif ($color =~ /^never$/i) {
264 } elsif ($color =~ /^auto$/i) {
265 $color = (-t STDOUT);
267 die "Invalid color mode: $color\n";
270 sub hash_save_array_words {
271 my ($hashRef, $arrayRef) = @_;
273 my @array = split(/,/, join(',', @$arrayRef));
274 foreach my $word (@array) {
275 $word =~ s/\s*\n?$//g;
278 $word =~ tr/[a-z]/[A-Z]/;
280 next if ($word =~ m/^\s*#/);
281 next if ($word =~ m/^\s*$/);
287 sub hash_show_words {
288 my ($hashRef, $prefix) = @_;
290 if (keys %$hashRef) {
291 print "\nNOTE: $prefix message types:";
292 foreach my $word (sort keys %$hashRef) {
299 hash_save_array_words(\%ignore_type, \@ignore);
300 hash_save_array_words(\%use_type, \@use);
303 my $dbg_possible = 0;
306 for my $key (keys %debug) {
308 eval "\${dbg_$key} = '$debug{$key}';";
312 my $rpt_cleaners = 0;
321 if (!top_of_kernel_tree($root)) {
322 die "$P: $root: --root does not point at a valid tree\n";
325 if (top_of_kernel_tree('.')) {
327 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
328 top_of_kernel_tree($1)) {
333 if (!defined $root) {
334 print "Must be run from the top-level dir. of a kernel tree\n";
339 my $emitted_corrupt = 0;
342 [A-Za-z_][A-Za-z\d_]*
343 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
345 our $Storage = qr{extern|static|asmlinkage};
359 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
360 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
361 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
362 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
363 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
365 # Notes to $Attribute:
366 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
388 ____cacheline_aligned|
389 ____cacheline_aligned_in_smp|
390 ____cacheline_internodealigned_in_smp|
394 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
395 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
396 our $Lval = qr{$Ident(?:$Member)*};
398 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
399 our $Binary = qr{(?i)0b[01]+$Int_type?};
400 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
401 our $Int = qr{[0-9]+$Int_type?};
402 our $Octal = qr{0[0-7]+$Int_type?};
403 our $String = qr{"[X\t]*"};
404 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
405 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
406 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
407 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
408 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
409 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
410 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
411 our $Arithmetic = qr{\+|-|\*|\/|%};
415 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
418 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
422 our $NonptrTypeMisordered;
423 our $NonptrTypeWithAttr;
427 our $DeclareMisordered;
429 our $NON_ASCII_UTF8 = qr{
430 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
431 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
432 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
433 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
434 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
435 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
436 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
440 [\x09\x0A\x0D\x20-\x7E] # ASCII
444 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
445 our $typeOtherOSTypedefs = qr{(?x:
446 u_(?:char|short|int|long) | # bsd
447 u(?:nchar|short|int|long) # sysv
449 our $typeKernelTypedefs = qr{(?x:
450 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
453 our $typeTypedefs = qr{(?x:
455 $typeOtherOSTypedefs\b|
456 $typeKernelTypedefs\b
459 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
461 our $logFunctions = qr{(?x:
462 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
463 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
465 WARN(?:_RATELIMIT|_ONCE|)|
470 seq_vprintf|seq_printf|seq_puts
473 our $signature_tags = qr{(?xi:
484 our @typeListMisordered = (
485 qr{char\s+(?:un)?signed},
486 qr{int\s+(?:(?:un)?signed\s+)?short\s},
487 qr{int\s+short(?:\s+(?:un)?signed)},
488 qr{short\s+int(?:\s+(?:un)?signed)},
489 qr{(?:un)?signed\s+int\s+short},
490 qr{short\s+(?:un)?signed},
491 qr{long\s+int\s+(?:un)?signed},
492 qr{int\s+long\s+(?:un)?signed},
493 qr{long\s+(?:un)?signed\s+int},
494 qr{int\s+(?:un)?signed\s+long},
495 qr{int\s+(?:un)?signed},
496 qr{int\s+long\s+long\s+(?:un)?signed},
497 qr{long\s+long\s+int\s+(?:un)?signed},
498 qr{long\s+long\s+(?:un)?signed\s+int},
499 qr{long\s+long\s+(?:un)?signed},
500 qr{long\s+(?:un)?signed},
505 qr{(?:(?:un)?signed\s+)?char},
506 qr{(?:(?:un)?signed\s+)?short\s+int},
507 qr{(?:(?:un)?signed\s+)?short},
508 qr{(?:(?:un)?signed\s+)?int},
509 qr{(?:(?:un)?signed\s+)?long\s+int},
510 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
511 qr{(?:(?:un)?signed\s+)?long\s+long},
512 qr{(?:(?:un)?signed\s+)?long},
521 qr{${Ident}_handler},
522 qr{${Ident}_handler_fn},
526 our $C90_int_types = qr{(?x:
527 long\s+long\s+int\s+(?:un)?signed|
528 long\s+long\s+(?:un)?signed\s+int|
529 long\s+long\s+(?:un)?signed|
530 (?:(?:un)?signed\s+)?long\s+long\s+int|
531 (?:(?:un)?signed\s+)?long\s+long|
532 int\s+long\s+long\s+(?:un)?signed|
533 int\s+(?:(?:un)?signed\s+)?long\s+long|
535 long\s+int\s+(?:un)?signed|
536 long\s+(?:un)?signed\s+int|
537 long\s+(?:un)?signed|
538 (?:(?:un)?signed\s+)?long\s+int|
539 (?:(?:un)?signed\s+)?long|
540 int\s+long\s+(?:un)?signed|
541 int\s+(?:(?:un)?signed\s+)?long|
544 (?:(?:un)?signed\s+)?int
547 our @typeListFile = ();
548 our @typeListWithAttr = (
550 qr{struct\s+$InitAttribute\s+$Ident},
551 qr{union\s+$InitAttribute\s+$Ident},
554 our @modifierList = (
557 our @modifierListFile = ();
559 our @mode_permission_funcs = (
561 ["module_param_(?:array|named|string)", 4],
562 ["module_param_array_named", 5],
563 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
564 ["proc_create(?:_data|)", 2],
565 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
566 ["IIO_DEV_ATTR_[A-Z_]+", 1],
567 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
568 ["SENSOR_TEMPLATE(?:_2|)", 3],
572 #Create a search pattern for all these functions to speed up a loop below
573 our $mode_perms_search = "";
574 foreach my $entry (@mode_permission_funcs) {
575 $mode_perms_search .= '|' if ($mode_perms_search ne "");
576 $mode_perms_search .= $entry->[0];
578 $mode_perms_search = "(?:${mode_perms_search})";
580 our $mode_perms_world_writable = qr{
588 our %mode_permission_string_types = (
607 #Create a search pattern for all these strings to speed up a loop below
608 our $mode_perms_string_search = "";
609 foreach my $entry (keys %mode_permission_string_types) {
610 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
611 $mode_perms_string_search .= $entry;
613 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
614 our $multi_mode_perms_string_search = qr{
615 ${single_mode_perms_string_search}
616 (?:\s*\|\s*${single_mode_perms_string_search})*
622 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
629 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
630 $curpos = pos($string);
633 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
635 $to |= $mode_permission_string_types{$match};
636 $val .= '\s*\|\s*' if ($val ne "");
640 $oval =~ s/^\s*\|\s*//;
641 $oval =~ s/\s*\|\s*$//;
642 return sprintf("%04o", $to);
645 our $allowed_asm_includes = qr{(?x:
651 # memory.h: ARM has a custom one
653 # Load common spelling mistakes and build regular expression list.
657 if (open(my $spelling, '<', $spelling_file)) {
658 while (<$spelling>) {
661 $line =~ s/\s*\n?$//g;
664 next if ($line =~ m/^\s*#/);
665 next if ($line =~ m/^\s*$/);
667 my ($suspect, $fix) = split(/\|\|/, $line);
669 $spelling_fix{$suspect} = $fix;
673 warn "No typos will be found - file '$spelling_file': $!\n";
677 if (open(my $spelling, '<', $codespellfile)) {
678 while (<$spelling>) {
681 $line =~ s/\s*\n?$//g;
684 next if ($line =~ m/^\s*#/);
685 next if ($line =~ m/^\s*$/);
686 next if ($line =~ m/, disabled/i);
690 my ($suspect, $fix) = split(/->/, $line);
692 $spelling_fix{$suspect} = $fix;
696 warn "No codespell typos will be found - file '$codespellfile': $!\n";
700 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
703 my ($wordsRef, $file) = @_;
705 if (open(my $words, '<', $file)) {
709 $line =~ s/\s*\n?$//g;
712 next if ($line =~ m/^\s*#/);
713 next if ($line =~ m/^\s*$/);
715 print("$file: '$line' invalid - ignored\n");
719 $$wordsRef .= '|' if ($$wordsRef ne "");
729 my $const_structs = "";
730 read_words(\$const_structs, $conststructsfile)
731 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
733 my $typeOtherTypedefs = "";
734 if (length($typedefsfile)) {
735 read_words(\$typeOtherTypedefs, $typedefsfile)
736 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
738 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
741 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
742 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
743 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
744 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
745 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
751 (?:$Modifier\s+|const\s+)*
753 (?:typeof|__typeof__)\s*\([^\)]*\)|
757 (?:\s+$Modifier|\s+const)*
759 $NonptrTypeMisordered = qr{
760 (?:$Modifier\s+|const\s+)*
764 (?:\s+$Modifier|\s+const)*
766 $NonptrTypeWithAttr = qr{
767 (?:$Modifier\s+|const\s+)*
769 (?:typeof|__typeof__)\s*\([^\)]*\)|
773 (?:\s+$Modifier|\s+const)*
777 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
778 (?:\s+$Inline|\s+$Modifier)*
780 $TypeMisordered = qr{
781 $NonptrTypeMisordered
782 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
783 (?:\s+$Inline|\s+$Modifier)*
785 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
786 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
790 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
792 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
793 # requires at least perl version v5.10.0
794 # Any use must be runtime checked with $^V
796 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
797 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
798 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
800 our $declaration_macros = qr{(?x:
801 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
802 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
803 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
804 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
809 return "" if (!defined($string));
811 while ($string =~ /^\s*\(.*\)\s*$/) {
812 $string =~ s@^\s*\(\s*@@;
813 $string =~ s@\s*\)\s*$@@;
816 $string =~ s@\s+@ @g;
821 sub seed_camelcase_file {
824 return if (!(-f $file));
828 open(my $include_file, '<', "$file")
829 or warn "$P: Can't read '$file' $!\n";
830 my $text = <$include_file>;
831 close($include_file);
833 my @lines = split('\n', $text);
835 foreach my $line (@lines) {
836 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
837 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
839 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
841 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
847 sub is_maintained_obsolete {
850 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
852 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
854 return $status =~ /obsolete/i;
857 sub is_SPDX_License_valid {
860 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
862 my $root_path = abs_path($root);
863 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
864 return 0 if ($status ne "");
868 my $camelcase_seeded = 0;
869 sub seed_camelcase_includes {
870 return if ($camelcase_seeded);
873 my $camelcase_cache = "";
874 my @include_files = ();
876 $camelcase_seeded = 1;
879 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
880 chomp $git_last_include_commit;
881 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
883 my $last_mod_date = 0;
884 $files = `find $root/include -name "*.h"`;
885 @include_files = split('\n', $files);
886 foreach my $file (@include_files) {
887 my $date = POSIX::strftime("%Y%m%d%H%M",
888 localtime((stat $file)[9]));
889 $last_mod_date = $date if ($last_mod_date < $date);
891 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
894 if ($camelcase_cache ne "" && -f $camelcase_cache) {
895 open(my $camelcase_file, '<', "$camelcase_cache")
896 or warn "$P: Can't read '$camelcase_cache' $!\n";
897 while (<$camelcase_file>) {
901 close($camelcase_file);
907 $files = `git ls-files "include/*.h"`;
908 @include_files = split('\n', $files);
911 foreach my $file (@include_files) {
912 seed_camelcase_file($file);
915 if ($camelcase_cache ne "") {
916 unlink glob ".checkpatch-camelcase.*";
917 open(my $camelcase_file, '>', "$camelcase_cache")
918 or warn "$P: Can't write '$camelcase_cache' $!\n";
919 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
920 print $camelcase_file ("$_\n");
922 close($camelcase_file);
926 sub git_commit_info {
927 my ($commit, $id, $desc) = @_;
929 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
931 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
932 $output =~ s/^\s*//gm;
933 my @lines = split("\n", $output);
935 return ($id, $desc) if ($#lines < 0);
937 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
938 # Maybe one day convert this block of bash into something that returns
939 # all matching commit ids, but it's very slow...
941 # echo "checking commits $1..."
942 # git rev-list --remotes | grep -i "^$1" |
943 # while read line ; do
944 # git log --format='%H %s' -1 $line |
945 # echo "commit $(cut -c 1-12,41-)"
947 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
950 $id = substr($lines[0], 0, 12);
951 $desc = substr($lines[0], 41);
957 $chk_signoff = 0 if ($file);
962 my @fixed_inserted = ();
963 my @fixed_deleted = ();
966 # If input is git commits, extract all commits from the commit expressions.
967 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
968 die "$P: No git repository found\n" if ($git && !-e ".git");
972 foreach my $commit_expr (@ARGV) {
974 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
975 $git_range = "-$2 $1";
976 } elsif ($commit_expr =~ m/\.\./) {
977 $git_range = "$commit_expr";
979 $git_range = "-1 $commit_expr";
981 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
982 foreach my $line (split(/\n/, $lines)) {
983 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
984 next if (!defined($1) || !defined($2));
987 unshift(@commits, $sha1);
988 $git_commits{$sha1} = $subject;
991 die "$P: no git commits after extraction!\n" if (@commits == 0);
996 for my $filename (@ARGV) {
999 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1000 die "$P: $filename: git format-patch failed - $!\n";
1002 open($FILE, '-|', "diff -u /dev/null $filename") ||
1003 die "$P: $filename: diff failed - $!\n";
1004 } elsif ($filename eq '-') {
1005 open($FILE, '<&STDIN');
1007 open($FILE, '<', "$filename") ||
1008 die "$P: $filename: open failed - $!\n";
1010 if ($filename eq '-') {
1011 $vname = 'Your patch';
1013 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1019 push(@rawlines, $_);
1023 if ($#ARGV > 0 && $quiet == 0) {
1024 print '-' x length($vname) . "\n";
1026 print '-' x length($vname) . "\n";
1029 if (!process($filename)) {
1035 @fixed_inserted = ();
1036 @fixed_deleted = ();
1038 @modifierListFile = ();
1044 hash_show_words(\%use_type, "Used");
1045 hash_show_words(\%ignore_type, "Ignored");
1047 if (!$perl_version_ok) {
1050 NOTE: perl $^V is not modern enough to detect all possible issues.
1051 An upgrade to at least perl $minimum_perl_version is suggested.
1057 NOTE: If any of the errors are false positives, please report
1058 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1065 sub top_of_kernel_tree {
1069 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1070 "README", "Documentation", "arch", "include", "drivers",
1071 "fs", "init", "ipc", "kernel", "lib", "scripts",
1074 foreach my $check (@tree_check) {
1075 if (! -e $root . '/' . $check) {
1083 my ($formatted_email) = @_;
1089 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1092 $comment = $3 if defined $3;
1093 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1095 $comment = $2 if defined $2;
1096 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1098 $comment = $2 if defined $2;
1099 $formatted_email =~ s/\Q$address\E.*$//;
1100 $name = $formatted_email;
1101 $name = trim($name);
1102 $name =~ s/^\"|\"$//g;
1103 # If there's a name left after stripping spaces and
1104 # leading quotes, and the address doesn't have both
1105 # leading and trailing angle brackets, the address
1107 # "joe smith joe@smith.com" bad
1108 # "joe smith <joe@smith.com" bad
1109 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1116 $name = trim($name);
1117 $name =~ s/^\"|\"$//g;
1118 $address = trim($address);
1119 $address =~ s/^\<|\>$//g;
1121 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1122 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1123 $name = "\"$name\"";
1126 return ($name, $address, $comment);
1130 my ($name, $address) = @_;
1132 my $formatted_email;
1134 $name = trim($name);
1135 $name =~ s/^\"|\"$//g;
1136 $address = trim($address);
1138 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1139 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1140 $name = "\"$name\"";
1143 if ("$name" eq "") {
1144 $formatted_email = "$address";
1146 $formatted_email = "$name <$address>";
1149 return $formatted_email;
1155 foreach my $path (split(/:/, $ENV{PATH})) {
1156 if (-e "$path/$bin") {
1157 return "$path/$bin";
1167 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1168 if (-e "$path/$conf") {
1169 return "$path/$conf";
1181 for my $c (split(//, $str)) {
1185 for (; ($n % 8) != 0; $n++) {
1197 (my $res = shift) =~ tr/\t/ /c;
1204 # Drop the diff line leader and expand tabs
1206 $line = expand_tabs($line);
1208 # Pick the indent from the front of the line.
1209 my ($white) = ($line =~ /^(\s*)/);
1211 return (length($line), length($white));
1214 my $sanitise_quote = '';
1216 sub sanitise_line_reset {
1217 my ($in_comment) = @_;
1220 $sanitise_quote = '*/';
1222 $sanitise_quote = '';
1235 # Always copy over the diff marker.
1236 $res = substr($line, 0, 1);
1238 for ($off = 1; $off < length($line); $off++) {
1239 $c = substr($line, $off, 1);
1241 # Comments we are whacking completely including the begin
1242 # and end, all to $;.
1243 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1244 $sanitise_quote = '*/';
1246 substr($res, $off, 2, "$;$;");
1250 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1251 $sanitise_quote = '';
1252 substr($res, $off, 2, "$;$;");
1256 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1257 $sanitise_quote = '//';
1259 substr($res, $off, 2, $sanitise_quote);
1264 # A \ in a string means ignore the next character.
1265 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1267 substr($res, $off, 2, 'XX');
1272 if ($c eq "'" || $c eq '"') {
1273 if ($sanitise_quote eq '') {
1274 $sanitise_quote = $c;
1276 substr($res, $off, 1, $c);
1278 } elsif ($sanitise_quote eq $c) {
1279 $sanitise_quote = '';
1283 #print "c<$c> SQ<$sanitise_quote>\n";
1284 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1285 substr($res, $off, 1, $;);
1286 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1287 substr($res, $off, 1, $;);
1288 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1289 substr($res, $off, 1, 'X');
1291 substr($res, $off, 1, $c);
1295 if ($sanitise_quote eq '//') {
1296 $sanitise_quote = '';
1299 # The pathname on a #include may be surrounded by '<' and '>'.
1300 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1301 my $clean = 'X' x length($1);
1302 $res =~ s@\<.*\>@<$clean>@;
1304 # The whole of a #error is a string.
1305 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1306 my $clean = 'X' x length($1);
1307 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1310 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1312 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1318 sub get_quoted_string {
1319 my ($line, $rawline) = @_;
1321 return "" if (!defined($line) || !defined($rawline));
1322 return "" if ($line !~ m/($String)/g);
1323 return substr($rawline, $-[0], $+[0] - $-[0]);
1326 sub ctx_statement_block {
1327 my ($linenr, $remain, $off) = @_;
1328 my $line = $linenr - 1;
1331 my $coff = $off - 1;
1345 @stack = (['', 0]) if ($#stack == -1);
1347 #warn "CSB: blk<$blk> remain<$remain>\n";
1348 # If we are about to drop off the end, pull in more
1351 for (; $remain > 0; $line++) {
1352 last if (!defined $lines[$line]);
1353 next if ($lines[$line] =~ /^-/);
1356 $blk .= $lines[$line] . "\n";
1357 $len = length($blk);
1361 # Bail if there is no further context.
1362 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1366 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1372 $c = substr($blk, $off, 1);
1373 $remainder = substr($blk, $off);
1375 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1377 # Handle nested #if/#else.
1378 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1379 push(@stack, [ $type, $level ]);
1380 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1381 ($type, $level) = @{$stack[$#stack - 1]};
1382 } elsif ($remainder =~ /^#\s*endif\b/) {
1383 ($type, $level) = @{pop(@stack)};
1386 # Statement ends at the ';' or a close '}' at the
1388 if ($level == 0 && $c eq ';') {
1392 # An else is really a conditional as long as its not else if
1393 if ($level == 0 && $coff_set == 0 &&
1394 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1395 $remainder =~ /^(else)(?:\s|{)/ &&
1396 $remainder !~ /^else\s+if\b/) {
1397 $coff = $off + length($1) - 1;
1399 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1400 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1403 if (($type eq '' || $type eq '(') && $c eq '(') {
1407 if ($type eq '(' && $c eq ')') {
1409 $type = ($level != 0)? '(' : '';
1411 if ($level == 0 && $coff < $soff) {
1414 #warn "CSB: mark coff<$coff>\n";
1417 if (($type eq '' || $type eq '{') && $c eq '{') {
1421 if ($type eq '{' && $c eq '}') {
1423 $type = ($level != 0)? '{' : '';
1426 if (substr($blk, $off + 1, 1) eq ';') {
1432 # Preprocessor commands end at the newline unless escaped.
1433 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1441 # We are truly at the end, so shuffle to the next line.
1448 my $statement = substr($blk, $soff, $off - $soff + 1);
1449 my $condition = substr($blk, $soff, $coff - $soff + 1);
1451 #warn "STATEMENT<$statement>\n";
1452 #warn "CONDITION<$condition>\n";
1454 #print "coff<$coff> soff<$off> loff<$loff>\n";
1456 return ($statement, $condition,
1457 $line, $remain + 1, $off - $loff + 1, $level);
1460 sub statement_lines {
1463 # Strip the diff line prefixes and rip blank lines at start and end.
1464 $stmt =~ s/(^|\n)./$1/g;
1468 my @stmt_lines = ($stmt =~ /\n/g);
1470 return $#stmt_lines + 2;
1473 sub statement_rawlines {
1476 my @stmt_lines = ($stmt =~ /\n/g);
1478 return $#stmt_lines + 2;
1481 sub statement_block_size {
1484 $stmt =~ s/(^|\n)./$1/g;
1490 my @stmt_lines = ($stmt =~ /\n/g);
1491 my @stmt_statements = ($stmt =~ /;/g);
1493 my $stmt_lines = $#stmt_lines + 2;
1494 my $stmt_statements = $#stmt_statements + 1;
1496 if ($stmt_lines > $stmt_statements) {
1499 return $stmt_statements;
1503 sub ctx_statement_full {
1504 my ($linenr, $remain, $off) = @_;
1505 my ($statement, $condition, $level);
1509 # Grab the first conditional/block pair.
1510 ($statement, $condition, $linenr, $remain, $off, $level) =
1511 ctx_statement_block($linenr, $remain, $off);
1512 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1513 push(@chunks, [ $condition, $statement ]);
1514 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1515 return ($level, $linenr, @chunks);
1518 # Pull in the following conditional/block pairs and see if they
1519 # could continue the statement.
1521 ($statement, $condition, $linenr, $remain, $off, $level) =
1522 ctx_statement_block($linenr, $remain, $off);
1523 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1524 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1526 push(@chunks, [ $condition, $statement ]);
1529 return ($level, $linenr, @chunks);
1533 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1535 my $start = $linenr - 1;
1542 my @stack = ($level);
1543 for ($line = $start; $remain > 0; $line++) {
1544 next if ($rawlines[$line] =~ /^-/);
1547 $blk .= $rawlines[$line];
1549 # Handle nested #if/#else.
1550 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1551 push(@stack, $level);
1552 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1553 $level = $stack[$#stack - 1];
1554 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1555 $level = pop(@stack);
1558 foreach my $c (split(//, $lines[$line])) {
1559 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1565 if ($c eq $close && $level > 0) {
1567 last if ($level == 0);
1568 } elsif ($c eq $open) {
1573 if (!$outer || $level <= 1) {
1574 push(@res, $rawlines[$line]);
1577 last if ($level == 0);
1580 return ($level, @res);
1582 sub ctx_block_outer {
1583 my ($linenr, $remain) = @_;
1585 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1589 my ($linenr, $remain) = @_;
1591 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1595 my ($linenr, $remain, $off) = @_;
1597 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1600 sub ctx_block_level {
1601 my ($linenr, $remain) = @_;
1603 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1605 sub ctx_statement_level {
1606 my ($linenr, $remain, $off) = @_;
1608 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1611 sub ctx_locate_comment {
1612 my ($first_line, $end_line) = @_;
1614 # Catch a comment on the end of the line itself.
1615 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1616 return $current_comment if (defined $current_comment);
1618 # Look through the context and try and figure out if there is a
1621 $current_comment = '';
1622 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1623 my $line = $rawlines[$linenr - 1];
1625 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1628 if ($line =~ m@/\*@) {
1631 if (!$in_comment && $current_comment ne '') {
1632 $current_comment = '';
1634 $current_comment .= $line . "\n" if ($in_comment);
1635 if ($line =~ m@\*/@) {
1640 chomp($current_comment);
1641 return($current_comment);
1643 sub ctx_has_comment {
1644 my ($first_line, $end_line) = @_;
1645 my $cmt = ctx_locate_comment($first_line, $end_line);
1647 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1648 ##print "CMMT: $cmt\n";
1650 return ($cmt ne '');
1654 my ($linenr, $cnt) = @_;
1656 my $offset = $linenr - 1;
1661 $line = $rawlines[$offset++];
1662 next if (defined($line) && $line =~ /^-/);
1670 my ($linenr, $lc) = @_;
1672 my $stat_real = raw_line($linenr, 0);
1673 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1674 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1681 my ($linenr, $cnt, $here) = @_;
1683 my $herectx = $here . "\n";
1684 for (my $n = 0; $n < $cnt; $n++) {
1685 $herectx .= raw_line($linenr, $n) . "\n";
1696 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1699 $coded = sprintf("^%c", unpack('C', $2) + 64);
1708 my $av_preprocessor = 0;
1713 sub annotate_reset {
1714 $av_preprocessor = 0;
1716 @av_paren_type = ('E');
1717 $av_pend_colon = 'O';
1720 sub annotate_values {
1721 my ($stream, $type) = @_;
1724 my $var = '_' x length($stream);
1727 print "$stream\n" if ($dbg_values > 1);
1729 while (length($cur)) {
1730 @av_paren_type = ('E') if ($#av_paren_type < 0);
1731 print " <" . join('', @av_paren_type) .
1732 "> <$type> <$av_pending>" if ($dbg_values > 1);
1733 if ($cur =~ /^(\s+)/o) {
1734 print "WS($1)\n" if ($dbg_values > 1);
1735 if ($1 =~ /\n/ && $av_preprocessor) {
1736 $type = pop(@av_paren_type);
1737 $av_preprocessor = 0;
1740 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1741 print "CAST($1)\n" if ($dbg_values > 1);
1742 push(@av_paren_type, $type);
1745 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1746 print "DECLARE($1)\n" if ($dbg_values > 1);
1749 } elsif ($cur =~ /^($Modifier)\s*/) {
1750 print "MODIFIER($1)\n" if ($dbg_values > 1);
1753 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1754 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1755 $av_preprocessor = 1;
1756 push(@av_paren_type, $type);
1762 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1763 print "UNDEF($1)\n" if ($dbg_values > 1);
1764 $av_preprocessor = 1;
1765 push(@av_paren_type, $type);
1767 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1768 print "PRE_START($1)\n" if ($dbg_values > 1);
1769 $av_preprocessor = 1;
1771 push(@av_paren_type, $type);
1772 push(@av_paren_type, $type);
1775 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1776 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1777 $av_preprocessor = 1;
1779 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1783 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1784 print "PRE_END($1)\n" if ($dbg_values > 1);
1786 $av_preprocessor = 1;
1788 # Assume all arms of the conditional end as this
1789 # one does, and continue as if the #endif was not here.
1790 pop(@av_paren_type);
1791 push(@av_paren_type, $type);
1794 } elsif ($cur =~ /^(\\\n)/o) {
1795 print "PRECONT($1)\n" if ($dbg_values > 1);
1797 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1798 print "ATTR($1)\n" if ($dbg_values > 1);
1799 $av_pending = $type;
1802 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1803 print "SIZEOF($1)\n" if ($dbg_values > 1);
1809 } elsif ($cur =~ /^(if|while|for)\b/o) {
1810 print "COND($1)\n" if ($dbg_values > 1);
1814 } elsif ($cur =~/^(case)/o) {
1815 print "CASE($1)\n" if ($dbg_values > 1);
1816 $av_pend_colon = 'C';
1819 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1820 print "KEYWORD($1)\n" if ($dbg_values > 1);
1823 } elsif ($cur =~ /^(\()/o) {
1824 print "PAREN('$1')\n" if ($dbg_values > 1);
1825 push(@av_paren_type, $av_pending);
1829 } elsif ($cur =~ /^(\))/o) {
1830 my $new_type = pop(@av_paren_type);
1831 if ($new_type ne '_') {
1833 print "PAREN('$1') -> $type\n"
1834 if ($dbg_values > 1);
1836 print "PAREN('$1')\n" if ($dbg_values > 1);
1839 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1840 print "FUNC($1)\n" if ($dbg_values > 1);
1844 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1845 if (defined $2 && $type eq 'C' || $type eq 'T') {
1846 $av_pend_colon = 'B';
1847 } elsif ($type eq 'E') {
1848 $av_pend_colon = 'L';
1850 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1853 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1854 print "IDENT($1)\n" if ($dbg_values > 1);
1857 } elsif ($cur =~ /^($Assignment)/o) {
1858 print "ASSIGN($1)\n" if ($dbg_values > 1);
1861 } elsif ($cur =~/^(;|{|})/) {
1862 print "END($1)\n" if ($dbg_values > 1);
1864 $av_pend_colon = 'O';
1866 } elsif ($cur =~/^(,)/) {
1867 print "COMMA($1)\n" if ($dbg_values > 1);
1870 } elsif ($cur =~ /^(\?)/o) {
1871 print "QUESTION($1)\n" if ($dbg_values > 1);
1874 } elsif ($cur =~ /^(:)/o) {
1875 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1877 substr($var, length($res), 1, $av_pend_colon);
1878 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1883 $av_pend_colon = 'O';
1885 } elsif ($cur =~ /^(\[)/o) {
1886 print "CLOSE($1)\n" if ($dbg_values > 1);
1889 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1892 print "OPV($1)\n" if ($dbg_values > 1);
1899 substr($var, length($res), 1, $variant);
1902 } elsif ($cur =~ /^($Operators)/o) {
1903 print "OP($1)\n" if ($dbg_values > 1);
1904 if ($1 ne '++' && $1 ne '--') {
1908 } elsif ($cur =~ /(^.)/o) {
1909 print "C($1)\n" if ($dbg_values > 1);
1912 $cur = substr($cur, length($1));
1913 $res .= $type x length($1);
1917 return ($res, $var);
1921 my ($possible, $line) = @_;
1922 my $notPermitted = qr{(?:
1939 ^(?:typedef|struct|enum)\b
1941 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1942 if ($possible !~ $notPermitted) {
1943 # Check for modifiers.
1944 $possible =~ s/\s*$Storage\s*//g;
1945 $possible =~ s/\s*$Sparse\s*//g;
1946 if ($possible =~ /^\s*$/) {
1948 } elsif ($possible =~ /\s/) {
1949 $possible =~ s/\s*$Type\s*//g;
1950 for my $modifier (split(' ', $possible)) {
1951 if ($modifier !~ $notPermitted) {
1952 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1953 push(@modifierListFile, $modifier);
1958 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1959 push(@typeListFile, $possible);
1963 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1972 $type =~ tr/[a-z]/[A-Z]/;
1974 return defined $use_type{$type} if (scalar keys %use_type > 0);
1976 return !defined $ignore_type{$type};
1980 my ($level, $type, $msg) = @_;
1982 if (!show_type($type) ||
1983 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1988 if ($level eq 'ERROR') {
1990 } elsif ($level eq 'WARNING') {
1996 $output .= $prefix . $level . ':';
1998 $output .= BLUE if ($color);
1999 $output .= "$type:";
2001 $output .= RESET if ($color);
2002 $output .= ' ' . $msg . "\n";
2005 my @lines = split("\n", $output, -1);
2006 splice(@lines, 1, 1);
2007 $output = join("\n", @lines);
2009 $output = (split('\n', $output))[0] . "\n" if ($terse);
2011 push(our @report, $output);
2020 sub fixup_current_range {
2021 my ($lineRef, $offset, $length) = @_;
2023 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2026 my $no = $o + $offset;
2027 my $nl = $l + $length;
2028 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2032 sub fix_inserted_deleted_lines {
2033 my ($linesRef, $insertedRef, $deletedRef) = @_;
2035 my $range_last_linenr = 0;
2036 my $delta_offset = 0;
2041 my $next_insert = 0;
2042 my $next_delete = 0;
2046 my $inserted = @{$insertedRef}[$next_insert++];
2047 my $deleted = @{$deletedRef}[$next_delete++];
2049 foreach my $old_line (@{$linesRef}) {
2051 my $line = $old_line; #don't modify the array
2052 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2054 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2055 $range_last_linenr = $new_linenr;
2056 fixup_current_range(\$line, $delta_offset, 0);
2059 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2060 $deleted = @{$deletedRef}[$next_delete++];
2062 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2065 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2066 push(@lines, ${$inserted}{'LINE'});
2067 $inserted = @{$insertedRef}[$next_insert++];
2069 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2073 push(@lines, $line);
2083 sub fix_insert_line {
2084 my ($linenr, $line) = @_;
2090 push(@fixed_inserted, $inserted);
2093 sub fix_delete_line {
2094 my ($linenr, $line) = @_;
2101 push(@fixed_deleted, $deleted);
2105 my ($type, $msg) = @_;
2107 if (report("ERROR", $type, $msg)) {
2115 my ($type, $msg) = @_;
2117 if (report("WARNING", $type, $msg)) {
2125 my ($type, $msg) = @_;
2127 if ($check && report("CHECK", $type, $msg)) {
2135 sub check_absolute_file {
2136 my ($absolute, $herecurr) = @_;
2137 my $file = $absolute;
2139 ##print "absolute<$absolute>\n";
2141 # See if any suffix of this path is a path within the tree.
2142 while ($file =~ s@^[^/]*/@@) {
2143 if (-f "$root/$file") {
2144 ##print "file<$file>\n";
2152 # It is, so see if the prefix is acceptable.
2153 my $prefix = $absolute;
2154 substr($prefix, -length($file)) = '';
2156 ##print "prefix<$prefix>\n";
2157 if ($prefix ne ".../") {
2158 WARN("USE_RELATIVE_PATH",
2159 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2166 $string =~ s/^\s+|\s+$//g;
2174 $string =~ s/^\s+//;
2182 $string =~ s/\s+$//;
2187 sub string_find_replace {
2188 my ($string, $find, $replace) = @_;
2190 $string =~ s/$find/$replace/g;
2198 my $source_indent = 8;
2199 my $max_spaces_before_tab = $source_indent - 1;
2200 my $spaces_to_tab = " " x $source_indent;
2202 #convert leading spaces to tabs
2203 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2204 #Remove spaces before a tab
2205 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2210 sub pos_last_openparen {
2215 my $opens = $line =~ tr/\(/\(/;
2216 my $closes = $line =~ tr/\)/\)/;
2218 my $last_openparen = 0;
2220 if (($opens == 0) || ($closes >= $opens)) {
2224 my $len = length($line);
2226 for ($pos = 0; $pos < $len; $pos++) {
2227 my $string = substr($line, $pos);
2228 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2229 $pos += length($1) - 1;
2230 } elsif (substr($line, $pos, 1) eq '(') {
2231 $last_openparen = $pos;
2232 } elsif (index($string, '(') == -1) {
2237 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2241 my $filename = shift;
2247 my $stashrawline="";
2257 my $authorsignoff = 0;
2259 my $is_binding_patch = -1;
2260 my $in_header_lines = $file ? 0 : 1;
2261 my $in_commit_log = 0; #Scanning lines before patch
2262 my $has_commit_log = 0; #Encountered lines before patch
2263 my $commit_log_lines = 0; #Number of commit log lines
2264 my $commit_log_possible_stack_dump = 0;
2265 my $commit_log_long_line = 0;
2266 my $commit_log_has_diff = 0;
2267 my $reported_maintainer_file = 0;
2268 my $non_utf8_charset = 0;
2270 my $last_blank_line = 0;
2271 my $last_coalesced_string_linenr = -1;
2279 # Trace the real file/line as we go.
2284 my $context_function; #undef'd unless there's a known function
2286 my $comment_edge = 0;
2290 my $prev_values = 'E';
2293 my %suppress_ifbraces;
2294 my %suppress_whiletrailers;
2295 my %suppress_export;
2296 my $suppress_statement = 0;
2298 my %signatures = ();
2300 # Pre-scan the patch sanitizing the lines.
2301 # Pre-scan the patch looking for any __setup documentation.
2303 my @setup_docs = ();
2306 my $camelcase_file_seeded = 0;
2308 my $checklicenseline = 1;
2310 sanitise_line_reset();
2312 foreach my $rawline (@rawlines) {
2316 push(@fixed, $rawline) if ($fix);
2318 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2320 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2325 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2334 # Guestimate if this is a continuing comment. Run
2335 # the context looking for a comment "edge". If this
2336 # edge is a close comment then we must be in a comment
2340 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2341 next if (defined $rawlines[$ln - 1] &&
2342 $rawlines[$ln - 1] =~ /^-/);
2344 #print "RAW<$rawlines[$ln - 1]>\n";
2345 last if (!defined $rawlines[$ln - 1]);
2346 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2347 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2352 if (defined $edge && $edge eq '*/') {
2356 # Guestimate if this is a continuing comment. If this
2357 # is the start of a diff block and this line starts
2358 # ' *' then it is very likely a comment.
2359 if (!defined $edge &&
2360 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2365 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2366 sanitise_line_reset($in_comment);
2368 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2369 # Standardise the strings and chars within the input to
2370 # simplify matching -- only bother with positive lines.
2371 $line = sanitise_line($rawline);
2373 push(@lines, $line);
2376 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2381 #print "==>$rawline\n";
2382 #print "-->$line\n";
2384 if ($setup_docs && $line =~ /^\+/) {
2385 push(@setup_docs, $line);
2394 foreach my $line (@lines) {
2397 my $sline = $line; #copy of $line
2398 $sline =~ s/$;/ /g; #with comments as spaces
2400 my $rawline = $rawlines[$linenr - 1];
2402 # check if it's a mode change, rename or start of a patch
2403 if (!$in_commit_log &&
2404 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2405 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2406 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2410 #extract the line range in the file after the patch is applied
2411 if (!$in_commit_log &&
2412 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2415 $first_line = $linenr + 1;
2425 %suppress_ifbraces = ();
2426 %suppress_whiletrailers = ();
2427 %suppress_export = ();
2428 $suppress_statement = 0;
2429 if ($context =~ /\b(\w+)\s*\(/) {
2430 $context_function = $1;
2432 undef $context_function;
2436 # track the line number as we move through the hunk, note that
2437 # new versions of GNU diff omit the leading space on completely
2438 # blank context lines so we need to count that too.
2439 } elsif ($line =~ /^( |\+|$)/) {
2441 $realcnt-- if ($realcnt != 0);
2443 # Measure the line length and indent.
2444 ($length, $indent) = line_stats($rawline);
2446 # Track the previous line.
2447 ($prevline, $stashline) = ($stashline, $line);
2448 ($previndent, $stashindent) = ($stashindent, $indent);
2449 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2451 #warn "line<$line>\n";
2453 } elsif ($realcnt == 1) {
2457 my $hunk_line = ($realcnt != 0);
2459 $here = "#$linenr: " if (!$file);
2460 $here = "#$realline: " if ($file);
2463 # extract the filename as it passes
2464 if ($line =~ /^diff --git.*?(\S+)$/) {
2466 $realfile =~ s@^([^/]*)/@@ if (!$file);
2469 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2471 $realfile =~ s@^([^/]*)/@@ if (!$file);
2475 if (!$file && $tree && $p1_prefix ne '' &&
2476 -e "$root/$p1_prefix") {
2477 WARN("PATCH_PREFIX",
2478 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2481 if ($realfile =~ m@^include/asm/@) {
2482 ERROR("MODIFIED_INCLUDE_ASM",
2483 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2488 #make up the handle for any error we report on this line
2490 $prefix = "$realfile:$realline: "
2493 $prefix = "$filename:$realline: ";
2495 $prefix = "$filename:$linenr: ";
2500 if (is_maintained_obsolete($realfile)) {
2502 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2504 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2507 $check = $check_orig;
2509 $checklicenseline = 1;
2511 if ($realfile !~ /^MAINTAINERS/) {
2512 my $last_binding_patch = $is_binding_patch;
2514 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2516 if (($last_binding_patch != -1) &&
2517 ($last_binding_patch ^ $is_binding_patch)) {
2518 WARN("DT_SPLIT_BINDING_PATCH",
2519 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2526 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2528 my $hereline = "$here\n$rawline\n";
2529 my $herecurr = "$here\n$rawline\n";
2530 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2532 $cnt_lines++ if ($realcnt != 0);
2534 # Verify the existence of a commit log if appropriate
2535 # 2 is used because a $signature is counted in $commit_log_lines
2536 if ($in_commit_log) {
2537 if ($line !~ /^\s*$/) {
2538 $commit_log_lines++; #could be a $signature
2540 } elsif ($has_commit_log && $commit_log_lines < 2) {
2541 WARN("COMMIT_MESSAGE",
2542 "Missing commit description - Add an appropriate one\n");
2543 $commit_log_lines = 2; #warn only once
2546 # Check if the commit log has what seems like a diff which can confuse patch
2547 if ($in_commit_log && !$commit_log_has_diff &&
2548 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2549 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2550 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2551 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2552 ERROR("DIFF_IN_COMMIT_MSG",
2553 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2554 $commit_log_has_diff = 1;
2557 # Check for incorrect file permissions
2558 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2559 my $permhere = $here . "FILE: $realfile\n";
2560 if ($realfile !~ m@scripts/@ &&
2561 $realfile !~ /\.(py|pl|awk|sh)$/) {
2562 ERROR("EXECUTE_PERMISSIONS",
2563 "do not set execute permissions for source files\n" . $permhere);
2567 # Check the patch for a From:
2568 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2570 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2574 # Check the patch for a signoff:
2575 if ($line =~ /^\s*signed-off-by:/i) {
2578 if ($author ne '') {
2581 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2587 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2588 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2589 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2590 $reported_maintainer_file = 1;
2593 # Check signature styles
2594 if (!$in_header_lines &&
2595 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2596 my $space_before = $1;
2598 my $space_after = $3;
2600 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2602 if ($sign_off !~ /$signature_tags/) {
2603 WARN("BAD_SIGN_OFF",
2604 "Non-standard signature: $sign_off\n" . $herecurr);
2606 if (defined $space_before && $space_before ne "") {
2607 if (WARN("BAD_SIGN_OFF",
2608 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2610 $fixed[$fixlinenr] =
2611 "$ucfirst_sign_off $email";
2614 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2615 if (WARN("BAD_SIGN_OFF",
2616 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2618 $fixed[$fixlinenr] =
2619 "$ucfirst_sign_off $email";
2623 if (!defined $space_after || $space_after ne " ") {
2624 if (WARN("BAD_SIGN_OFF",
2625 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2627 $fixed[$fixlinenr] =
2628 "$ucfirst_sign_off $email";
2632 my ($email_name, $email_address, $comment) = parse_email($email);
2633 my $suggested_email = format_email(($email_name, $email_address));
2634 if ($suggested_email eq "") {
2635 ERROR("BAD_SIGN_OFF",
2636 "Unrecognized email address: '$email'\n" . $herecurr);
2638 my $dequoted = $suggested_email;
2639 $dequoted =~ s/^"//;
2640 $dequoted =~ s/" </ </;
2641 # Don't force email to have quotes
2642 # Allow just an angle bracketed address
2643 if ("$dequoted$comment" ne $email &&
2644 "<$email_address>$comment" ne $email &&
2645 "$suggested_email$comment" ne $email) {
2646 WARN("BAD_SIGN_OFF",
2647 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2651 # Check for duplicate signatures
2652 my $sig_nospace = $line;
2653 $sig_nospace =~ s/\s//g;
2654 $sig_nospace = lc($sig_nospace);
2655 if (defined $signatures{$sig_nospace}) {
2656 WARN("BAD_SIGN_OFF",
2657 "Duplicate signature\n" . $herecurr);
2659 $signatures{$sig_nospace} = 1;
2663 # Check email subject for common tools that don't need to be mentioned
2664 if ($in_header_lines &&
2665 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2666 WARN("EMAIL_SUBJECT",
2667 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2670 # Check for unwanted Gerrit info
2671 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2672 ERROR("GERRIT_CHANGE_ID",
2673 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2676 # Check if the commit log is in a possible stack dump
2677 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2678 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2679 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2681 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2682 # stack dump address
2683 $commit_log_possible_stack_dump = 1;
2686 # Check for line lengths > 75 in commit log, warn once
2687 if ($in_commit_log && !$commit_log_long_line &&
2688 length($line) > 75 &&
2689 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2690 # file delta changes
2691 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2693 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2694 # A Fixes: or Link: line
2695 $commit_log_possible_stack_dump)) {
2696 WARN("COMMIT_LOG_LONG_LINE",
2697 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2698 $commit_log_long_line = 1;
2701 # Reset possible stack dump if a blank line is found
2702 if ($in_commit_log && $commit_log_possible_stack_dump &&
2704 $commit_log_possible_stack_dump = 0;
2707 # Check for git id commit length and improperly formed commit descriptions
2708 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2709 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2710 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2711 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2712 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2713 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2714 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2715 my $init_char = "c";
2716 my $orig_commit = "";
2723 my $id = '0123456789ab';
2724 my $orig_desc = "commit description";
2725 my $description = "";
2727 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2729 $orig_commit = lc($2);
2730 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2731 $orig_commit = lc($1);
2734 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2735 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2736 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2737 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2738 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2741 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2742 defined $rawlines[$linenr] &&
2743 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2746 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2747 defined $rawlines[$linenr] &&
2748 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2749 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2751 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2752 $orig_desc .= " " . $1;
2756 ($id, $description) = git_commit_info($orig_commit,
2760 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2761 ERROR("GIT_COMMIT_ID",
2762 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2766 # Check for added, moved or deleted files
2767 if (!$reported_maintainer_file && !$in_commit_log &&
2768 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2769 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2770 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2771 (defined($1) || defined($2))))) {
2773 $reported_maintainer_file = 1;
2774 WARN("FILE_PATH_CHANGES",
2775 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2778 # Check for wrappage within a valid hunk of the file
2779 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2780 ERROR("CORRUPTED_PATCH",
2781 "patch seems to be corrupt (line wrapped?)\n" .
2782 $herecurr) if (!$emitted_corrupt++);
2785 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2786 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2787 $rawline !~ m/^$UTF8*$/) {
2788 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2790 my $blank = copy_spacing($rawline);
2791 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2792 my $hereptr = "$hereline$ptr\n";
2795 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2798 # Check if it's the start of a commit log
2799 # (not a header line and we haven't seen the patch filename)
2800 if ($in_header_lines && $realfile =~ /^$/ &&
2801 !($rawline =~ /^\s+(?:\S|$)/ ||
2802 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2803 $in_header_lines = 0;
2805 $has_commit_log = 1;
2808 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2809 # declined it, i.e defined some charset where it is missing.
2810 if ($in_header_lines &&
2811 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2813 $non_utf8_charset = 1;
2816 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2817 $rawline =~ /$NON_ASCII_UTF8/) {
2818 WARN("UTF8_BEFORE_PATCH",
2819 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2822 # Check for absolute kernel paths in commit message
2823 if ($tree && $in_commit_log) {
2824 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2827 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2828 check_absolute_file($1, $herecurr)) {
2831 check_absolute_file($file, $herecurr);
2836 # Check for various typo / spelling mistakes
2837 if (defined($misspellings) &&
2838 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2839 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2841 my $typo_fix = $spelling_fix{lc($typo)};
2842 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2843 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2844 my $msg_level = \&WARN;
2845 $msg_level = \&CHK if ($file);
2846 if (&{$msg_level}("TYPO_SPELLING",
2847 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2849 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2854 # ignore non-hunk lines and lines being removed
2855 next if (!$hunk_line || $line =~ /^-/);
2857 #trailing whitespace
2858 if ($line =~ /^\+.*\015/) {
2859 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2860 if (ERROR("DOS_LINE_ENDINGS",
2861 "DOS line endings\n" . $herevet) &&
2863 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2865 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2866 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2867 if (ERROR("TRAILING_WHITESPACE",
2868 "trailing whitespace\n" . $herevet) &&
2870 $fixed[$fixlinenr] =~ s/\s+$//;
2876 # Check for FSF mailing addresses.
2877 if ($rawline =~ /\bwrite to the Free/i ||
2878 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2879 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2880 $rawline =~ /\b51\s+Franklin\s+St/i) {
2881 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2882 my $msg_level = \&ERROR;
2883 $msg_level = \&CHK if ($file);
2884 &{$msg_level}("FSF_MAILING_ADDRESS",
2885 "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)
2888 # check for Kconfig help text having a real description
2889 # Only applies when adding the entry originally, after that we do not have
2890 # sufficient context to determine whether it is indeed long enough.
2891 if ($realfile =~ /Kconfig/ &&
2892 # 'choice' is usually the last thing on the line (though
2893 # Kconfig supports named choices), so use a word boundary
2894 # (\b) rather than a whitespace character (\s)
2895 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2898 my $ln = $linenr + 1;
2902 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2903 $f = $lines[$ln - 1];
2904 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2905 $is_end = $lines[$ln - 1] =~ /^\+/;
2907 next if ($f =~ /^-/);
2908 last if (!$file && $f =~ /^\@\@/);
2910 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2912 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2913 if ($lines[$ln - 1] =~ "---help---") {
2914 WARN("CONFIG_DESCRIPTION",
2915 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2923 next if ($f =~ /^$/);
2925 # This only checks context lines in the patch
2926 # and so hopefully shouldn't trigger false
2927 # positives, even though some of these are
2928 # common words in help texts
2929 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2930 if|endif|menu|endmenu|source)\b/x) {
2936 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2937 WARN("CONFIG_DESCRIPTION",
2938 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2940 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2943 # check for MAINTAINERS entries that don't have the right form
2944 if ($realfile =~ /^MAINTAINERS$/ &&
2945 $rawline =~ /^\+[A-Z]:/ &&
2946 $rawline !~ /^\+[A-Z]:\t\S/) {
2947 if (WARN("MAINTAINERS_STYLE",
2948 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2950 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2954 # discourage the use of boolean for type definition attributes of Kconfig options
2955 if ($realfile =~ /Kconfig/ &&
2956 $line =~ /^\+\s*\bboolean\b/) {
2957 WARN("CONFIG_TYPE_BOOLEAN",
2958 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2961 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2962 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2965 'EXTRA_AFLAGS' => 'asflags-y',
2966 'EXTRA_CFLAGS' => 'ccflags-y',
2967 'EXTRA_CPPFLAGS' => 'cppflags-y',
2968 'EXTRA_LDFLAGS' => 'ldflags-y',
2971 WARN("DEPRECATED_VARIABLE",
2972 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2975 # check for DT compatible documentation
2976 if (defined $root &&
2977 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2978 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2980 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2982 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2983 my $vp_file = $dt_path . "vendor-prefixes.txt";
2985 foreach my $compat (@compats) {
2986 my $compat2 = $compat;
2987 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2988 my $compat3 = $compat;
2989 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2990 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2992 WARN("UNDOCUMENTED_DT_STRING",
2993 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2996 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2998 `grep -Eq "^$vendor\\b" $vp_file`;
3000 WARN("UNDOCUMENTED_DT_STRING",
3001 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3006 # check for using SPDX license tag at beginning of files
3007 if ($realline == $checklicenseline) {
3008 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3009 $checklicenseline = 2;
3010 } elsif ($rawline =~ /^\+/) {
3012 if ($realfile =~ /\.(h|s|S)$/) {
3014 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3016 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3018 } elsif ($realfile =~ /\.rst$/) {
3022 if ($comment !~ /^$/ &&
3023 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3024 WARN("SPDX_LICENSE_TAG",
3025 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3026 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3027 my $spdx_license = $1;
3028 if (!is_SPDX_License_valid($spdx_license)) {
3029 WARN("SPDX_LICENSE_TAG",
3030 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3036 # check we are in a valid source file if not then ignore this hunk
3037 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3039 # line length limit (with some exclusions)
3041 # There are a few types of lines that may extend beyond $max_line_length:
3042 # logging functions like pr_info that end in a string
3043 # lines with a single string
3044 # #defines that are a single string
3045 # lines with an RFC3986 like URL
3047 # There are 3 different line length message types:
3048 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3049 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3050 # LONG_LINE all other lines longer than $max_line_length
3052 # if LONG_LINE is ignored, the other 2 types are also ignored
3055 if ($line =~ /^\+/ && $length > $max_line_length) {
3056 my $msg_type = "LONG_LINE";
3058 # Check the allowed long line types first
3060 # logging functions that end in a string that starts
3061 # before $max_line_length
3062 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3063 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3066 # lines with only strings (w/ possible termination)
3067 # #defines with only strings
3068 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3069 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3072 # More special cases
3073 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3074 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3077 # URL ($rawline is used in case the URL is in a comment)
3078 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3081 # Otherwise set the alternate message types
3083 # a comment starts before $max_line_length
3084 } elsif ($line =~ /($;[\s$;]*)$/ &&
3085 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3086 $msg_type = "LONG_LINE_COMMENT"
3088 # a quoted string starts before $max_line_length
3089 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3090 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3091 $msg_type = "LONG_LINE_STRING"
3094 if ($msg_type ne "" &&
3095 (show_type("LONG_LINE") || show_type($msg_type))) {
3096 my $msg_level = \&WARN;
3097 $msg_level = \&CHK if ($file);
3098 &{$msg_level}($msg_type,
3099 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3103 # check for adding lines without a newline.
3104 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3105 WARN("MISSING_EOF_NEWLINE",
3106 "adding a line without newline at end of file\n" . $herecurr);
3109 # check we are in a valid source file C or perl if not then ignore this hunk
3110 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3112 # at the beginning of a line any tabs must come first and anything
3113 # more than 8 must use tabs.
3114 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3115 $rawline =~ /^\+\s* \s*/) {
3116 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3118 if (ERROR("CODE_INDENT",
3119 "code indent should use tabs where possible\n" . $herevet) &&
3121 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3125 # check for space before tabs.
3126 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3127 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3128 if (WARN("SPACE_BEFORE_TAB",
3129 "please, no space before tabs\n" . $herevet) &&
3131 while ($fixed[$fixlinenr] =~
3132 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3133 while ($fixed[$fixlinenr] =~
3134 s/(^\+.*) +\t/$1\t/) {}
3138 # check for assignments on the start of a line
3139 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3140 CHK("ASSIGNMENT_CONTINUATIONS",
3141 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3144 # check for && or || at the start of a line
3145 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3146 CHK("LOGICAL_CONTINUATIONS",
3147 "Logical continuations should be on the previous line\n" . $hereprev);
3150 # check indentation starts on a tab stop
3151 if ($perl_version_ok &&
3152 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3153 my $indent = length($1);
3156 "Statements should start on a tabstop\n" . $herecurr) &&
3158 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3163 # check multi-line statement indentation matches previous line
3164 if ($perl_version_ok &&
3165 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3166 $prevline =~ /^\+(\t*)(.*)$/;
3170 my $pos = pos_last_openparen($rest);
3172 $line =~ /^(\+| )([ \t]*)/;
3175 my $goodtabindent = $oldindent .
3178 my $goodspaceindent = $oldindent . " " x $pos;
3180 if ($newindent ne $goodtabindent &&
3181 $newindent ne $goodspaceindent) {
3183 if (CHK("PARENTHESIS_ALIGNMENT",
3184 "Alignment should match open parenthesis\n" . $hereprev) &&
3185 $fix && $line =~ /^\+/) {
3186 $fixed[$fixlinenr] =~
3187 s/^\+[ \t]*/\+$goodtabindent/;
3193 # check for space after cast like "(int) foo" or "(struct foo) bar"
3194 # avoid checking a few false positives:
3195 # "sizeof(<type>)" or "__alignof__(<type>)"
3196 # function pointer declarations like "(*foo)(int) = bar;"
3197 # structure definitions like "(struct foo) { 0 };"
3198 # multiline macros that define functions
3199 # known attributes or the __attribute__ keyword
3200 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3201 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3203 "No space is necessary after a cast\n" . $herecurr) &&
3205 $fixed[$fixlinenr] =~
3206 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3210 # Block comment styles
3211 # Networking with an initial /*
3212 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3213 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3214 $rawline =~ /^\+[ \t]*\*/ &&
3216 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3217 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3220 # Block comments use * on subsequent lines
3221 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3222 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3223 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3224 $rawline =~ /^\+/ && #line is new
3225 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3226 WARN("BLOCK_COMMENT_STYLE",
3227 "Block comments use * on subsequent lines\n" . $hereprev);
3230 # Block comments use */ on trailing lines
3231 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3232 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3233 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3234 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3235 WARN("BLOCK_COMMENT_STYLE",
3236 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3239 # Block comment * alignment
3240 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3241 $line =~ /^\+[ \t]*$;/ && #leading comment
3242 $rawline =~ /^\+[ \t]*\*/ && #leading *
3243 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3244 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3245 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3247 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3249 $oldindent = expand_tabs($1);
3251 $prevrawline =~ m@^\+(.*/?)\*@;
3252 $oldindent = expand_tabs($1);
3254 $rawline =~ m@^\+([ \t]*)\*@;
3256 $newindent = expand_tabs($newindent);
3257 if (length($oldindent) ne length($newindent)) {
3258 WARN("BLOCK_COMMENT_STYLE",
3259 "Block comments should align the * on each line\n" . $hereprev);
3263 # check for missing blank lines after struct/union declarations
3264 # with exceptions for various attributes and macros
3265 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3267 !($line =~ /^\+\s*$/ ||
3268 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3269 $line =~ /^\+\s*MODULE_/i ||
3270 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3271 $line =~ /^\+[a-z_]*init/ ||
3272 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3273 $line =~ /^\+\s*DECLARE/ ||
3274 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3275 $line =~ /^\+\s*__setup/)) {
3276 if (CHK("LINE_SPACING",
3277 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3279 fix_insert_line($fixlinenr, "\+");
3283 # check for multiple consecutive blank lines
3284 if ($prevline =~ /^[\+ ]\s*$/ &&
3285 $line =~ /^\+\s*$/ &&
3286 $last_blank_line != ($linenr - 1)) {
3287 if (CHK("LINE_SPACING",
3288 "Please don't use multiple blank lines\n" . $hereprev) &&
3290 fix_delete_line($fixlinenr, $rawline);
3293 $last_blank_line = $linenr;
3296 # check for missing blank lines after declarations
3297 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3298 # actual declarations
3299 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3300 # function pointer declarations
3301 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3302 # foo bar; where foo is some local typedef or #define
3303 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3304 # known declaration macros
3305 $prevline =~ /^\+\s+$declaration_macros/) &&
3306 # for "else if" which can look like "$Ident $Ident"
3307 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3308 # other possible extensions of declaration lines
3309 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3310 # not starting a section or a macro "\" extended line
3311 $prevline =~ /(?:\{\s*|\\)$/) &&
3312 # looks like a declaration
3313 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3314 # function pointer declarations
3315 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3316 # foo bar; where foo is some local typedef or #define
3317 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3318 # known declaration macros
3319 $sline =~ /^\+\s+$declaration_macros/ ||
3320 # start of struct or union or enum
3321 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3322 # start or end of block or continuation of declaration
3323 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3324 # bitfield continuation
3325 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3326 # other possible extensions of declaration lines
3327 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3328 # indentation of previous and current line are the same
3329 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3330 if (WARN("LINE_SPACING",
3331 "Missing a blank line after declarations\n" . $hereprev) &&
3333 fix_insert_line($fixlinenr, "\+");
3337 # check for spaces at the beginning of a line.
3339 # 1) within comments
3340 # 2) indented preprocessor commands
3342 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3343 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3344 if (WARN("LEADING_SPACE",
3345 "please, no spaces at the start of a line\n" . $herevet) &&
3347 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3351 # check we are in a valid C source file if not then ignore this hunk
3352 next if ($realfile !~ /\.(h|c)$/);
3354 # check for unusual line ending [ or (
3355 if ($line =~ /^\+.*([\[\(])\s*$/) {
3356 CHK("OPEN_ENDED_LINE",
3357 "Lines should not end with a '$1'\n" . $herecurr);
3360 # check if this appears to be the start function declaration, save the name
3361 if ($sline =~ /^\+\{\s*$/ &&
3362 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3363 $context_function = $1;
3366 # check if this appears to be the end of function declaration
3367 if ($sline =~ /^\+\}\s*$/) {
3368 undef $context_function;
3371 # check indentation of any line with a bare else
3372 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3373 # if the previous line is a break or return and is indented 1 tab more...
3374 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3375 my $tabs = length($1) + 1;
3376 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3377 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3378 defined $lines[$linenr] &&
3379 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3380 WARN("UNNECESSARY_ELSE",
3381 "else is not generally useful after a break or return\n" . $hereprev);
3385 # check indentation of a line with a break;
3386 # if the previous line is a goto or return and is indented the same # of tabs
3387 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3389 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3390 WARN("UNNECESSARY_BREAK",
3391 "break is not useful after a goto or return\n" . $hereprev);
3395 # check for RCS/CVS revision markers
3396 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3398 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3401 # check for old HOTPLUG __dev<foo> section markings
3402 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3403 WARN("HOTPLUG_SECTION",
3404 "Using $1 is unnecessary\n" . $herecurr);
3407 # Check for potential 'bare' types
3408 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3410 #print "LINE<$line>\n";
3411 if ($linenr > $suppress_statement &&
3412 $realcnt && $sline =~ /.\s*\S/) {
3413 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3414 ctx_statement_block($linenr, $realcnt, 0);
3415 $stat =~ s/\n./\n /g;
3416 $cond =~ s/\n./\n /g;
3418 #print "linenr<$linenr> <$stat>\n";
3419 # If this statement has no statement boundaries within
3420 # it there is no point in retrying a statement scan
3421 # until we hit end of it.
3422 my $frag = $stat; $frag =~ s/;+\s*$//;
3423 if ($frag !~ /(?:{|;)/) {
3424 #print "skip<$line_nr_next>\n";
3425 $suppress_statement = $line_nr_next;
3428 # Find the real next line.
3429 $realline_next = $line_nr_next;
3430 if (defined $realline_next &&
3431 (!defined $lines[$realline_next - 1] ||
3432 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3439 # Ignore goto labels.
3440 if ($s =~ /$Ident:\*$/s) {
3442 # Ignore functions being called
3443 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3445 } elsif ($s =~ /^.\s*else\b/s) {
3447 # declarations always start with types
3448 } 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) {
3451 possible($type, "A:" . $s);
3453 # definitions in global scope can only start with types
3454 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3455 possible($1, "B:" . $s);
3458 # any (foo ... *) is a pointer cast, and foo is a type
3459 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3460 possible($1, "C:" . $s);
3463 # Check for any sort of function declaration.
3464 # int foo(something bar, other baz);
3465 # void (*store_gdt)(x86_descr_ptr *);
3466 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3467 my ($name_len) = length($1);
3470 substr($ctx, 0, $name_len + 1, '');
3471 $ctx =~ s/\)[^\)]*$//;
3473 for my $arg (split(/\s*,\s*/, $ctx)) {
3474 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3476 possible($1, "D:" . $s);
3484 # Checks which may be anchored in the context.
3487 # Check for switch () and associated case and default
3488 # statements should be at the same indent.
3489 if ($line=~/\bswitch\s*\(.*\)/) {
3492 my @ctx = ctx_block_outer($linenr, $realcnt);
3494 for my $ctx (@ctx) {
3495 my ($clen, $cindent) = line_stats($ctx);
3496 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3497 $indent != $cindent) {
3498 $err .= "$sep$ctx\n";
3505 ERROR("SWITCH_CASE_INDENT_LEVEL",
3506 "switch and case should be at the same indent\n$hereline$err");
3510 # if/while/etc brace do not go on next line, unless defining a do while loop,
3511 # or if that brace on the next line is for something else
3512 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3513 my $pre_ctx = "$1$2";
3515 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3517 if ($line =~ /^\+\t{6,}/) {
3518 WARN("DEEP_INDENTATION",
3519 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3522 my $ctx_cnt = $realcnt - $#ctx - 1;
3523 my $ctx = join("\n", @ctx);
3525 my $ctx_ln = $linenr;
3526 my $ctx_skip = $realcnt;
3528 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3529 defined $lines[$ctx_ln - 1] &&
3530 $lines[$ctx_ln - 1] =~ /^-/)) {
3531 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3532 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3536 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3537 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3539 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3541 "that open brace { should be on the previous line\n" .
3542 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3544 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3545 $ctx =~ /\)\s*\;\s*$/ &&
3546 defined $lines[$ctx_ln - 1])
3548 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3549 if ($nindent > $indent) {
3550 WARN("TRAILING_SEMICOLON",
3551 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3552 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3557 # Check relative indent for conditionals and blocks.
3558 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3559 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3560 ctx_statement_block($linenr, $realcnt, 0)
3561 if (!defined $stat);
3562 my ($s, $c) = ($stat, $cond);
3564 substr($s, 0, length($c), '');
3566 # remove inline comments
3570 # Find out how long the conditional actually is.
3571 my @newlines = ($c =~ /\n/gs);
3572 my $cond_lines = 1 + $#newlines;
3574 # Make sure we remove the line prefixes as we have
3575 # none on the first line, and are going to readd them
3578 while ($s =~ /\n\s+\\\n/) {
3579 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3582 # We want to check the first line inside the block
3583 # starting at the end of the conditional, so remove:
3584 # 1) any blank line termination
3585 # 2) any opening brace { on end of the line
3587 my $continuation = 0;
3589 $s =~ s/^.*\bdo\b//;
3591 if ($s =~ s/^\s*\\//) {
3594 if ($s =~ s/^\s*?\n//) {
3599 # Also ignore a loop construct at the end of a
3600 # preprocessor statement.
3601 if (($prevline =~ /^.\s*#\s*define\s/ ||
3602 $prevline =~ /\\\s*$/) && $continuation == 0) {
3608 while ($cond_ptr != $cond_lines) {
3609 $cond_ptr = $cond_lines;
3611 # If we see an #else/#elif then the code
3613 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3618 # 1) blank lines, they should be at 0,
3619 # 2) preprocessor lines, and
3621 if ($continuation ||
3623 $s =~ /^\s*#\s*?/ ||
3624 $s =~ /^\s*$Ident\s*:/) {
3625 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3626 if ($s =~ s/^.*?\n//) {
3632 my (undef, $sindent) = line_stats("+" . $s);
3633 my $stat_real = raw_line($linenr, $cond_lines);
3635 # Check if either of these lines are modified, else
3636 # this is not this patch's fault.
3637 if (!defined($stat_real) ||
3638 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3641 if (defined($stat_real) && $cond_lines > 1) {
3642 $stat_real = "[...]\n$stat_real";
3645 #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";
3647 if ($check && $s ne '' &&
3648 (($sindent % 8) != 0 ||
3649 ($sindent < $indent) ||
3650 ($sindent == $indent &&
3651 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3652 ($sindent > $indent + 8))) {
3653 WARN("SUSPECT_CODE_INDENT",
3654 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3658 # Track the 'values' across context and added lines.
3659 my $opline = $line; $opline =~ s/^./ /;
3660 my ($curr_values, $curr_vars) =
3661 annotate_values($opline . "\n", $prev_values);
3662 $curr_values = $prev_values . $curr_values;
3664 my $outline = $opline; $outline =~ s/\t/ /g;
3665 print "$linenr > .$outline\n";
3666 print "$linenr > $curr_values\n";
3667 print "$linenr > $curr_vars\n";
3669 $prev_values = substr($curr_values, -1);
3671 #ignore lines not being added
3672 next if ($line =~ /^[^\+]/);
3674 # check for dereferences that span multiple lines
3675 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3676 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3677 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3679 $line =~ /^.\s*($Lval)/;
3682 WARN("MULTILINE_DEREFERENCE",
3683 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3686 # check for declarations of signed or unsigned without int
3687 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3690 $var = "" if (!defined $var);
3691 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3695 $pointer = "" if (!defined $pointer);
3697 if (WARN("UNSPECIFIED_INT",
3698 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3700 my $decl = trim($sign) . " int ";
3701 my $comp_pointer = $pointer;
3702 $comp_pointer =~ s/\s//g;
3703 $decl .= $comp_pointer;
3704 $decl = rtrim($decl) if ($var eq "");
3705 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3710 # TEST: allow direct testing of the type matcher.
3712 if ($line =~ /^.\s*$Declare\s*$/) {
3714 "TEST: is type\n" . $herecurr);
3715 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3716 ERROR("TEST_NOT_TYPE",
3717 "TEST: is not type ($1 is)\n". $herecurr);
3721 # TEST: allow direct testing of the attribute matcher.
3723 if ($line =~ /^.\s*$Modifier\s*$/) {
3725 "TEST: is attr\n" . $herecurr);
3726 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3727 ERROR("TEST_NOT_ATTR",
3728 "TEST: is not attr ($1 is)\n". $herecurr);
3733 # check for initialisation to aggregates open brace on the next line
3734 if ($line =~ /^.\s*{/ &&
3735 $prevline =~ /(?:^|[^=])=\s*$/) {
3736 if (ERROR("OPEN_BRACE",
3737 "that open brace { should be on the previous line\n" . $hereprev) &&
3738 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3739 fix_delete_line($fixlinenr - 1, $prevrawline);
3740 fix_delete_line($fixlinenr, $rawline);
3741 my $fixedline = $prevrawline;
3742 $fixedline =~ s/\s*=\s*$/ = {/;
3743 fix_insert_line($fixlinenr, $fixedline);
3745 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3746 fix_insert_line($fixlinenr, $fixedline);
3751 # Checks which are anchored on the added line.
3754 # check for malformed paths in #include statements (uses RAW line)
3755 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3757 if ($path =~ m{//}) {
3758 ERROR("MALFORMED_INCLUDE",
3759 "malformed #include filename\n" . $herecurr);
3761 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3762 ERROR("UAPI_INCLUDE",
3763 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3767 # no C99 // comments
3768 if ($line =~ m{//}) {
3769 if (ERROR("C99_COMMENTS",
3770 "do not use C99 // comments\n" . $herecurr) &&
3772 my $line = $fixed[$fixlinenr];
3773 if ($line =~ /\/\/(.*)$/) {
3774 my $comment = trim($1);
3775 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3779 # Remove C99 comments.
3781 $opline =~ s@//.*@@;
3783 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3784 # the whole statement.
3785 #print "APW <$lines[$realline_next - 1]>\n";
3786 if (defined $realline_next &&
3787 exists $lines[$realline_next - 1] &&
3788 !defined $suppress_export{$realline_next} &&
3789 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3790 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3791 # Handle definitions which produce identifiers with
3794 # EXPORT_SYMBOL(something_foo);
3796 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3797 $name =~ /^${Ident}_$2/) {
3798 #print "FOO C name<$name>\n";
3799 $suppress_export{$realline_next} = 1;
3801 } elsif ($stat !~ /(?:
3803 ^.DEFINE_$Ident\(\Q$name\E\)|
3804 ^.DECLARE_$Ident\(\Q$name\E\)|
3805 ^.LIST_HEAD\(\Q$name\E\)|
3806 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3807 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3809 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3810 $suppress_export{$realline_next} = 2;
3812 $suppress_export{$realline_next} = 1;
3815 if (!defined $suppress_export{$linenr} &&
3816 $prevline =~ /^.\s*$/ &&
3817 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3818 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3819 #print "FOO B <$lines[$linenr - 1]>\n";
3820 $suppress_export{$linenr} = 2;
3822 if (defined $suppress_export{$linenr} &&
3823 $suppress_export{$linenr} == 2) {
3824 WARN("EXPORT_SYMBOL",
3825 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3828 # check for global initialisers.
3829 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3830 if (ERROR("GLOBAL_INITIALISERS",
3831 "do not initialise globals to $1\n" . $herecurr) &&
3833 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3836 # check for static initialisers.
3837 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3838 if (ERROR("INITIALISED_STATIC",
3839 "do not initialise statics to $1\n" .
3842 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3846 # check for misordered declarations of char/short/int/long with signed/unsigned
3847 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3849 WARN("MISORDERED_TYPE",
3850 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3853 # check for unnecessary <signed> int declarations of short/long/long long
3854 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3855 my $type = trim($1);
3856 next if ($type !~ /\bint\b/);
3857 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3858 my $new_type = $type;
3859 $new_type =~ s/\b\s*int\s*\b/ /;
3860 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3861 $new_type =~ s/^const\s+//;
3862 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3863 $new_type = "const $new_type" if ($type =~ /^const\b/);
3864 $new_type =~ s/\s+/ /g;
3865 $new_type = trim($new_type);
3866 if (WARN("UNNECESSARY_INT",
3867 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3869 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3873 # check for static const char * arrays.
3874 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3875 WARN("STATIC_CONST_CHAR_ARRAY",
3876 "static const char * array should probably be static const char * const\n" .
3880 # check for static char foo[] = "bar" declarations.
3881 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3882 WARN("STATIC_CONST_CHAR_ARRAY",
3883 "static char array declaration should probably be static const char\n" .
3887 # check for const <foo> const where <foo> is not a pointer or array type
3888 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3890 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3892 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3893 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3895 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3899 # check for non-global char *foo[] = {"bar", ...} declarations.
3900 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3901 WARN("STATIC_CONST_CHAR_ARRAY",
3902 "char * array declaration might be better as static const\n" .
3906 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3907 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3909 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3911 if (WARN("ARRAY_SIZE",
3912 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3914 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3919 # check for function declarations without arguments like "int foo()"
3920 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3921 if (ERROR("FUNCTION_WITHOUT_ARGS",
3922 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3924 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3928 # check for new typedefs, only function parameters and sparse annotations
3930 if ($line =~ /\btypedef\s/ &&
3931 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3932 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3933 $line !~ /\b$typeTypedefs\b/ &&
3934 $line !~ /\b__bitwise\b/) {
3935 WARN("NEW_TYPEDEFS",
3936 "do not add new typedefs\n" . $herecurr);
3939 # * goes on variable not on type
3941 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3943 my ($ident, $from, $to) = ($1, $2, $2);
3945 # Should start with a space.
3946 $to =~ s/^(\S)/ $1/;
3947 # Should not end with a space.
3949 # '*'s should not have spaces between.
3950 while ($to =~ s/\*\s+\*/\*\*/) {
3953 ## print "1: from<$from> to<$to> ident<$ident>\n";
3955 if (ERROR("POINTER_LOCATION",
3956 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3958 my $sub_from = $ident;
3959 my $sub_to = $ident;
3960 $sub_to =~ s/\Q$from\E/$to/;
3961 $fixed[$fixlinenr] =~
3962 s@\Q$sub_from\E@$sub_to@;
3966 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3968 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3970 # Should start with a space.
3971 $to =~ s/^(\S)/ $1/;
3972 # Should not end with a space.
3974 # '*'s should not have spaces between.
3975 while ($to =~ s/\*\s+\*/\*\*/) {
3977 # Modifiers should have spaces.
3978 $to =~ s/(\b$Modifier$)/$1 /;
3980 ## print "2: from<$from> to<$to> ident<$ident>\n";
3981 if ($from ne $to && $ident !~ /^$Modifier$/) {
3982 if (ERROR("POINTER_LOCATION",
3983 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3986 my $sub_from = $match;
3987 my $sub_to = $match;
3988 $sub_to =~ s/\Q$from\E/$to/;
3989 $fixed[$fixlinenr] =~
3990 s@\Q$sub_from\E@$sub_to@;
3995 # avoid BUG() or BUG_ON()
3996 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3997 my $msg_level = \&WARN;
3998 $msg_level = \&CHK if ($file);
3999 &{$msg_level}("AVOID_BUG",
4000 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4003 # avoid LINUX_VERSION_CODE
4004 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4005 WARN("LINUX_VERSION_CODE",
4006 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4009 # check for uses of printk_ratelimit
4010 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4011 WARN("PRINTK_RATELIMITED",
4012 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4015 # printk should use KERN_* levels
4016 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4017 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4018 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4021 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4023 my $level = lc($orig);
4024 $level = "warn" if ($level eq "warning");
4025 my $level2 = $level;
4026 $level2 = "dbg" if ($level eq "debug");
4027 WARN("PREFER_PR_LEVEL",
4028 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4031 if ($line =~ /\bpr_warning\s*\(/) {
4032 if (WARN("PREFER_PR_LEVEL",
4033 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4035 $fixed[$fixlinenr] =~
4036 s/\bpr_warning\b/pr_warn/;
4040 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4042 my $level = lc($orig);
4043 $level = "warn" if ($level eq "warning");
4044 $level = "dbg" if ($level eq "debug");
4045 WARN("PREFER_DEV_LEVEL",
4046 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4049 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4050 # number of false positives, but assembly files are not checked, so at
4051 # least the arch entry code will not trigger this warning.
4052 if ($line =~ /\bENOSYS\b/) {
4054 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4057 # function brace can't be on same line, except for #defines of do while,
4058 # or if closed on same line
4059 if ($perl_version_ok &&
4060 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4061 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4063 if (ERROR("OPEN_BRACE",
4064 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4066 fix_delete_line($fixlinenr, $rawline);
4067 my $fixed_line = $rawline;
4068 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4071 fix_insert_line($fixlinenr, ltrim($line1));
4072 fix_insert_line($fixlinenr, "\+{");
4073 if ($line2 !~ /^\s*$/) {
4074 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4079 # open braces for enum, union and struct go on the same line.
4080 if ($line =~ /^.\s*{/ &&
4081 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4082 if (ERROR("OPEN_BRACE",
4083 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4084 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4085 fix_delete_line($fixlinenr - 1, $prevrawline);
4086 fix_delete_line($fixlinenr, $rawline);
4087 my $fixedline = rtrim($prevrawline) . " {";
4088 fix_insert_line($fixlinenr, $fixedline);
4089 $fixedline = $rawline;
4090 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4091 if ($fixedline !~ /^\+\s*$/) {
4092 fix_insert_line($fixlinenr, $fixedline);
4097 # missing space after union, struct or enum definition
4098 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4100 "missing space after $1 definition\n" . $herecurr) &&
4102 $fixed[$fixlinenr] =~
4103 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4107 # Function pointer declarations
4108 # check spacing between type, funcptr, and args
4109 # canonical declaration is "type (*funcptr)(args...)"
4110 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4112 my $pre_pointer_space = $2;
4113 my $post_pointer_space = $3;
4115 my $post_funcname_space = $5;
4116 my $pre_args_space = $6;
4118 # the $Declare variable will capture all spaces after the type
4119 # so check it for a missing trailing missing space but pointer return types
4120 # don't need a space so don't warn for those.
4121 my $post_declare_space = "";
4122 if ($declare =~ /(\s+)$/) {
4123 $post_declare_space = $1;
4124 $declare = rtrim($declare);
4126 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4128 "missing space after return type\n" . $herecurr);
4129 $post_declare_space = " ";
4132 # unnecessary space "type (*funcptr)(args...)"
4133 # This test is not currently implemented because these declarations are
4135 # int foo(int bar, ...)
4136 # and this is form shouldn't/doesn't generate a checkpatch warning.
4138 # elsif ($declare =~ /\s{2,}$/) {
4140 # "Multiple spaces after return type\n" . $herecurr);
4143 # unnecessary space "type ( *funcptr)(args...)"
4144 if (defined $pre_pointer_space &&
4145 $pre_pointer_space =~ /^\s/) {
4147 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4150 # unnecessary space "type (* funcptr)(args...)"
4151 if (defined $post_pointer_space &&
4152 $post_pointer_space =~ /^\s/) {
4154 "Unnecessary space before function pointer name\n" . $herecurr);
4157 # unnecessary space "type (*funcptr )(args...)"
4158 if (defined $post_funcname_space &&
4159 $post_funcname_space =~ /^\s/) {
4161 "Unnecessary space after function pointer name\n" . $herecurr);
4164 # unnecessary space "type (*funcptr) (args...)"
4165 if (defined $pre_args_space &&
4166 $pre_args_space =~ /^\s/) {
4168 "Unnecessary space before function pointer arguments\n" . $herecurr);
4171 if (show_type("SPACING") && $fix) {
4172 $fixed[$fixlinenr] =~
4173 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4177 # check for spacing round square brackets; allowed:
4178 # 1. with a type on the left -- int [] a;
4179 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4180 # 3. inside a curly brace -- = { [0...10] = 5 }
4181 while ($line =~ /(.*?\s)\[/g) {
4182 my ($where, $prefix) = ($-[1], $1);
4183 if ($prefix !~ /$Type\s+$/ &&
4184 ($where != 0 || $prefix !~ /^.\s+$/) &&
4185 $prefix !~ /[{,:]\s+$/) {
4186 if (ERROR("BRACKET_SPACE",
4187 "space prohibited before open square bracket '['\n" . $herecurr) &&
4189 $fixed[$fixlinenr] =~
4190 s/^(\+.*?)\s+\[/$1\[/;
4195 # check for spaces between functions and their parentheses.
4196 while ($line =~ /($Ident)\s+\(/g) {
4198 my $ctx_before = substr($line, 0, $-[1]);
4199 my $ctx = "$ctx_before$name";
4201 # Ignore those directives where spaces _are_ permitted.
4203 if|for|while|switch|return|case|
4204 volatile|__volatile__|
4205 __attribute__|format|__extension__|
4208 # cpp #define statements have non-optional spaces, ie
4209 # if there is a space between the name and the open
4210 # parenthesis it is simply not a parameter group.
4211 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4213 # cpp #elif statement condition may start with a (
4214 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4216 # If this whole things ends with a type its most
4217 # likely a typedef for a function.
4218 } elsif ($ctx =~ /$Type$/) {
4222 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4224 $fixed[$fixlinenr] =~
4225 s/\b$name\s+\(/$name\(/;
4230 # Check operator spacing.
4231 if (!($line=~/\#\s*include/)) {
4232 my $fixed_line = "";
4236 <<=|>>=|<=|>=|==|!=|
4237 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4238 =>|->|<<|>>|<|>|=|!|~|
4239 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4242 my @elements = split(/($ops|;)/, $opline);
4244 ## print("element count: <" . $#elements . ">\n");
4245 ## foreach my $el (@elements) {
4246 ## print("el: <$el>\n");
4249 my @fix_elements = ();
4252 foreach my $el (@elements) {
4253 push(@fix_elements, substr($rawline, $off, length($el)));
4254 $off += length($el);
4259 my $blank = copy_spacing($opline);
4260 my $last_after = -1;
4262 for (my $n = 0; $n < $#elements; $n += 2) {
4264 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4266 ## print("n: <$n> good: <$good>\n");
4268 $off += length($elements[$n]);
4270 # Pick up the preceding and succeeding characters.
4271 my $ca = substr($opline, 0, $off);
4273 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4274 $cc = substr($opline, $off + length($elements[$n + 1]));
4276 my $cb = "$ca$;$cc";
4279 $a = 'V' if ($elements[$n] ne '');
4280 $a = 'W' if ($elements[$n] =~ /\s$/);
4281 $a = 'C' if ($elements[$n] =~ /$;$/);
4282 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4283 $a = 'O' if ($elements[$n] eq '');
4284 $a = 'E' if ($ca =~ /^\s*$/);
4286 my $op = $elements[$n + 1];
4289 if (defined $elements[$n + 2]) {
4290 $c = 'V' if ($elements[$n + 2] ne '');
4291 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4292 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4293 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4294 $c = 'O' if ($elements[$n + 2] eq '');
4295 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4300 my $ctx = "${a}x${c}";
4302 my $at = "(ctx:$ctx)";
4304 my $ptr = substr($blank, 0, $off) . "^";
4305 my $hereptr = "$hereline$ptr\n";
4307 # Pull out the value of this operator.
4308 my $op_type = substr($curr_values, $off + 1, 1);
4310 # Get the full operator variant.
4311 my $opv = $op . substr($curr_vars, $off, 1);
4313 # Ignore operators passed as parameters.
4314 if ($op_type ne 'V' &&
4315 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4318 # } elsif ($op =~ /^$;+$/) {
4320 # ; should have either the end of line or a space or \ after it
4321 } elsif ($op eq ';') {
4322 if ($ctx !~ /.x[WEBC]/ &&
4323 $cc !~ /^\\/ && $cc !~ /^;/) {
4324 if (ERROR("SPACING",
4325 "space required after that '$op' $at\n" . $hereptr)) {
4326 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4332 } elsif ($op eq '//') {
4334 # : when part of a bitfield
4335 } elsif ($opv eq ':B') {
4336 # skip the bitfield test for now
4340 } elsif ($op eq '->') {
4341 if ($ctx =~ /Wx.|.xW/) {
4342 if (ERROR("SPACING",
4343 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4344 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4345 if (defined $fix_elements[$n + 2]) {
4346 $fix_elements[$n + 2] =~ s/^\s+//;
4352 # , must not have a space before and must have a space on the right.
4353 } elsif ($op eq ',') {
4354 my $rtrim_before = 0;
4355 my $space_after = 0;
4356 if ($ctx =~ /Wx./) {
4357 if (ERROR("SPACING",
4358 "space prohibited before that '$op' $at\n" . $hereptr)) {
4363 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4364 if (ERROR("SPACING",
4365 "space required after that '$op' $at\n" . $hereptr)) {
4371 if ($rtrim_before || $space_after) {
4372 if ($rtrim_before) {
4373 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4375 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4382 # '*' as part of a type definition -- reported already.
4383 } elsif ($opv eq '*_') {
4384 #warn "'*' is part of type\n";
4386 # unary operators should have a space before and
4387 # none after. May be left adjacent to another
4388 # unary operator, or a cast
4389 } elsif ($op eq '!' || $op eq '~' ||
4390 $opv eq '*U' || $opv eq '-U' ||
4391 $opv eq '&U' || $opv eq '&&U') {
4392 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4393 if (ERROR("SPACING",
4394 "space required before that '$op' $at\n" . $hereptr)) {
4395 if ($n != $last_after + 2) {
4396 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4401 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4402 # A unary '*' may be const
4404 } elsif ($ctx =~ /.xW/) {
4405 if (ERROR("SPACING",
4406 "space prohibited after that '$op' $at\n" . $hereptr)) {
4407 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4408 if (defined $fix_elements[$n + 2]) {
4409 $fix_elements[$n + 2] =~ s/^\s+//;
4415 # unary ++ and unary -- are allowed no space on one side.
4416 } elsif ($op eq '++' or $op eq '--') {
4417 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4418 if (ERROR("SPACING",
4419 "space required one side of that '$op' $at\n" . $hereptr)) {
4420 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4424 if ($ctx =~ /Wx[BE]/ ||
4425 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4426 if (ERROR("SPACING",
4427 "space prohibited before that '$op' $at\n" . $hereptr)) {
4428 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4432 if ($ctx =~ /ExW/) {
4433 if (ERROR("SPACING",
4434 "space prohibited after that '$op' $at\n" . $hereptr)) {
4435 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4436 if (defined $fix_elements[$n + 2]) {
4437 $fix_elements[$n + 2] =~ s/^\s+//;
4443 # << and >> may either have or not have spaces both sides
4444 } elsif ($op eq '<<' or $op eq '>>' or
4445 $op eq '&' or $op eq '^' or $op eq '|' or
4446 $op eq '+' or $op eq '-' or
4447 $op eq '*' or $op eq '/' or
4451 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4453 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4454 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4455 $fix_elements[$n + 2] =~ s/^\s+//;
4458 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4460 "space preferred before that '$op' $at\n" . $hereptr)) {
4461 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4465 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4466 if (ERROR("SPACING",
4467 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4468 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4469 if (defined $fix_elements[$n + 2]) {
4470 $fix_elements[$n + 2] =~ s/^\s+//;
4476 # A colon needs no spaces before when it is
4477 # terminating a case value or a label.
4478 } elsif ($opv eq ':C' || $opv eq ':L') {
4479 if ($ctx =~ /Wx./) {
4480 if (ERROR("SPACING",
4481 "space prohibited before that '$op' $at\n" . $hereptr)) {
4482 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4487 # All the others need spaces both sides.
4488 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4491 # Ignore email addresses <foo@bar>
4493 $cc =~ /^\S+\@\S+>/) ||
4495 $ca =~ /<\S+\@\S+$/))
4500 # for asm volatile statements
4501 # ignore a colon with another
4502 # colon immediately before or after
4504 ($ca =~ /:$/ || $cc =~ /^:/)) {
4508 # messages are ERROR, but ?: are CHK
4510 my $msg_level = \&ERROR;
4511 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4513 if (&{$msg_level}("SPACING",
4514 "spaces required around that '$op' $at\n" . $hereptr)) {
4515 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4516 if (defined $fix_elements[$n + 2]) {
4517 $fix_elements[$n + 2] =~ s/^\s+//;
4523 $off += length($elements[$n + 1]);
4525 ## print("n: <$n> GOOD: <$good>\n");
4527 $fixed_line = $fixed_line . $good;
4530 if (($#elements % 2) == 0) {
4531 $fixed_line = $fixed_line . $fix_elements[$#elements];
4534 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4535 $fixed[$fixlinenr] = $fixed_line;
4541 # check for whitespace before a non-naked semicolon
4542 if ($line =~ /^\+.*\S\s+;\s*$/) {
4544 "space prohibited before semicolon\n" . $herecurr) &&
4546 1 while $fixed[$fixlinenr] =~
4547 s/^(\+.*\S)\s+;/$1;/;
4551 # check for multiple assignments
4552 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4553 CHK("MULTIPLE_ASSIGNMENTS",
4554 "multiple assignments should be avoided\n" . $herecurr);
4557 ## # check for multiple declarations, allowing for a function declaration
4559 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4560 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4562 ## # Remove any bracketed sections to ensure we do not
4563 ## # falsly report the parameters of functions.
4565 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4567 ## if ($ln =~ /,/) {
4568 ## WARN("MULTIPLE_DECLARATION",
4569 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4573 #need space before brace following if, while, etc
4574 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4575 $line =~ /\b(?:else|do)\{/) {
4576 if (ERROR("SPACING",
4577 "space required before the open brace '{'\n" . $herecurr) &&
4579 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4583 ## # check for blank lines before declarations
4584 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4585 ## $prevrawline =~ /^.\s*$/) {
4587 ## "No blank lines before declarations\n" . $hereprev);
4591 # closing brace should have a space following it when it has anything
4593 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4594 if (ERROR("SPACING",
4595 "space required after that close brace '}'\n" . $herecurr) &&
4597 $fixed[$fixlinenr] =~
4598 s/}((?!(?:,|;|\)))\S)/} $1/;
4602 # check spacing on square brackets
4603 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4604 if (ERROR("SPACING",
4605 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4607 $fixed[$fixlinenr] =~
4611 if ($line =~ /\s\]/) {
4612 if (ERROR("SPACING",
4613 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4615 $fixed[$fixlinenr] =~
4620 # check spacing on parentheses
4621 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4622 $line !~ /for\s*\(\s+;/) {
4623 if (ERROR("SPACING",
4624 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4626 $fixed[$fixlinenr] =~
4630 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4631 $line !~ /for\s*\(.*;\s+\)/ &&
4632 $line !~ /:\s+\)/) {
4633 if (ERROR("SPACING",
4634 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4636 $fixed[$fixlinenr] =~
4641 # check unnecessary parentheses around addressof/dereference single $Lvals
4642 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4644 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4646 if (CHK("UNNECESSARY_PARENTHESES",
4647 "Unnecessary parentheses around $var\n" . $herecurr) &&
4649 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4653 # check for unnecessary parentheses around function pointer uses
4654 # ie: (foo->bar)(); should be foo->bar();
4655 # but not "if (foo->bar) (" to avoid some false positives
4656 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4658 if (CHK("UNNECESSARY_PARENTHESES",
4659 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4661 my $var2 = deparenthesize($var);
4663 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4667 # check for unnecessary parentheses around comparisons in if uses
4668 # when !drivers/staging or command-line uses --strict
4669 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4670 $perl_version_ok && defined($stat) &&
4671 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4673 my $test = substr($2, 1, -1);
4675 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4677 # avoid parentheses around potential macro args
4678 next if ($match =~ /^\s*\w+\s*$/);
4679 if (!defined($herectx)) {
4680 $herectx = $here . "\n";
4681 my $cnt = statement_rawlines($if_stat);
4682 for (my $n = 0; $n < $cnt; $n++) {
4683 my $rl = raw_line($linenr, $n);
4684 $herectx .= $rl . "\n";
4685 last if $rl =~ /^[ \+].*\{/;
4688 CHK("UNNECESSARY_PARENTHESES",
4689 "Unnecessary parentheses around '$match'\n" . $herectx);
4693 #goto labels aren't indented, allow a single space however
4694 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4695 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4696 if (WARN("INDENTED_LABEL",
4697 "labels should not be indented\n" . $herecurr) &&
4699 $fixed[$fixlinenr] =~
4704 # return is not a function
4705 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4707 if ($perl_version_ok &&
4708 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4710 $value = deparenthesize($value);
4711 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4712 ERROR("RETURN_PARENTHESES",
4713 "return is not a function, parentheses are not required\n" . $herecurr);
4715 } elsif ($spacing !~ /\s+/) {
4717 "space required before the open parenthesis '('\n" . $herecurr);
4721 # unnecessary return in a void function
4722 # at end-of-function, with the previous line a single leading tab, then return;
4723 # and the line before that not a goto label target like "out:"
4724 if ($sline =~ /^[ \+]}\s*$/ &&
4725 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4727 $lines[$linenr - 3] =~ /^[ +]/ &&
4728 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4730 "void function return statements are not generally useful\n" . $hereprev);
4733 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4734 if ($perl_version_ok &&
4735 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4736 my $openparens = $1;
4737 my $count = $openparens =~ tr@\(@\(@;
4739 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4740 my $comp = $4; #Not $1 because of $LvalOrFunc
4741 $msg = " - maybe == should be = ?" if ($comp eq "==");
4742 WARN("UNNECESSARY_PARENTHESES",
4743 "Unnecessary parentheses$msg\n" . $herecurr);
4747 # comparisons with a constant or upper case identifier on the left
4748 # avoid cases like "foo + BAR < baz"
4749 # only fix matches surrounded by parentheses to avoid incorrect
4750 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4751 if ($perl_version_ok &&
4752 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4757 my $newcomp = $comp;
4758 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4759 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4760 WARN("CONSTANT_COMPARISON",
4761 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4765 } elsif ($comp eq "<=") {
4767 } elsif ($comp eq ">") {
4769 } elsif ($comp eq ">=") {
4772 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4776 # Return of what appears to be an errno should normally be negative
4777 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4779 if ($name ne 'EOF' && $name ne 'ERROR') {
4780 WARN("USE_NEGATIVE_ERRNO",
4781 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4785 # Need a space before open parenthesis after if, while etc
4786 if ($line =~ /\b(if|while|for|switch)\(/) {
4787 if (ERROR("SPACING",
4788 "space required before the open parenthesis '('\n" . $herecurr) &&
4790 $fixed[$fixlinenr] =~
4791 s/\b(if|while|for|switch)\(/$1 \(/;
4795 # Check for illegal assignment in if conditional -- and check for trailing
4796 # statements after the conditional.
4797 if ($line =~ /do\s*(?!{)/) {
4798 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4799 ctx_statement_block($linenr, $realcnt, 0)
4800 if (!defined $stat);
4801 my ($stat_next) = ctx_statement_block($line_nr_next,
4802 $remain_next, $off_next);
4803 $stat_next =~ s/\n./\n /g;
4804 ##print "stat<$stat> stat_next<$stat_next>\n";
4806 if ($stat_next =~ /^\s*while\b/) {
4807 # If the statement carries leading newlines,
4808 # then count those as offsets.
4810 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4812 statement_rawlines($whitespace) - 1;
4814 $suppress_whiletrailers{$line_nr_next +
4818 if (!defined $suppress_whiletrailers{$linenr} &&
4819 defined($stat) && defined($cond) &&
4820 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4821 my ($s, $c) = ($stat, $cond);
4823 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4824 ERROR("ASSIGN_IN_IF",
4825 "do not use assignment in if condition\n" . $herecurr);
4828 # Find out what is on the end of the line after the
4830 substr($s, 0, length($c), '');
4832 $s =~ s/$;//g; # Remove any comments
4833 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4834 $c !~ /}\s*while\s*/)
4836 # Find out how long the conditional actually is.
4837 my @newlines = ($c =~ /\n/gs);
4838 my $cond_lines = 1 + $#newlines;
4841 $stat_real = raw_line($linenr, $cond_lines)
4842 . "\n" if ($cond_lines);
4843 if (defined($stat_real) && $cond_lines > 1) {
4844 $stat_real = "[...]\n$stat_real";
4847 ERROR("TRAILING_STATEMENTS",
4848 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4852 # Check for bitwise tests written as boolean
4864 WARN("HEXADECIMAL_BOOLEAN_TEST",
4865 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4868 # if and else should not have general statements after it
4869 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4871 $s =~ s/$;//g; # Remove any comments
4872 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4873 ERROR("TRAILING_STATEMENTS",
4874 "trailing statements should be on next line\n" . $herecurr);
4877 # if should not continue a brace
4878 if ($line =~ /}\s*if\b/) {
4879 ERROR("TRAILING_STATEMENTS",
4880 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4883 # case and default should not have general statements after them
4884 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4886 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4890 ERROR("TRAILING_STATEMENTS",
4891 "trailing statements should be on next line\n" . $herecurr);
4894 # Check for }<nl>else {, these must be at the same
4895 # indent level to be relevant to each other.
4896 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4897 $previndent == $indent) {
4898 if (ERROR("ELSE_AFTER_BRACE",
4899 "else should follow close brace '}'\n" . $hereprev) &&
4900 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4901 fix_delete_line($fixlinenr - 1, $prevrawline);
4902 fix_delete_line($fixlinenr, $rawline);
4903 my $fixedline = $prevrawline;
4904 $fixedline =~ s/}\s*$//;
4905 if ($fixedline !~ /^\+\s*$/) {
4906 fix_insert_line($fixlinenr, $fixedline);
4908 $fixedline = $rawline;
4909 $fixedline =~ s/^(.\s*)else/$1} else/;
4910 fix_insert_line($fixlinenr, $fixedline);
4914 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4915 $previndent == $indent) {
4916 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4918 # Find out what is on the end of the line after the
4920 substr($s, 0, length($c), '');
4923 if ($s =~ /^\s*;/) {
4924 if (ERROR("WHILE_AFTER_BRACE",
4925 "while should follow close brace '}'\n" . $hereprev) &&
4926 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4927 fix_delete_line($fixlinenr - 1, $prevrawline);
4928 fix_delete_line($fixlinenr, $rawline);
4929 my $fixedline = $prevrawline;
4930 my $trailing = $rawline;
4931 $trailing =~ s/^\+//;
4932 $trailing = trim($trailing);
4933 $fixedline =~ s/}\s*$/} $trailing/;
4934 fix_insert_line($fixlinenr, $fixedline);
4939 #Specific variable tests
4940 while ($line =~ m{($Constant|$Lval)}g) {
4943 #gcc binary extension
4944 if ($var =~ /^$Binary$/) {
4945 if (WARN("GCC_BINARY_CONSTANT",
4946 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4948 my $hexval = sprintf("0x%x", oct($var));
4949 $fixed[$fixlinenr] =~
4950 s/\b$var\b/$hexval/;
4955 if ($var !~ /^$Constant$/ &&
4956 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4957 #Ignore Page<foo> variants
4958 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4959 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4960 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4961 #Ignore some three character SI units explicitly, like MiB and KHz
4962 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4963 while ($var =~ m{($Ident)}g) {
4965 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4967 seed_camelcase_includes();
4968 if (!$file && !$camelcase_file_seeded) {
4969 seed_camelcase_file($realfile);
4970 $camelcase_file_seeded = 1;
4973 if (!defined $camelcase{$word}) {
4974 $camelcase{$word} = 1;
4976 "Avoid CamelCase: <$word>\n" . $herecurr);
4982 #no spaces allowed after \ in define
4983 if ($line =~ /\#\s*define.*\\\s+$/) {
4984 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4985 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4987 $fixed[$fixlinenr] =~ s/\s+$//;
4991 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4992 # itself <asm/foo.h> (uses RAW line)
4993 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4995 my $checkfile = "include/linux/$file";
4996 if (-f "$root/$checkfile" &&
4997 $realfile ne $checkfile &&
4998 $1 !~ /$allowed_asm_includes/)
5000 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5001 if ($asminclude > 0) {
5002 if ($realfile =~ m{^arch/}) {
5003 CHK("ARCH_INCLUDE_LINUX",
5004 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5006 WARN("INCLUDE_LINUX",
5007 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5013 # multi-statement macros should be enclosed in a do while loop, grab the
5014 # first statement and ensure its the whole macro if its not enclosed
5015 # in a known good container
5016 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5017 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5020 my ($off, $dstat, $dcond, $rest);
5022 my $has_flow_statement = 0;
5023 my $has_arg_concat = 0;
5024 ($dstat, $dcond, $ln, $cnt, $off) =
5025 ctx_statement_block($linenr, $realcnt, 0);
5027 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5028 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5030 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5031 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5033 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5034 my $define_args = $1;
5035 my $define_stmt = $dstat;
5038 if (defined $define_args && $define_args ne "") {
5039 $define_args = substr($define_args, 1, length($define_args) - 2);
5040 $define_args =~ s/\s*//g;
5041 $define_args =~ s/\\\+?//g;
5042 @def_args = split(",", $define_args);
5046 $dstat =~ s/\\\n.//g;
5047 $dstat =~ s/^\s*//s;
5048 $dstat =~ s/\s*$//s;
5050 # Flatten any parentheses and braces
5051 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5052 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5053 $dstat =~ s/.\[[^\[\]]*\]/1/)
5057 # Flatten any obvious string concatentation.
5058 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5059 $dstat =~ s/$Ident\s*($String)/$1/)
5063 # Make asm volatile uses seem like a generic function
5064 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5066 my $exceptions = qr{
5079 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5082 my $stmt_cnt = statement_rawlines($ctx);
5083 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5086 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5087 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5088 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5089 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5090 $dstat !~ /$exceptions/ &&
5091 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5092 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5093 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5094 $dstat !~ /^for\s*$Constant$/ && # for (...)
5095 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5096 $dstat !~ /^do\s*{/ && # do {...
5097 $dstat !~ /^\(\{/ && # ({...
5098 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5100 if ($dstat =~ /^\s*if\b/) {
5101 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5102 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5103 } elsif ($dstat =~ /;/) {
5104 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5105 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5107 ERROR("COMPLEX_MACRO",
5108 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5113 # Make $define_stmt single line, comment-free, etc
5114 my @stmt_array = split('\n', $define_stmt);
5117 foreach my $l (@stmt_array) {
5122 } elsif ($l =~ /^[\+ ]/) {
5123 $define_stmt .= substr($l, 1);
5126 $define_stmt =~ s/$;//g;
5127 $define_stmt =~ s/\s+/ /g;
5128 $define_stmt = trim($define_stmt);
5130 # check if any macro arguments are reused (ignore '...' and 'type')
5131 foreach my $arg (@def_args) {
5132 next if ($arg =~ /\.\.\./);
5133 next if ($arg =~ /^type$/i);
5134 my $tmp_stmt = $define_stmt;
5135 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5136 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5137 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5138 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5140 CHK("MACRO_ARG_REUSE",
5141 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5143 # check if any macro arguments may have other precedence issues
5144 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5145 ((defined($1) && $1 ne ',') ||
5146 (defined($2) && $2 ne ','))) {
5147 CHK("MACRO_ARG_PRECEDENCE",
5148 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5152 # check for macros with flow control, but without ## concatenation
5153 # ## concatenation is commonly a macro that defines a function so ignore those
5154 if ($has_flow_statement && !$has_arg_concat) {
5155 my $cnt = statement_rawlines($ctx);
5156 my $herectx = get_stat_here($linenr, $cnt, $here);
5158 WARN("MACRO_WITH_FLOW_CONTROL",
5159 "Macros with flow control statements should be avoided\n" . "$herectx");
5162 # check for line continuations outside of #defines, preprocessor #, and asm
5165 if ($prevline !~ /^..*\\$/ &&
5166 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5167 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5168 $line =~ /^\+.*\\$/) {
5169 WARN("LINE_CONTINUATIONS",
5170 "Avoid unnecessary line continuations\n" . $herecurr);
5174 # do {} while (0) macro tests:
5175 # single-statement macros do not need to be enclosed in do while (0) loop,
5176 # macro should not end with a semicolon
5177 if ($perl_version_ok &&
5178 $realfile !~ m@/vmlinux.lds.h$@ &&
5179 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5182 my ($off, $dstat, $dcond, $rest);
5184 ($dstat, $dcond, $ln, $cnt, $off) =
5185 ctx_statement_block($linenr, $realcnt, 0);
5188 $dstat =~ s/\\\n.//g;
5191 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5196 my $cnt = statement_rawlines($ctx);
5197 my $herectx = get_stat_here($linenr, $cnt, $here);
5199 if (($stmts =~ tr/;/;/) == 1 &&
5200 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5201 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5202 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5204 if (defined $semis && $semis ne "") {
5205 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5206 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5208 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5210 my $cnt = statement_rawlines($ctx);
5211 my $herectx = get_stat_here($linenr, $cnt, $here);
5213 WARN("TRAILING_SEMICOLON",
5214 "macros should not use a trailing semicolon\n" . "$herectx");
5218 # check for redundant bracing round if etc
5219 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5220 my ($level, $endln, @chunks) =
5221 ctx_statement_full($linenr, $realcnt, 1);
5222 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5223 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5224 if ($#chunks > 0 && $level == 0) {
5228 my $herectx = $here . "\n";
5229 my $ln = $linenr - 1;
5230 for my $chunk (@chunks) {
5231 my ($cond, $block) = @{$chunk};
5233 # If the condition carries leading newlines, then count those as offsets.
5234 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5235 my $offset = statement_rawlines($whitespace) - 1;
5237 $allowed[$allow] = 0;
5238 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5240 # We have looked at and allowed this specific line.
5241 $suppress_ifbraces{$ln + $offset} = 1;
5243 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5244 $ln += statement_rawlines($block) - 1;
5246 substr($block, 0, length($cond), '');
5248 $seen++ if ($block =~ /^\s*{/);
5250 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5251 if (statement_lines($cond) > 1) {
5252 #print "APW: ALLOWED: cond<$cond>\n";
5253 $allowed[$allow] = 1;
5255 if ($block =~/\b(?:if|for|while)\b/) {
5256 #print "APW: ALLOWED: block<$block>\n";
5257 $allowed[$allow] = 1;
5259 if (statement_block_size($block) > 1) {
5260 #print "APW: ALLOWED: lines block<$block>\n";
5261 $allowed[$allow] = 1;
5266 my $sum_allowed = 0;
5267 foreach (@allowed) {
5270 if ($sum_allowed == 0) {
5272 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5273 } elsif ($sum_allowed != $allow &&
5276 "braces {} should be used on all arms of this statement\n" . $herectx);
5281 if (!defined $suppress_ifbraces{$linenr - 1} &&
5282 $line =~ /\b(if|while|for|else)\b/) {
5285 # Check the pre-context.
5286 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5287 #print "APW: ALLOWED: pre<$1>\n";
5291 my ($level, $endln, @chunks) =
5292 ctx_statement_full($linenr, $realcnt, $-[0]);
5294 # Check the condition.
5295 my ($cond, $block) = @{$chunks[0]};
5296 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5297 if (defined $cond) {
5298 substr($block, 0, length($cond), '');
5300 if (statement_lines($cond) > 1) {
5301 #print "APW: ALLOWED: cond<$cond>\n";
5304 if ($block =~/\b(?:if|for|while)\b/) {
5305 #print "APW: ALLOWED: block<$block>\n";
5308 if (statement_block_size($block) > 1) {
5309 #print "APW: ALLOWED: lines block<$block>\n";
5312 # Check the post-context.
5313 if (defined $chunks[1]) {
5314 my ($cond, $block) = @{$chunks[1]};
5315 if (defined $cond) {
5316 substr($block, 0, length($cond), '');
5318 if ($block =~ /^\s*\{/) {
5319 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5323 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5324 my $cnt = statement_rawlines($block);
5325 my $herectx = get_stat_here($linenr, $cnt, $here);
5328 "braces {} are not necessary for single statement blocks\n" . $herectx);
5332 # check for single line unbalanced braces
5333 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5334 $sline =~ /^.\s*else\s*\{\s*$/) {
5335 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5338 # check for unnecessary blank lines around braces
5339 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5341 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5342 $fix && $prevrawline =~ /^\+/) {
5343 fix_delete_line($fixlinenr - 1, $prevrawline);
5346 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5348 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5350 fix_delete_line($fixlinenr, $rawline);
5354 # no volatiles please
5355 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5356 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5358 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5361 # Check for user-visible strings broken across lines, which breaks the ability
5362 # to grep for the string. Make exceptions when the previous string ends in a
5363 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5364 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5365 if ($line =~ /^\+\s*$String/ &&
5366 $prevline =~ /"\s*$/ &&
5367 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5368 if (WARN("SPLIT_STRING",
5369 "quoted string split across lines\n" . $hereprev) &&
5371 $prevrawline =~ /^\+.*"\s*$/ &&
5372 $last_coalesced_string_linenr != $linenr - 1) {
5373 my $extracted_string = get_quoted_string($line, $rawline);
5374 my $comma_close = "";
5375 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5379 fix_delete_line($fixlinenr - 1, $prevrawline);
5380 fix_delete_line($fixlinenr, $rawline);
5381 my $fixedline = $prevrawline;
5382 $fixedline =~ s/"\s*$//;
5383 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5384 fix_insert_line($fixlinenr - 1, $fixedline);
5385 $fixedline = $rawline;
5386 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5387 if ($fixedline !~ /\+\s*$/) {
5388 fix_insert_line($fixlinenr, $fixedline);
5390 $last_coalesced_string_linenr = $linenr;
5394 # check for missing a space in a string concatenation
5395 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5396 WARN('MISSING_SPACE',
5397 "break quoted strings at a space character\n" . $hereprev);
5400 # check for an embedded function name in a string when the function is known
5401 # This does not work very well for -f --file checking as it depends on patch
5402 # context providing the function name or a single line form for in-file
5403 # function declarations
5404 if ($line =~ /^\+.*$String/ &&
5405 defined($context_function) &&
5406 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5407 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5408 WARN("EMBEDDED_FUNCTION_NAME",
5409 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5412 # check for spaces before a quoted newline
5413 if ($rawline =~ /^.*\".*\s\\n/) {
5414 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5415 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5417 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5422 # concatenated string without spaces between elements
5423 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5424 if (CHK("CONCATENATED_STRING",
5425 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5427 while ($line =~ /($String)/g) {
5428 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5429 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5430 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5435 # uncoalesced string fragments
5436 if ($line =~ /$String\s*"/) {
5437 if (WARN("STRING_FRAGMENTS",
5438 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5440 while ($line =~ /($String)(?=\s*")/g) {
5441 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5442 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5447 # check for non-standard and hex prefixed decimal printf formats
5448 my $show_L = 1; #don't show the same defect twice
5450 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5451 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5452 $string =~ s/%%/__/g;
5454 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5456 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5460 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5462 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5465 # check for 0x<decimal>
5466 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5467 ERROR("PRINTF_0XDECIMAL",
5468 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5472 # check for line continuations in quoted strings with odd counts of "
5473 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5474 WARN("LINE_CONTINUATIONS",
5475 "Avoid line continuations in quoted strings\n" . $herecurr);
5479 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5481 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5485 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5487 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5490 # check for needless "if (<foo>) fn(<foo>)" uses
5491 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5492 my $tested = quotemeta($1);
5493 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5494 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5496 if (WARN('NEEDLESS_IF',
5497 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5500 my $leading_tabs = "";
5501 my $new_leading_tabs = "";
5502 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5507 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5508 $new_leading_tabs = $1;
5509 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5516 fix_delete_line($fixlinenr - 1, $prevrawline);
5517 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5523 # check for unnecessary "Out of Memory" messages
5524 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5525 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5526 (defined $1 || defined $3) &&
5529 my $testline = $lines[$linenr - 3];
5531 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5532 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5534 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|kmemdup|(?:dev_)?alloc_skb)/) {
5536 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5540 # check for logging functions with KERN_<LEVEL>
5541 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5542 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5544 if (WARN("UNNECESSARY_KERN_LEVEL",
5545 "Possible unnecessary $level\n" . $herecurr) &&
5547 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5551 # check for logging continuations
5552 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5553 WARN("LOGGING_CONTINUATION",
5554 "Avoid logging continuation uses where feasible\n" . $herecurr);
5557 # check for mask then right shift without a parentheses
5558 if ($perl_version_ok &&
5559 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5560 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5561 WARN("MASK_THEN_SHIFT",
5562 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5565 # check for pointer comparisons to NULL
5566 if ($perl_version_ok) {
5567 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5570 $equal = "" if ($4 eq "!=");
5571 if (CHK("COMPARISON_TO_NULL",
5572 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5574 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5579 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5580 if ($line =~ /(\b$InitAttribute\b)/) {
5582 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5585 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5586 ERROR("MISPLACED_INIT",
5587 "$attr should be placed after $var\n" . $herecurr)) ||
5588 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5589 WARN("MISPLACED_INIT",
5590 "$attr should be placed after $var\n" . $herecurr))) &&
5592 $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;
5597 # check for $InitAttributeData (ie: __initdata) with const
5598 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5600 $attr =~ /($InitAttributePrefix)(.*)/;
5601 my $attr_prefix = $1;
5603 if (ERROR("INIT_ATTRIBUTE",
5604 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5606 $fixed[$fixlinenr] =~
5607 s/$InitAttributeData/${attr_prefix}initconst/;
5611 # check for $InitAttributeConst (ie: __initconst) without const
5612 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5614 if (ERROR("INIT_ATTRIBUTE",
5615 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5617 my $lead = $fixed[$fixlinenr] =~
5618 /(^\+\s*(?:static\s+))/;
5620 $lead = "$lead " if ($lead !~ /^\+$/);
5621 $lead = "${lead}const ";
5622 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5626 # check for __read_mostly with const non-pointer (should just be const)
5627 if ($line =~ /\b__read_mostly\b/ &&
5628 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5629 if (ERROR("CONST_READ_MOSTLY",
5630 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5632 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5636 # don't use __constant_<foo> functions outside of include/uapi/
5637 if ($realfile !~ m@^include/uapi/@ &&
5638 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5639 my $constant_func = $1;
5640 my $func = $constant_func;
5641 $func =~ s/^__constant_//;
5642 if (WARN("CONSTANT_CONVERSION",
5643 "$constant_func should be $func\n" . $herecurr) &&
5645 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5649 # prefer usleep_range over udelay
5650 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5652 # ignore udelay's < 10, however
5653 if (! ($delay < 10) ) {
5655 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5657 if ($delay > 2000) {
5659 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5663 # warn about unexpectedly long msleep's
5664 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5667 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5671 # check for comparisons of jiffies
5672 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5673 WARN("JIFFIES_COMPARISON",
5674 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5677 # check for comparisons of get_jiffies_64()
5678 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5679 WARN("JIFFIES_COMPARISON",
5680 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5683 # warn about #ifdefs in C files
5684 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5685 # print "#ifdef in C files should be avoided\n";
5686 # print "$herecurr";
5690 # warn about spacing in #ifdefs
5691 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5692 if (ERROR("SPACING",
5693 "exactly one space required after that #$1\n" . $herecurr) &&
5695 $fixed[$fixlinenr] =~
5696 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5701 # check for spinlock_t definitions without a comment.
5702 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5703 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5705 if (!ctx_has_comment($first_line, $linenr)) {
5706 CHK("UNCOMMENTED_DEFINITION",
5707 "$1 definition without comment\n" . $herecurr);
5710 # check for memory barriers without a comment.
5716 read_barrier_depends
5718 my $barrier_stems = qr{
5726 my $all_barriers = qr{
5728 smp_(?:$barrier_stems)|
5729 virt_(?:$barrier_stems)
5732 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5733 if (!ctx_has_comment($first_line, $linenr)) {
5734 WARN("MEMORY_BARRIER",
5735 "memory barrier without comment\n" . $herecurr);
5739 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5741 if ($realfile !~ m@^include/asm-generic/@ &&
5742 $realfile !~ m@/barrier\.h$@ &&
5743 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5744 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5745 WARN("MEMORY_BARRIER",
5746 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5749 # check for waitqueue_active without a comment.
5750 if ($line =~ /\bwaitqueue_active\s*\(/) {
5751 if (!ctx_has_comment($first_line, $linenr)) {
5752 WARN("WAITQUEUE_ACTIVE",
5753 "waitqueue_active without comment\n" . $herecurr);
5757 # check for smp_read_barrier_depends and read_barrier_depends
5758 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5759 WARN("READ_BARRIER_DEPENDS",
5760 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5763 # check of hardware specific defines
5764 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5766 "architecture specific defines should be avoided\n" . $herecurr);
5769 # check that the storage class is not after a type
5770 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5771 WARN("STORAGE_CLASS",
5772 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5774 # Check that the storage class is at the beginning of a declaration
5775 if ($line =~ /\b$Storage\b/ &&
5776 $line !~ /^.\s*$Storage/ &&
5777 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5778 $1 !~ /[\,\)]\s*$/) {
5779 WARN("STORAGE_CLASS",
5780 "storage class should be at the beginning of the declaration\n" . $herecurr);
5783 # check the location of the inline attribute, that it is between
5784 # storage class and type.
5785 if ($line =~ /\b$Type\s+$Inline\b/ ||
5786 $line =~ /\b$Inline\s+$Storage\b/) {
5787 ERROR("INLINE_LOCATION",
5788 "inline keyword should sit between storage class and type\n" . $herecurr);
5791 # Check for __inline__ and __inline, prefer inline
5792 if ($realfile !~ m@\binclude/uapi/@ &&
5793 $line =~ /\b(__inline__|__inline)\b/) {
5795 "plain inline is preferred over $1\n" . $herecurr) &&
5797 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5802 # Check for __attribute__ packed, prefer __packed
5803 if ($realfile !~ m@\binclude/uapi/@ &&
5804 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5805 WARN("PREFER_PACKED",
5806 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5809 # Check for __attribute__ aligned, prefer __aligned
5810 if ($realfile !~ m@\binclude/uapi/@ &&
5811 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5812 WARN("PREFER_ALIGNED",
5813 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5816 # Check for __attribute__ format(printf, prefer __printf
5817 if ($realfile !~ m@\binclude/uapi/@ &&
5818 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5819 if (WARN("PREFER_PRINTF",
5820 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5822 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5827 # Check for __attribute__ format(scanf, prefer __scanf
5828 if ($realfile !~ m@\binclude/uapi/@ &&
5829 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5830 if (WARN("PREFER_SCANF",
5831 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5833 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5837 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5838 if ($perl_version_ok &&
5839 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5840 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5841 $line =~ /\b__weak\b/)) {
5842 ERROR("WEAK_DECLARATION",
5843 "Using weak declarations can have unintended link defects\n" . $herecurr);
5846 # check for c99 types like uint8_t used outside of uapi/ and tools/
5847 if ($realfile !~ m@\binclude/uapi/@ &&
5848 $realfile !~ m@\btools/@ &&
5849 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5851 if ($type =~ /\b($typeC99Typedefs)\b/) {
5853 my $kernel_type = 'u';
5854 $kernel_type = 's' if ($type =~ /^_*[si]/);
5857 if (CHK("PREFER_KERNEL_TYPES",
5858 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5860 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5865 # check for cast of C90 native int or longer types constants
5866 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5869 if (WARN("TYPECAST_INT_CONSTANT",
5870 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5873 my $newconst = $const;
5874 $newconst =~ s/${Int_type}$//;
5875 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5876 if ($cast =~ /\blong\s+long\b/) {
5878 } elsif ($cast =~ /\blong\b/) {
5881 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5885 # check for sizeof(&)
5886 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5887 WARN("SIZEOF_ADDRESS",
5888 "sizeof(& should be avoided\n" . $herecurr);
5891 # check for sizeof without parenthesis
5892 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5893 if (WARN("SIZEOF_PARENTHESIS",
5894 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5896 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5900 # check for struct spinlock declarations
5901 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5902 WARN("USE_SPINLOCK_T",
5903 "struct spinlock should be spinlock_t\n" . $herecurr);
5906 # check for seq_printf uses that could be seq_puts
5907 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5908 my $fmt = get_quoted_string($line, $rawline);
5911 if (WARN("PREFER_SEQ_PUTS",
5912 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5914 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5919 # check for vsprintf extension %p<foo> misuses
5920 if ($perl_version_ok &&
5922 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5923 $1 !~ /^_*volatile_*$/) {
5926 my $lc = $stat =~ tr@\n@@;
5927 $lc = $lc + $linenr;
5928 for (my $count = $linenr; $count <= $lc; $count++) {
5931 my $bad_specifier = "";
5932 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5935 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5938 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5939 $bad_specifier = $specifier;
5942 if ($extension eq "x" && !defined($stat_real)) {
5943 if (!defined($stat_real)) {
5944 $stat_real = get_stat_real($linenr, $lc);
5946 WARN("VSPRINTF_SPECIFIER_PX",
5947 "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n");
5950 if ($bad_specifier ne "") {
5951 my $stat_real = get_stat_real($linenr, $lc);
5952 my $ext_type = "Invalid";
5954 if ($bad_specifier =~ /p[Ff]/) {
5955 $ext_type = "Deprecated";
5956 $use = " - use %pS instead";
5957 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5960 WARN("VSPRINTF_POINTER_EXTENSION",
5961 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5966 # Check for misused memsets
5967 if ($perl_version_ok &&
5969 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5975 if ($ms_size =~ /^(0x|)0$/i) {
5977 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5978 } elsif ($ms_size =~ /^(0x|)1$/i) {
5980 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5984 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5985 # if ($perl_version_ok &&
5987 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5988 # if (WARN("PREFER_ETHER_ADDR_COPY",
5989 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5991 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5995 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5996 # if ($perl_version_ok &&
5998 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5999 # WARN("PREFER_ETHER_ADDR_EQUAL",
6000 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6003 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6004 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6005 # if ($perl_version_ok &&
6007 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6011 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6012 # if (WARN("PREFER_ETH_ZERO_ADDR",
6013 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6015 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6017 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6018 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6019 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6021 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6026 # typecasts on min/max could be min_t/max_t
6027 if ($perl_version_ok &&
6029 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6030 if (defined $2 || defined $7) {
6032 my $cast1 = deparenthesize($2);
6034 my $cast2 = deparenthesize($7);
6038 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6039 $cast = "$cast1 or $cast2";
6040 } elsif ($cast1 ne "") {
6046 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6050 # check usleep_range arguments
6051 if ($perl_version_ok &&
6053 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6057 WARN("USLEEP_RANGE",
6058 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6059 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6061 WARN("USLEEP_RANGE",
6062 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6066 # check for naked sscanf
6067 if ($perl_version_ok &&
6069 $line =~ /\bsscanf\b/ &&
6070 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6071 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6072 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6073 my $lc = $stat =~ tr@\n@@;
6074 $lc = $lc + $linenr;
6075 my $stat_real = get_stat_real($linenr, $lc);
6076 WARN("NAKED_SSCANF",
6077 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6080 # check for simple sscanf that should be kstrto<foo>
6081 if ($perl_version_ok &&
6083 $line =~ /\bsscanf\b/) {
6084 my $lc = $stat =~ tr@\n@@;
6085 $lc = $lc + $linenr;
6086 my $stat_real = get_stat_real($linenr, $lc);
6087 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6089 my $count = $format =~ tr@%@%@;
6091 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6092 WARN("SSCANF_TO_KSTRTO",
6093 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6098 # check for new externs in .h files.
6099 if ($realfile =~ /\.h$/ &&
6100 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6101 if (CHK("AVOID_EXTERNS",
6102 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6104 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6108 # check for new externs in .c files.
6109 if ($realfile =~ /\.c$/ && defined $stat &&
6110 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6112 my $function_name = $1;
6113 my $paren_space = $2;
6116 if (defined $cond) {
6117 substr($s, 0, length($cond), '');
6119 if ($s =~ /^\s*;/ &&
6120 $function_name ne 'uninitialized_var')
6122 WARN("AVOID_EXTERNS",
6123 "externs should be avoided in .c files\n" . $herecurr);
6126 if ($paren_space =~ /\n/) {
6127 WARN("FUNCTION_ARGUMENTS",
6128 "arguments for function declarations should follow identifier\n" . $herecurr);
6131 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6132 $stat =~ /^.\s*extern\s+/)
6134 WARN("AVOID_EXTERNS",
6135 "externs should be avoided in .c files\n" . $herecurr);
6138 # check for function declarations that have arguments without identifier names
6139 if (defined $stat &&
6140 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6142 my $args = trim($1);
6143 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6145 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6146 WARN("FUNCTION_ARGUMENTS",
6147 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6152 # check for function definitions
6153 if ($perl_version_ok &&
6155 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6156 $context_function = $1;
6158 # check for multiline function definition with misplaced open brace
6160 my $cnt = statement_rawlines($stat);
6161 my $herectx = $here . "\n";
6162 for (my $n = 0; $n < $cnt; $n++) {
6163 my $rl = raw_line($linenr, $n);
6164 $herectx .= $rl . "\n";
6165 $ok = 1 if ($rl =~ /^[ \+]\{/);
6166 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6167 last if $rl =~ /^[ \+].*\{/;
6171 "open brace '{' following function definitions go on the next line\n" . $herectx);
6175 # checks for new __setup's
6176 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6179 if (!grep(/$name/, @setup_docs)) {
6180 CHK("UNDOCUMENTED_SETUP",
6181 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6185 # check for pointless casting of kmalloc return
6186 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6187 WARN("UNNECESSARY_CASTS",
6188 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6192 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6193 if ($perl_version_ok &&
6194 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6195 CHK("ALLOC_SIZEOF_STRUCT",
6196 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6199 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6200 if ($perl_version_ok &&
6202 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6206 my $newfunc = "kmalloc_array";
6207 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6210 if ($a1 =~ /^sizeof\s*\S/) {
6214 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6215 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6216 my $cnt = statement_rawlines($stat);
6217 my $herectx = get_stat_here($linenr, $cnt, $here);
6219 if (WARN("ALLOC_WITH_MULTIPLY",
6220 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6223 $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;
6228 # check for krealloc arg reuse
6229 if ($perl_version_ok &&
6230 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6232 WARN("KREALLOC_ARG_REUSE",
6233 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6236 # check for alloc argument mismatch
6237 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6238 WARN("ALLOC_ARRAY_ARGS",
6239 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6242 # check for multiple semicolons
6243 if ($line =~ /;\s*;\s*$/) {
6244 if (WARN("ONE_SEMICOLON",
6245 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6247 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6251 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6252 if ($realfile !~ m@^include/uapi/@ &&
6253 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6255 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6256 if (CHK("BIT_MACRO",
6257 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6259 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6263 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6264 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6266 if (WARN("PREFER_IS_ENABLED",
6267 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6269 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6273 # check for case / default statements not preceded by break/fallthrough/switch
6274 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6276 my $has_statement = 0;
6278 my $prevline = $linenr;
6279 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6281 my $rline = $rawlines[$prevline - 1];
6282 my $fline = $lines[$prevline - 1];
6283 last if ($fline =~ /^\@\@/);
6284 next if ($fline =~ /^\-/);
6285 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6286 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6287 next if ($fline =~ /^.[\s$;]*$/);
6290 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6292 if (!$has_break && $has_statement) {
6293 WARN("MISSING_BREAK",
6294 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6298 # check for switch/default statements without a break;
6299 if ($perl_version_ok &&
6301 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6302 my $cnt = statement_rawlines($stat);
6303 my $herectx = get_stat_here($linenr, $cnt, $here);
6305 WARN("DEFAULT_NO_BREAK",
6306 "switch default: should use break\n" . $herectx);
6309 # check for gcc specific __FUNCTION__
6310 if ($line =~ /\b__FUNCTION__\b/) {
6311 if (WARN("USE_FUNC",
6312 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6314 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6318 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6319 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6321 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6324 # check for use of yield()
6325 if ($line =~ /\byield\s*\(\s*\)/) {
6327 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6330 # check for comparisons against true and false
6331 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6339 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6341 my $type = lc($otype);
6342 if ($type =~ /^(?:true|false)$/) {
6343 if (("$test" eq "==" && "$type" eq "true") ||
6344 ("$test" eq "!=" && "$type" eq "false")) {
6348 CHK("BOOL_COMPARISON",
6349 "Using comparison to $otype is error prone\n" . $herecurr);
6351 ## maybe suggesting a correct construct would better
6352 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6357 # check for bool bitfields
6358 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6359 WARN("BOOL_BITFIELD",
6360 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6363 # check for bool use in .h files
6364 if ($realfile =~ /\.h$/ &&
6365 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6367 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6370 # check for semaphores initialized locked
6371 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6372 WARN("CONSIDER_COMPLETION",
6373 "consider using a completion\n" . $herecurr);
6376 # recommend kstrto* over simple_strto* and strict_strto*
6377 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6378 WARN("CONSIDER_KSTRTO",
6379 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6382 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6383 if ($line =~ /^.\s*__initcall\s*\(/) {
6384 WARN("USE_DEVICE_INITCALL",
6385 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6388 # check for various structs that are normally const (ops, kgdb, device_tree)
6389 # and avoid what seem like struct definitions 'struct foo {'
6390 if ($line !~ /\bconst\b/ &&
6391 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6392 WARN("CONST_STRUCT",
6393 "struct $1 should normally be const\n" . $herecurr);
6396 # use of NR_CPUS is usually wrong
6397 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6398 if ($line =~ /\bNR_CPUS\b/ &&
6399 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6400 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6401 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6402 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6403 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6406 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6409 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6410 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6411 ERROR("DEFINE_ARCH_HAS",
6412 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6415 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6416 if ($perl_version_ok &&
6417 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6418 WARN("LIKELY_MISUSE",
6419 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6422 # whine mightly about in_atomic
6423 if ($line =~ /\bin_atomic\s*\(/) {
6424 if ($realfile =~ m@^drivers/@) {
6426 "do not use in_atomic in drivers\n" . $herecurr);
6427 } elsif ($realfile !~ m@^kernel/@) {
6429 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6433 # check for mutex_trylock_recursive usage
6434 if ($line =~ /mutex_trylock_recursive/) {
6436 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6439 # check for lockdep_set_novalidate_class
6440 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6441 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6442 if ($realfile !~ m@^kernel/lockdep@ &&
6443 $realfile !~ m@^include/linux/lockdep@ &&
6444 $realfile !~ m@^drivers/base/core@) {
6446 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6450 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6451 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6452 WARN("EXPORTED_WORLD_WRITABLE",
6453 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6456 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6457 # and whether or not function naming is typical and if
6458 # DEVICE_ATTR permissions uses are unusual too
6459 if ($perl_version_ok &&
6461 $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) {
6466 my $octal_perms = perms_to_octal($perms);
6467 if ($show =~ /^${var}_show$/ &&
6468 $store =~ /^${var}_store$/ &&
6469 $octal_perms eq "0644") {
6470 if (WARN("DEVICE_ATTR_RW",
6471 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6473 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6475 } elsif ($show =~ /^${var}_show$/ &&
6476 $store =~ /^NULL$/ &&
6477 $octal_perms eq "0444") {
6478 if (WARN("DEVICE_ATTR_RO",
6479 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6481 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6483 } elsif ($show =~ /^NULL$/ &&
6484 $store =~ /^${var}_store$/ &&
6485 $octal_perms eq "0200") {
6486 if (WARN("DEVICE_ATTR_WO",
6487 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6489 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6491 } elsif ($octal_perms eq "0644" ||
6492 $octal_perms eq "0444" ||
6493 $octal_perms eq "0200") {
6494 my $newshow = "$show";
6495 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6496 my $newstore = $store;
6497 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6499 if ($show ne $newshow) {
6500 $rename .= " '$show' to '$newshow'";
6502 if ($store ne $newstore) {
6503 $rename .= " '$store' to '$newstore'";
6505 WARN("DEVICE_ATTR_FUNCTIONS",
6506 "Consider renaming function(s)$rename\n" . $herecurr);
6508 WARN("DEVICE_ATTR_PERMS",
6509 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6513 # Mode permission misuses where it seems decimal should be octal
6514 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6515 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6516 # specific definition of not visible in sysfs.
6517 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6518 # use the default permissions
6519 if ($perl_version_ok &&
6521 $line =~ /$mode_perms_search/) {
6522 foreach my $entry (@mode_permission_funcs) {
6523 my $func = $entry->[0];
6524 my $arg_pos = $entry->[1];
6526 my $lc = $stat =~ tr@\n@@;
6527 $lc = $lc + $linenr;
6528 my $stat_real = get_stat_real($linenr, $lc);
6533 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6535 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6536 if ($stat =~ /$test/) {
6538 $val = $6 if ($skip_args ne "");
6539 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6540 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6541 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6542 ERROR("NON_OCTAL_PERMISSIONS",
6543 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6545 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6546 ERROR("EXPORTED_WORLD_WRITABLE",
6547 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6553 # check for uses of S_<PERMS> that could be octal for readability
6554 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6556 my $octal = perms_to_octal($oval);
6557 if (WARN("SYMBOLIC_PERMS",
6558 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6560 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6564 # validate content of MODULE_LICENSE against list from include/linux/module.h
6565 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6566 my $extracted_string = get_quoted_string($line, $rawline);
6567 my $valid_licenses = qr{
6570 GPL\ and\ additional\ rights|
6576 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6577 WARN("MODULE_LICENSE",
6578 "unknown module license " . $extracted_string . "\n" . $herecurr);
6583 # If we have no input at all, then there is nothing to report on
6584 # so just keep quiet.
6585 if ($#rawlines == -1) {
6589 # In mailback mode only produce a report in the negative, for
6590 # things that appear to be patches.
6591 if ($mailback && ($clean == 1 || !$is_patch)) {
6595 # This is not a patch, and we are are in 'no-patch' mode so
6597 if (!$chk_patch && !$is_patch) {
6601 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6602 ERROR("NOT_UNIFIED_DIFF",
6603 "Does not appear to be a unified-diff format patch\n");
6605 if ($is_patch && $has_commit_log && $chk_signoff) {
6606 if ($signoff == 0) {
6607 ERROR("MISSING_SIGN_OFF",
6608 "Missing Signed-off-by: line(s)\n");
6609 } elsif (!$authorsignoff) {
6610 WARN("NO_AUTHOR_SIGN_OFF",
6611 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6615 print report_dump();
6616 if ($summary && !($clean == 1 && $quiet == 1)) {
6617 print "$filename " if ($summary_file);
6618 print "total: $cnt_error errors, $cnt_warn warnings, " .
6619 (($check)? "$cnt_chk checks, " : "") .
6620 "$cnt_lines lines checked\n";
6624 # If there were any defects found and not already fixing them
6625 if (!$clean and !$fix) {
6628 NOTE: For some of the reported defects, checkpatch may be able to
6629 mechanically convert to the typical style using --fix or --fix-inplace.
6632 # If there were whitespace errors which cleanpatch can fix
6633 # then suggest that.
6634 if ($rpt_cleaners) {
6638 NOTE: Whitespace errors detected.
6639 You may wish to use scripts/cleanpatch or scripts/cleanfile
6644 if ($clean == 0 && $fix &&
6645 ("@rawlines" ne "@fixed" ||
6646 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6647 my $newfile = $filename;
6648 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6652 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6654 open($f, '>', $newfile)
6655 or die "$P: Can't open $newfile for write\n";
6656 foreach my $fixed_line (@fixed) {
6659 if ($linecount > 3) {
6660 $fixed_line =~ s/^\+//;
6661 print $f $fixed_line . "\n";
6664 print $f $fixed_line . "\n";
6672 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6674 Do _NOT_ trust the results written to this file.
6675 Do _NOT_ submit these changes without inspecting them for correctness.
6677 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6678 No warranties, expressed or implied...
6686 print "$vname has no obvious style problems and is ready for submission.\n";
6688 print "$vname has style problems, please review.\n";