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);
18 my $D = dirname(abs_path($P));
22 use Getopt::Long qw(:config no_auto_abbrev);
52 my $configuration_file = ".checkpatch.conf";
53 my $max_line_length = 80;
54 my $ignore_perl_version = 0;
55 my $minimum_perl_version = 5.10.0;
56 my $min_conf_desc_length = 4;
57 my $spelling_file = "$D/spelling.txt";
59 my $codespellfile = "/usr/share/codespell/dictionary.txt";
60 my $conststructsfile = "$D/const_structs.checkpatch";
61 my $typedefsfile = "";
63 my $allow_c99_comments = 1;
69 Usage: $P [OPTION]... [FILE]...
74 --no-tree run without a kernel tree
75 --no-signoff do not check for 'Signed-off-by' line
76 --patch treat FILE as patchfile (default)
77 --emacs emacs compile window format
78 --terse one line per report
79 --showfile emit diffed file position, not input file position
80 -g, --git treat FILE as a single commit or git revision range
81 single git commit with:
85 multiple git commits with:
89 git merges are ignored
90 -f, --file treat FILE as regular source file
91 --subjective, --strict enable more subjective tests
92 --list-types list the possible message types
93 --types TYPE(,TYPE2...) show only these comma separated message types
94 --ignore TYPE(,TYPE2...) ignore various comma separated message types
95 --show-types show the specific message type in the output
96 --max-line-length=n set the maximum line length, if exceeded, warn
97 --min-conf-desc-length=n set the min description length, if shorter, warn
98 --root=PATH PATH to the kernel tree root
99 --no-summary suppress the per-file summary
100 --mailback only produce a report in case of warnings/errors
101 --summary-file include the filename in summary
102 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
103 'values', 'possible', 'type', and 'attr' (default
105 --test-only=WORD report only warnings/errors containing WORD
107 --fix EXPERIMENTAL - may create horrible results
108 If correctable single-line errors exist, create
109 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
110 with potential errors corrected to the preferred
112 --fix-inplace EXPERIMENTAL - may create horrible results
113 Is the same as --fix, but overwrites the input
114 file. It's your fault if there's no backup or git
115 --ignore-perl-version override checking of perl version. expect
117 --codespell Use the codespell dictionary for spelling/typos
118 (default:/usr/share/codespell/dictionary.txt)
119 --codespellfile Use this codespell dictionary
120 --typedefsfile Read additional types from this file
121 --color[=WHEN] Use colors 'always', 'never', or only when output
122 is a terminal ('auto'). Default is 'auto'.
123 -h, --help, --version display this help and exit
125 When FILE is - read standard input.
133 return grep { !$seen{$_}++ } @_;
143 open(my $script, '<', abs_path($P)) or
144 die "$P: Can't read '$P' $!\n";
146 my $text = <$script>;
150 # Also catch when type or level is passed through a variable
151 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
154 @types = sort(uniq(@types));
155 print("#\tMessage type\n\n");
156 foreach my $type (@types) {
157 print(++$count . "\t" . $type . "\n");
163 my $conf = which_conf($configuration_file);
166 open(my $conffile, '<', "$conf")
167 or warn "$P: Can't find a readable $configuration_file file $!\n";
169 while (<$conffile>) {
172 $line =~ s/\s*\n?$//g;
176 next if ($line =~ m/^\s*#/);
177 next if ($line =~ m/^\s*$/);
179 my @words = split(" ", $line);
180 foreach my $word (@words) {
181 last if ($word =~ m/^#/);
182 push (@conf_args, $word);
186 unshift(@ARGV, @conf_args) if @conf_args;
189 # Perl's Getopt::Long allows options to take optional arguments after a space.
190 # Prevent --color by itself from consuming other arguments
192 if ($_ eq "--color" || $_ eq "-color") {
193 $_ = "--color=$color";
198 'q|quiet+' => \$quiet,
200 'signoff!' => \$chk_signoff,
201 'patch!' => \$chk_patch,
204 'showfile!' => \$showfile,
207 'subjective!' => \$check,
208 'strict!' => \$check,
209 'ignore=s' => \@ignore,
211 'show-types!' => \$show_types,
212 'list-types!' => \$list_types,
213 'max-line-length=i' => \$max_line_length,
214 'min-conf-desc-length=i' => \$min_conf_desc_length,
216 'summary!' => \$summary,
217 'mailback!' => \$mailback,
218 'summary-file!' => \$summary_file,
220 'fix-inplace!' => \$fix_inplace,
221 'ignore-perl-version!' => \$ignore_perl_version,
222 'debug=s' => \%debug,
223 'test-only=s' => \$tst_only,
224 'codespell!' => \$codespell,
225 'codespellfile=s' => \$codespellfile,
226 'typedefsfile=s' => \$typedefsfile,
227 'color=s' => \$color,
228 'no-color' => \$color, #keep old behaviors of -nocolor
229 'nocolor' => \$color, #keep old behaviors of -nocolor
236 list_types(0) if ($list_types);
238 $fix = 1 if ($fix_inplace);
239 $check_orig = $check;
243 my $perl_version_ok = 1;
244 if ($^V && $^V lt $minimum_perl_version) {
245 $perl_version_ok = 0;
246 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
247 exit(1) if (!$ignore_perl_version);
250 #if no filenames are given, push '-' to read patch from stdin
255 if ($color =~ /^[01]$/) {
257 } elsif ($color =~ /^always$/i) {
259 } elsif ($color =~ /^never$/i) {
261 } elsif ($color =~ /^auto$/i) {
262 $color = (-t STDOUT);
264 die "Invalid color mode: $color\n";
267 sub hash_save_array_words {
268 my ($hashRef, $arrayRef) = @_;
270 my @array = split(/,/, join(',', @$arrayRef));
271 foreach my $word (@array) {
272 $word =~ s/\s*\n?$//g;
275 $word =~ tr/[a-z]/[A-Z]/;
277 next if ($word =~ m/^\s*#/);
278 next if ($word =~ m/^\s*$/);
284 sub hash_show_words {
285 my ($hashRef, $prefix) = @_;
287 if (keys %$hashRef) {
288 print "\nNOTE: $prefix message types:";
289 foreach my $word (sort keys %$hashRef) {
296 hash_save_array_words(\%ignore_type, \@ignore);
297 hash_save_array_words(\%use_type, \@use);
300 my $dbg_possible = 0;
303 for my $key (keys %debug) {
305 eval "\${dbg_$key} = '$debug{$key}';";
309 my $rpt_cleaners = 0;
318 if (!top_of_kernel_tree($root)) {
319 die "$P: $root: --root does not point at a valid tree\n";
322 if (top_of_kernel_tree('.')) {
324 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
325 top_of_kernel_tree($1)) {
330 if (!defined $root) {
331 print "Must be run from the top-level dir. of a kernel tree\n";
336 my $emitted_corrupt = 0;
339 [A-Za-z_][A-Za-z\d_]*
340 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
342 our $Storage = qr{extern|static|asmlinkage};
356 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
357 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
358 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
359 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
360 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
362 # Notes to $Attribute:
363 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
384 ____cacheline_aligned|
385 ____cacheline_aligned_in_smp|
386 ____cacheline_internodealigned_in_smp|
390 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
391 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
392 our $Lval = qr{$Ident(?:$Member)*};
394 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
395 our $Binary = qr{(?i)0b[01]+$Int_type?};
396 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
397 our $Int = qr{[0-9]+$Int_type?};
398 our $Octal = qr{0[0-7]+$Int_type?};
399 our $String = qr{"[X\t]*"};
400 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
401 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
402 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
403 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
404 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
405 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
406 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
407 our $Arithmetic = qr{\+|-|\*|\/|%};
411 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
414 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
418 our $NonptrTypeMisordered;
419 our $NonptrTypeWithAttr;
423 our $DeclareMisordered;
425 our $NON_ASCII_UTF8 = qr{
426 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
427 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
428 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
429 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
430 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
431 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
432 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
436 [\x09\x0A\x0D\x20-\x7E] # ASCII
440 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
441 our $typeOtherOSTypedefs = qr{(?x:
442 u_(?:char|short|int|long) | # bsd
443 u(?:nchar|short|int|long) # sysv
445 our $typeKernelTypedefs = qr{(?x:
446 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
449 our $typeTypedefs = qr{(?x:
451 $typeOtherOSTypedefs\b|
452 $typeKernelTypedefs\b
455 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
457 our $logFunctions = qr{(?x:
458 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
459 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
461 WARN(?:_RATELIMIT|_ONCE|)|
464 seq_vprintf|seq_printf|seq_puts
467 our $signature_tags = qr{(?xi:
478 our @typeListMisordered = (
479 qr{char\s+(?:un)?signed},
480 qr{int\s+(?:(?:un)?signed\s+)?short\s},
481 qr{int\s+short(?:\s+(?:un)?signed)},
482 qr{short\s+int(?:\s+(?:un)?signed)},
483 qr{(?:un)?signed\s+int\s+short},
484 qr{short\s+(?:un)?signed},
485 qr{long\s+int\s+(?:un)?signed},
486 qr{int\s+long\s+(?:un)?signed},
487 qr{long\s+(?:un)?signed\s+int},
488 qr{int\s+(?:un)?signed\s+long},
489 qr{int\s+(?:un)?signed},
490 qr{int\s+long\s+long\s+(?:un)?signed},
491 qr{long\s+long\s+int\s+(?:un)?signed},
492 qr{long\s+long\s+(?:un)?signed\s+int},
493 qr{long\s+long\s+(?:un)?signed},
494 qr{long\s+(?:un)?signed},
499 qr{(?:(?:un)?signed\s+)?char},
500 qr{(?:(?:un)?signed\s+)?short\s+int},
501 qr{(?:(?:un)?signed\s+)?short},
502 qr{(?:(?:un)?signed\s+)?int},
503 qr{(?:(?:un)?signed\s+)?long\s+int},
504 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
505 qr{(?:(?:un)?signed\s+)?long\s+long},
506 qr{(?:(?:un)?signed\s+)?long},
515 qr{${Ident}_handler},
516 qr{${Ident}_handler_fn},
520 our $C90_int_types = qr{(?x:
521 long\s+long\s+int\s+(?:un)?signed|
522 long\s+long\s+(?:un)?signed\s+int|
523 long\s+long\s+(?:un)?signed|
524 (?:(?:un)?signed\s+)?long\s+long\s+int|
525 (?:(?:un)?signed\s+)?long\s+long|
526 int\s+long\s+long\s+(?:un)?signed|
527 int\s+(?:(?:un)?signed\s+)?long\s+long|
529 long\s+int\s+(?:un)?signed|
530 long\s+(?:un)?signed\s+int|
531 long\s+(?:un)?signed|
532 (?:(?:un)?signed\s+)?long\s+int|
533 (?:(?:un)?signed\s+)?long|
534 int\s+long\s+(?:un)?signed|
535 int\s+(?:(?:un)?signed\s+)?long|
538 (?:(?:un)?signed\s+)?int
541 our @typeListFile = ();
542 our @typeListWithAttr = (
544 qr{struct\s+$InitAttribute\s+$Ident},
545 qr{union\s+$InitAttribute\s+$Ident},
548 our @modifierList = (
551 our @modifierListFile = ();
553 our @mode_permission_funcs = (
555 ["module_param_(?:array|named|string)", 4],
556 ["module_param_array_named", 5],
557 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
558 ["proc_create(?:_data|)", 2],
559 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
560 ["IIO_DEV_ATTR_[A-Z_]+", 1],
561 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
562 ["SENSOR_TEMPLATE(?:_2|)", 3],
566 #Create a search pattern for all these functions to speed up a loop below
567 our $mode_perms_search = "";
568 foreach my $entry (@mode_permission_funcs) {
569 $mode_perms_search .= '|' if ($mode_perms_search ne "");
570 $mode_perms_search .= $entry->[0];
572 $mode_perms_search = "(?:${mode_perms_search})";
574 our $mode_perms_world_writable = qr{
582 our %mode_permission_string_types = (
601 #Create a search pattern for all these strings to speed up a loop below
602 our $mode_perms_string_search = "";
603 foreach my $entry (keys %mode_permission_string_types) {
604 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
605 $mode_perms_string_search .= $entry;
607 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
608 our $multi_mode_perms_string_search = qr{
609 ${single_mode_perms_string_search}
610 (?:\s*\|\s*${single_mode_perms_string_search})*
616 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
623 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
624 $curpos = pos($string);
627 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
629 $to |= $mode_permission_string_types{$match};
630 $val .= '\s*\|\s*' if ($val ne "");
634 $oval =~ s/^\s*\|\s*//;
635 $oval =~ s/\s*\|\s*$//;
636 return sprintf("%04o", $to);
639 our $allowed_asm_includes = qr{(?x:
645 # memory.h: ARM has a custom one
647 # Load common spelling mistakes and build regular expression list.
651 if (open(my $spelling, '<', $spelling_file)) {
652 while (<$spelling>) {
655 $line =~ s/\s*\n?$//g;
658 next if ($line =~ m/^\s*#/);
659 next if ($line =~ m/^\s*$/);
661 my ($suspect, $fix) = split(/\|\|/, $line);
663 $spelling_fix{$suspect} = $fix;
667 warn "No typos will be found - file '$spelling_file': $!\n";
671 if (open(my $spelling, '<', $codespellfile)) {
672 while (<$spelling>) {
675 $line =~ s/\s*\n?$//g;
678 next if ($line =~ m/^\s*#/);
679 next if ($line =~ m/^\s*$/);
680 next if ($line =~ m/, disabled/i);
684 my ($suspect, $fix) = split(/->/, $line);
686 $spelling_fix{$suspect} = $fix;
690 warn "No codespell typos will be found - file '$codespellfile': $!\n";
694 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
697 my ($wordsRef, $file) = @_;
699 if (open(my $words, '<', $file)) {
703 $line =~ s/\s*\n?$//g;
706 next if ($line =~ m/^\s*#/);
707 next if ($line =~ m/^\s*$/);
709 print("$file: '$line' invalid - ignored\n");
713 $$wordsRef .= '|' if ($$wordsRef ne "");
723 my $const_structs = "";
724 read_words(\$const_structs, $conststructsfile)
725 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
727 my $typeOtherTypedefs = "";
728 if (length($typedefsfile)) {
729 read_words(\$typeOtherTypedefs, $typedefsfile)
730 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
732 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
735 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
736 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
737 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
738 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
739 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
745 (?:$Modifier\s+|const\s+)*
747 (?:typeof|__typeof__)\s*\([^\)]*\)|
751 (?:\s+$Modifier|\s+const)*
753 $NonptrTypeMisordered = qr{
754 (?:$Modifier\s+|const\s+)*
758 (?:\s+$Modifier|\s+const)*
760 $NonptrTypeWithAttr = qr{
761 (?:$Modifier\s+|const\s+)*
763 (?:typeof|__typeof__)\s*\([^\)]*\)|
767 (?:\s+$Modifier|\s+const)*
771 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
772 (?:\s+$Inline|\s+$Modifier)*
774 $TypeMisordered = qr{
775 $NonptrTypeMisordered
776 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
777 (?:\s+$Inline|\s+$Modifier)*
779 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
780 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
784 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
786 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
787 # requires at least perl version v5.10.0
788 # Any use must be runtime checked with $^V
790 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
791 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
792 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
794 our $declaration_macros = qr{(?x:
795 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
796 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
797 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
798 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
803 return "" if (!defined($string));
805 while ($string =~ /^\s*\(.*\)\s*$/) {
806 $string =~ s@^\s*\(\s*@@;
807 $string =~ s@\s*\)\s*$@@;
810 $string =~ s@\s+@ @g;
815 sub seed_camelcase_file {
818 return if (!(-f $file));
822 open(my $include_file, '<', "$file")
823 or warn "$P: Can't read '$file' $!\n";
824 my $text = <$include_file>;
825 close($include_file);
827 my @lines = split('\n', $text);
829 foreach my $line (@lines) {
830 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
831 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
833 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
835 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
841 sub is_maintained_obsolete {
844 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
846 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
848 return $status =~ /obsolete/i;
851 my $camelcase_seeded = 0;
852 sub seed_camelcase_includes {
853 return if ($camelcase_seeded);
856 my $camelcase_cache = "";
857 my @include_files = ();
859 $camelcase_seeded = 1;
862 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
863 chomp $git_last_include_commit;
864 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
866 my $last_mod_date = 0;
867 $files = `find $root/include -name "*.h"`;
868 @include_files = split('\n', $files);
869 foreach my $file (@include_files) {
870 my $date = POSIX::strftime("%Y%m%d%H%M",
871 localtime((stat $file)[9]));
872 $last_mod_date = $date if ($last_mod_date < $date);
874 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
877 if ($camelcase_cache ne "" && -f $camelcase_cache) {
878 open(my $camelcase_file, '<', "$camelcase_cache")
879 or warn "$P: Can't read '$camelcase_cache' $!\n";
880 while (<$camelcase_file>) {
884 close($camelcase_file);
890 $files = `git ls-files "include/*.h"`;
891 @include_files = split('\n', $files);
894 foreach my $file (@include_files) {
895 seed_camelcase_file($file);
898 if ($camelcase_cache ne "") {
899 unlink glob ".checkpatch-camelcase.*";
900 open(my $camelcase_file, '>', "$camelcase_cache")
901 or warn "$P: Can't write '$camelcase_cache' $!\n";
902 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
903 print $camelcase_file ("$_\n");
905 close($camelcase_file);
909 sub git_commit_info {
910 my ($commit, $id, $desc) = @_;
912 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
914 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
915 $output =~ s/^\s*//gm;
916 my @lines = split("\n", $output);
918 return ($id, $desc) if ($#lines < 0);
920 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
921 # Maybe one day convert this block of bash into something that returns
922 # all matching commit ids, but it's very slow...
924 # echo "checking commits $1..."
925 # git rev-list --remotes | grep -i "^$1" |
926 # while read line ; do
927 # git log --format='%H %s' -1 $line |
928 # echo "commit $(cut -c 1-12,41-)"
930 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
933 $id = substr($lines[0], 0, 12);
934 $desc = substr($lines[0], 41);
940 $chk_signoff = 0 if ($file);
945 my @fixed_inserted = ();
946 my @fixed_deleted = ();
949 # If input is git commits, extract all commits from the commit expressions.
950 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
951 die "$P: No git repository found\n" if ($git && !-e ".git");
955 foreach my $commit_expr (@ARGV) {
957 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
958 $git_range = "-$2 $1";
959 } elsif ($commit_expr =~ m/\.\./) {
960 $git_range = "$commit_expr";
962 $git_range = "-1 $commit_expr";
964 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
965 foreach my $line (split(/\n/, $lines)) {
966 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
967 next if (!defined($1) || !defined($2));
970 unshift(@commits, $sha1);
971 $git_commits{$sha1} = $subject;
974 die "$P: no git commits after extraction!\n" if (@commits == 0);
979 for my $filename (@ARGV) {
982 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
983 die "$P: $filename: git format-patch failed - $!\n";
985 open($FILE, '-|', "diff -u /dev/null $filename") ||
986 die "$P: $filename: diff failed - $!\n";
987 } elsif ($filename eq '-') {
988 open($FILE, '<&STDIN');
990 open($FILE, '<', "$filename") ||
991 die "$P: $filename: open failed - $!\n";
993 if ($filename eq '-') {
994 $vname = 'Your patch';
996 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1002 push(@rawlines, $_);
1006 if ($#ARGV > 0 && $quiet == 0) {
1007 print '-' x length($vname) . "\n";
1009 print '-' x length($vname) . "\n";
1012 if (!process($filename)) {
1018 @fixed_inserted = ();
1019 @fixed_deleted = ();
1021 @modifierListFile = ();
1027 hash_show_words(\%use_type, "Used");
1028 hash_show_words(\%ignore_type, "Ignored");
1030 if (!$perl_version_ok) {
1033 NOTE: perl $^V is not modern enough to detect all possible issues.
1034 An upgrade to at least perl $minimum_perl_version is suggested.
1040 NOTE: If any of the errors are false positives, please report
1041 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1048 sub top_of_kernel_tree {
1052 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1053 "README", "Documentation", "arch", "include", "drivers",
1054 "fs", "init", "ipc", "kernel", "lib", "scripts",
1057 foreach my $check (@tree_check) {
1058 if (! -e $root . '/' . $check) {
1066 my ($formatted_email) = @_;
1072 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1075 $comment = $3 if defined $3;
1076 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1078 $comment = $2 if defined $2;
1079 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1081 $comment = $2 if defined $2;
1082 $formatted_email =~ s/\Q$address\E.*$//;
1083 $name = $formatted_email;
1084 $name = trim($name);
1085 $name =~ s/^\"|\"$//g;
1086 # If there's a name left after stripping spaces and
1087 # leading quotes, and the address doesn't have both
1088 # leading and trailing angle brackets, the address
1090 # "joe smith joe@smith.com" bad
1091 # "joe smith <joe@smith.com" bad
1092 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1099 $name = trim($name);
1100 $name =~ s/^\"|\"$//g;
1101 $address = trim($address);
1102 $address =~ s/^\<|\>$//g;
1104 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1105 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1106 $name = "\"$name\"";
1109 return ($name, $address, $comment);
1113 my ($name, $address) = @_;
1115 my $formatted_email;
1117 $name = trim($name);
1118 $name =~ s/^\"|\"$//g;
1119 $address = trim($address);
1121 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1122 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1123 $name = "\"$name\"";
1126 if ("$name" eq "") {
1127 $formatted_email = "$address";
1129 $formatted_email = "$name <$address>";
1132 return $formatted_email;
1138 foreach my $path (split(/:/, $ENV{PATH})) {
1139 if (-e "$path/$bin") {
1140 return "$path/$bin";
1150 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1151 if (-e "$path/$conf") {
1152 return "$path/$conf";
1164 for my $c (split(//, $str)) {
1168 for (; ($n % 8) != 0; $n++) {
1180 (my $res = shift) =~ tr/\t/ /c;
1187 # Drop the diff line leader and expand tabs
1189 $line = expand_tabs($line);
1191 # Pick the indent from the front of the line.
1192 my ($white) = ($line =~ /^(\s*)/);
1194 return (length($line), length($white));
1197 my $sanitise_quote = '';
1199 sub sanitise_line_reset {
1200 my ($in_comment) = @_;
1203 $sanitise_quote = '*/';
1205 $sanitise_quote = '';
1218 # Always copy over the diff marker.
1219 $res = substr($line, 0, 1);
1221 for ($off = 1; $off < length($line); $off++) {
1222 $c = substr($line, $off, 1);
1224 # Comments we are whacking completely including the begin
1225 # and end, all to $;.
1226 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1227 $sanitise_quote = '*/';
1229 substr($res, $off, 2, "$;$;");
1233 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1234 $sanitise_quote = '';
1235 substr($res, $off, 2, "$;$;");
1239 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1240 $sanitise_quote = '//';
1242 substr($res, $off, 2, $sanitise_quote);
1247 # A \ in a string means ignore the next character.
1248 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1250 substr($res, $off, 2, 'XX');
1255 if ($c eq "'" || $c eq '"') {
1256 if ($sanitise_quote eq '') {
1257 $sanitise_quote = $c;
1259 substr($res, $off, 1, $c);
1261 } elsif ($sanitise_quote eq $c) {
1262 $sanitise_quote = '';
1266 #print "c<$c> SQ<$sanitise_quote>\n";
1267 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1268 substr($res, $off, 1, $;);
1269 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1270 substr($res, $off, 1, $;);
1271 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1272 substr($res, $off, 1, 'X');
1274 substr($res, $off, 1, $c);
1278 if ($sanitise_quote eq '//') {
1279 $sanitise_quote = '';
1282 # The pathname on a #include may be surrounded by '<' and '>'.
1283 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1284 my $clean = 'X' x length($1);
1285 $res =~ s@\<.*\>@<$clean>@;
1287 # The whole of a #error is a string.
1288 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1289 my $clean = 'X' x length($1);
1290 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1293 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1295 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1301 sub get_quoted_string {
1302 my ($line, $rawline) = @_;
1304 return "" if (!defined($line) || !defined($rawline));
1305 return "" if ($line !~ m/($String)/g);
1306 return substr($rawline, $-[0], $+[0] - $-[0]);
1309 sub ctx_statement_block {
1310 my ($linenr, $remain, $off) = @_;
1311 my $line = $linenr - 1;
1314 my $coff = $off - 1;
1328 @stack = (['', 0]) if ($#stack == -1);
1330 #warn "CSB: blk<$blk> remain<$remain>\n";
1331 # If we are about to drop off the end, pull in more
1334 for (; $remain > 0; $line++) {
1335 last if (!defined $lines[$line]);
1336 next if ($lines[$line] =~ /^-/);
1339 $blk .= $lines[$line] . "\n";
1340 $len = length($blk);
1344 # Bail if there is no further context.
1345 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1349 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1355 $c = substr($blk, $off, 1);
1356 $remainder = substr($blk, $off);
1358 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1360 # Handle nested #if/#else.
1361 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1362 push(@stack, [ $type, $level ]);
1363 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1364 ($type, $level) = @{$stack[$#stack - 1]};
1365 } elsif ($remainder =~ /^#\s*endif\b/) {
1366 ($type, $level) = @{pop(@stack)};
1369 # Statement ends at the ';' or a close '}' at the
1371 if ($level == 0 && $c eq ';') {
1375 # An else is really a conditional as long as its not else if
1376 if ($level == 0 && $coff_set == 0 &&
1377 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1378 $remainder =~ /^(else)(?:\s|{)/ &&
1379 $remainder !~ /^else\s+if\b/) {
1380 $coff = $off + length($1) - 1;
1382 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1383 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1386 if (($type eq '' || $type eq '(') && $c eq '(') {
1390 if ($type eq '(' && $c eq ')') {
1392 $type = ($level != 0)? '(' : '';
1394 if ($level == 0 && $coff < $soff) {
1397 #warn "CSB: mark coff<$coff>\n";
1400 if (($type eq '' || $type eq '{') && $c eq '{') {
1404 if ($type eq '{' && $c eq '}') {
1406 $type = ($level != 0)? '{' : '';
1409 if (substr($blk, $off + 1, 1) eq ';') {
1415 # Preprocessor commands end at the newline unless escaped.
1416 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1424 # We are truly at the end, so shuffle to the next line.
1431 my $statement = substr($blk, $soff, $off - $soff + 1);
1432 my $condition = substr($blk, $soff, $coff - $soff + 1);
1434 #warn "STATEMENT<$statement>\n";
1435 #warn "CONDITION<$condition>\n";
1437 #print "coff<$coff> soff<$off> loff<$loff>\n";
1439 return ($statement, $condition,
1440 $line, $remain + 1, $off - $loff + 1, $level);
1443 sub statement_lines {
1446 # Strip the diff line prefixes and rip blank lines at start and end.
1447 $stmt =~ s/(^|\n)./$1/g;
1451 my @stmt_lines = ($stmt =~ /\n/g);
1453 return $#stmt_lines + 2;
1456 sub statement_rawlines {
1459 my @stmt_lines = ($stmt =~ /\n/g);
1461 return $#stmt_lines + 2;
1464 sub statement_block_size {
1467 $stmt =~ s/(^|\n)./$1/g;
1473 my @stmt_lines = ($stmt =~ /\n/g);
1474 my @stmt_statements = ($stmt =~ /;/g);
1476 my $stmt_lines = $#stmt_lines + 2;
1477 my $stmt_statements = $#stmt_statements + 1;
1479 if ($stmt_lines > $stmt_statements) {
1482 return $stmt_statements;
1486 sub ctx_statement_full {
1487 my ($linenr, $remain, $off) = @_;
1488 my ($statement, $condition, $level);
1492 # Grab the first conditional/block pair.
1493 ($statement, $condition, $linenr, $remain, $off, $level) =
1494 ctx_statement_block($linenr, $remain, $off);
1495 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1496 push(@chunks, [ $condition, $statement ]);
1497 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1498 return ($level, $linenr, @chunks);
1501 # Pull in the following conditional/block pairs and see if they
1502 # could continue the statement.
1504 ($statement, $condition, $linenr, $remain, $off, $level) =
1505 ctx_statement_block($linenr, $remain, $off);
1506 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1507 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1509 push(@chunks, [ $condition, $statement ]);
1512 return ($level, $linenr, @chunks);
1516 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1518 my $start = $linenr - 1;
1525 my @stack = ($level);
1526 for ($line = $start; $remain > 0; $line++) {
1527 next if ($rawlines[$line] =~ /^-/);
1530 $blk .= $rawlines[$line];
1532 # Handle nested #if/#else.
1533 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1534 push(@stack, $level);
1535 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1536 $level = $stack[$#stack - 1];
1537 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1538 $level = pop(@stack);
1541 foreach my $c (split(//, $lines[$line])) {
1542 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1548 if ($c eq $close && $level > 0) {
1550 last if ($level == 0);
1551 } elsif ($c eq $open) {
1556 if (!$outer || $level <= 1) {
1557 push(@res, $rawlines[$line]);
1560 last if ($level == 0);
1563 return ($level, @res);
1565 sub ctx_block_outer {
1566 my ($linenr, $remain) = @_;
1568 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1572 my ($linenr, $remain) = @_;
1574 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1578 my ($linenr, $remain, $off) = @_;
1580 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1583 sub ctx_block_level {
1584 my ($linenr, $remain) = @_;
1586 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1588 sub ctx_statement_level {
1589 my ($linenr, $remain, $off) = @_;
1591 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1594 sub ctx_locate_comment {
1595 my ($first_line, $end_line) = @_;
1597 # Catch a comment on the end of the line itself.
1598 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1599 return $current_comment if (defined $current_comment);
1601 # Look through the context and try and figure out if there is a
1604 $current_comment = '';
1605 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1606 my $line = $rawlines[$linenr - 1];
1608 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1611 if ($line =~ m@/\*@) {
1614 if (!$in_comment && $current_comment ne '') {
1615 $current_comment = '';
1617 $current_comment .= $line . "\n" if ($in_comment);
1618 if ($line =~ m@\*/@) {
1623 chomp($current_comment);
1624 return($current_comment);
1626 sub ctx_has_comment {
1627 my ($first_line, $end_line) = @_;
1628 my $cmt = ctx_locate_comment($first_line, $end_line);
1630 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1631 ##print "CMMT: $cmt\n";
1633 return ($cmt ne '');
1637 my ($linenr, $cnt) = @_;
1639 my $offset = $linenr - 1;
1644 $line = $rawlines[$offset++];
1645 next if (defined($line) && $line =~ /^-/);
1653 my ($linenr, $lc) = @_;
1655 my $stat_real = raw_line($linenr, 0);
1656 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1657 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1664 my ($linenr, $cnt, $here) = @_;
1666 my $herectx = $here . "\n";
1667 for (my $n = 0; $n < $cnt; $n++) {
1668 $herectx .= raw_line($linenr, $n) . "\n";
1679 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1682 $coded = sprintf("^%c", unpack('C', $2) + 64);
1691 my $av_preprocessor = 0;
1696 sub annotate_reset {
1697 $av_preprocessor = 0;
1699 @av_paren_type = ('E');
1700 $av_pend_colon = 'O';
1703 sub annotate_values {
1704 my ($stream, $type) = @_;
1707 my $var = '_' x length($stream);
1710 print "$stream\n" if ($dbg_values > 1);
1712 while (length($cur)) {
1713 @av_paren_type = ('E') if ($#av_paren_type < 0);
1714 print " <" . join('', @av_paren_type) .
1715 "> <$type> <$av_pending>" if ($dbg_values > 1);
1716 if ($cur =~ /^(\s+)/o) {
1717 print "WS($1)\n" if ($dbg_values > 1);
1718 if ($1 =~ /\n/ && $av_preprocessor) {
1719 $type = pop(@av_paren_type);
1720 $av_preprocessor = 0;
1723 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1724 print "CAST($1)\n" if ($dbg_values > 1);
1725 push(@av_paren_type, $type);
1728 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1729 print "DECLARE($1)\n" if ($dbg_values > 1);
1732 } elsif ($cur =~ /^($Modifier)\s*/) {
1733 print "MODIFIER($1)\n" if ($dbg_values > 1);
1736 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1737 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1738 $av_preprocessor = 1;
1739 push(@av_paren_type, $type);
1745 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1746 print "UNDEF($1)\n" if ($dbg_values > 1);
1747 $av_preprocessor = 1;
1748 push(@av_paren_type, $type);
1750 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1751 print "PRE_START($1)\n" if ($dbg_values > 1);
1752 $av_preprocessor = 1;
1754 push(@av_paren_type, $type);
1755 push(@av_paren_type, $type);
1758 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1759 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1760 $av_preprocessor = 1;
1762 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1766 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1767 print "PRE_END($1)\n" if ($dbg_values > 1);
1769 $av_preprocessor = 1;
1771 # Assume all arms of the conditional end as this
1772 # one does, and continue as if the #endif was not here.
1773 pop(@av_paren_type);
1774 push(@av_paren_type, $type);
1777 } elsif ($cur =~ /^(\\\n)/o) {
1778 print "PRECONT($1)\n" if ($dbg_values > 1);
1780 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1781 print "ATTR($1)\n" if ($dbg_values > 1);
1782 $av_pending = $type;
1785 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1786 print "SIZEOF($1)\n" if ($dbg_values > 1);
1792 } elsif ($cur =~ /^(if|while|for)\b/o) {
1793 print "COND($1)\n" if ($dbg_values > 1);
1797 } elsif ($cur =~/^(case)/o) {
1798 print "CASE($1)\n" if ($dbg_values > 1);
1799 $av_pend_colon = 'C';
1802 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1803 print "KEYWORD($1)\n" if ($dbg_values > 1);
1806 } elsif ($cur =~ /^(\()/o) {
1807 print "PAREN('$1')\n" if ($dbg_values > 1);
1808 push(@av_paren_type, $av_pending);
1812 } elsif ($cur =~ /^(\))/o) {
1813 my $new_type = pop(@av_paren_type);
1814 if ($new_type ne '_') {
1816 print "PAREN('$1') -> $type\n"
1817 if ($dbg_values > 1);
1819 print "PAREN('$1')\n" if ($dbg_values > 1);
1822 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1823 print "FUNC($1)\n" if ($dbg_values > 1);
1827 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1828 if (defined $2 && $type eq 'C' || $type eq 'T') {
1829 $av_pend_colon = 'B';
1830 } elsif ($type eq 'E') {
1831 $av_pend_colon = 'L';
1833 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1836 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1837 print "IDENT($1)\n" if ($dbg_values > 1);
1840 } elsif ($cur =~ /^($Assignment)/o) {
1841 print "ASSIGN($1)\n" if ($dbg_values > 1);
1844 } elsif ($cur =~/^(;|{|})/) {
1845 print "END($1)\n" if ($dbg_values > 1);
1847 $av_pend_colon = 'O';
1849 } elsif ($cur =~/^(,)/) {
1850 print "COMMA($1)\n" if ($dbg_values > 1);
1853 } elsif ($cur =~ /^(\?)/o) {
1854 print "QUESTION($1)\n" if ($dbg_values > 1);
1857 } elsif ($cur =~ /^(:)/o) {
1858 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1860 substr($var, length($res), 1, $av_pend_colon);
1861 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1866 $av_pend_colon = 'O';
1868 } elsif ($cur =~ /^(\[)/o) {
1869 print "CLOSE($1)\n" if ($dbg_values > 1);
1872 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1875 print "OPV($1)\n" if ($dbg_values > 1);
1882 substr($var, length($res), 1, $variant);
1885 } elsif ($cur =~ /^($Operators)/o) {
1886 print "OP($1)\n" if ($dbg_values > 1);
1887 if ($1 ne '++' && $1 ne '--') {
1891 } elsif ($cur =~ /(^.)/o) {
1892 print "C($1)\n" if ($dbg_values > 1);
1895 $cur = substr($cur, length($1));
1896 $res .= $type x length($1);
1900 return ($res, $var);
1904 my ($possible, $line) = @_;
1905 my $notPermitted = qr{(?:
1922 ^(?:typedef|struct|enum)\b
1924 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1925 if ($possible !~ $notPermitted) {
1926 # Check for modifiers.
1927 $possible =~ s/\s*$Storage\s*//g;
1928 $possible =~ s/\s*$Sparse\s*//g;
1929 if ($possible =~ /^\s*$/) {
1931 } elsif ($possible =~ /\s/) {
1932 $possible =~ s/\s*$Type\s*//g;
1933 for my $modifier (split(' ', $possible)) {
1934 if ($modifier !~ $notPermitted) {
1935 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1936 push(@modifierListFile, $modifier);
1941 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1942 push(@typeListFile, $possible);
1946 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1955 $type =~ tr/[a-z]/[A-Z]/;
1957 return defined $use_type{$type} if (scalar keys %use_type > 0);
1959 return !defined $ignore_type{$type};
1963 my ($level, $type, $msg) = @_;
1965 if (!show_type($type) ||
1966 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1971 if ($level eq 'ERROR') {
1973 } elsif ($level eq 'WARNING') {
1979 $output .= $prefix . $level . ':';
1981 $output .= BLUE if ($color);
1982 $output .= "$type:";
1984 $output .= RESET if ($color);
1985 $output .= ' ' . $msg . "\n";
1988 my @lines = split("\n", $output, -1);
1989 splice(@lines, 1, 1);
1990 $output = join("\n", @lines);
1992 $output = (split('\n', $output))[0] . "\n" if ($terse);
1994 push(our @report, $output);
2003 sub fixup_current_range {
2004 my ($lineRef, $offset, $length) = @_;
2006 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2009 my $no = $o + $offset;
2010 my $nl = $l + $length;
2011 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2015 sub fix_inserted_deleted_lines {
2016 my ($linesRef, $insertedRef, $deletedRef) = @_;
2018 my $range_last_linenr = 0;
2019 my $delta_offset = 0;
2024 my $next_insert = 0;
2025 my $next_delete = 0;
2029 my $inserted = @{$insertedRef}[$next_insert++];
2030 my $deleted = @{$deletedRef}[$next_delete++];
2032 foreach my $old_line (@{$linesRef}) {
2034 my $line = $old_line; #don't modify the array
2035 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2037 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2038 $range_last_linenr = $new_linenr;
2039 fixup_current_range(\$line, $delta_offset, 0);
2042 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2043 $deleted = @{$deletedRef}[$next_delete++];
2045 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2048 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2049 push(@lines, ${$inserted}{'LINE'});
2050 $inserted = @{$insertedRef}[$next_insert++];
2052 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2056 push(@lines, $line);
2066 sub fix_insert_line {
2067 my ($linenr, $line) = @_;
2073 push(@fixed_inserted, $inserted);
2076 sub fix_delete_line {
2077 my ($linenr, $line) = @_;
2084 push(@fixed_deleted, $deleted);
2088 my ($type, $msg) = @_;
2090 if (report("ERROR", $type, $msg)) {
2098 my ($type, $msg) = @_;
2100 if (report("WARNING", $type, $msg)) {
2108 my ($type, $msg) = @_;
2110 if ($check && report("CHECK", $type, $msg)) {
2118 sub check_absolute_file {
2119 my ($absolute, $herecurr) = @_;
2120 my $file = $absolute;
2122 ##print "absolute<$absolute>\n";
2124 # See if any suffix of this path is a path within the tree.
2125 while ($file =~ s@^[^/]*/@@) {
2126 if (-f "$root/$file") {
2127 ##print "file<$file>\n";
2135 # It is, so see if the prefix is acceptable.
2136 my $prefix = $absolute;
2137 substr($prefix, -length($file)) = '';
2139 ##print "prefix<$prefix>\n";
2140 if ($prefix ne ".../") {
2141 WARN("USE_RELATIVE_PATH",
2142 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2149 $string =~ s/^\s+|\s+$//g;
2157 $string =~ s/^\s+//;
2165 $string =~ s/\s+$//;
2170 sub string_find_replace {
2171 my ($string, $find, $replace) = @_;
2173 $string =~ s/$find/$replace/g;
2181 my $source_indent = 8;
2182 my $max_spaces_before_tab = $source_indent - 1;
2183 my $spaces_to_tab = " " x $source_indent;
2185 #convert leading spaces to tabs
2186 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2187 #Remove spaces before a tab
2188 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2193 sub pos_last_openparen {
2198 my $opens = $line =~ tr/\(/\(/;
2199 my $closes = $line =~ tr/\)/\)/;
2201 my $last_openparen = 0;
2203 if (($opens == 0) || ($closes >= $opens)) {
2207 my $len = length($line);
2209 for ($pos = 0; $pos < $len; $pos++) {
2210 my $string = substr($line, $pos);
2211 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2212 $pos += length($1) - 1;
2213 } elsif (substr($line, $pos, 1) eq '(') {
2214 $last_openparen = $pos;
2215 } elsif (index($string, '(') == -1) {
2220 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2224 my $filename = shift;
2230 my $stashrawline="";
2240 my $in_header_lines = $file ? 0 : 1;
2241 my $in_commit_log = 0; #Scanning lines before patch
2242 my $has_commit_log = 0; #Encountered lines before patch
2243 my $commit_log_possible_stack_dump = 0;
2244 my $commit_log_long_line = 0;
2245 my $commit_log_has_diff = 0;
2246 my $reported_maintainer_file = 0;
2247 my $non_utf8_charset = 0;
2249 my $last_blank_line = 0;
2250 my $last_coalesced_string_linenr = -1;
2258 # Trace the real file/line as we go.
2263 my $context_function; #undef'd unless there's a known function
2265 my $comment_edge = 0;
2269 my $prev_values = 'E';
2272 my %suppress_ifbraces;
2273 my %suppress_whiletrailers;
2274 my %suppress_export;
2275 my $suppress_statement = 0;
2277 my %signatures = ();
2279 # Pre-scan the patch sanitizing the lines.
2280 # Pre-scan the patch looking for any __setup documentation.
2282 my @setup_docs = ();
2285 my $camelcase_file_seeded = 0;
2287 my $checklicenseline = 1;
2289 sanitise_line_reset();
2291 foreach my $rawline (@rawlines) {
2295 push(@fixed, $rawline) if ($fix);
2297 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2299 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2304 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2313 # Guestimate if this is a continuing comment. Run
2314 # the context looking for a comment "edge". If this
2315 # edge is a close comment then we must be in a comment
2319 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2320 next if (defined $rawlines[$ln - 1] &&
2321 $rawlines[$ln - 1] =~ /^-/);
2323 #print "RAW<$rawlines[$ln - 1]>\n";
2324 last if (!defined $rawlines[$ln - 1]);
2325 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2326 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2331 if (defined $edge && $edge eq '*/') {
2335 # Guestimate if this is a continuing comment. If this
2336 # is the start of a diff block and this line starts
2337 # ' *' then it is very likely a comment.
2338 if (!defined $edge &&
2339 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2344 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2345 sanitise_line_reset($in_comment);
2347 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2348 # Standardise the strings and chars within the input to
2349 # simplify matching -- only bother with positive lines.
2350 $line = sanitise_line($rawline);
2352 push(@lines, $line);
2355 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2360 #print "==>$rawline\n";
2361 #print "-->$line\n";
2363 if ($setup_docs && $line =~ /^\+/) {
2364 push(@setup_docs, $line);
2373 foreach my $line (@lines) {
2376 my $sline = $line; #copy of $line
2377 $sline =~ s/$;/ /g; #with comments as spaces
2379 my $rawline = $rawlines[$linenr - 1];
2381 # check if it's a mode change, rename or start of a patch
2382 if (!$in_commit_log &&
2383 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2384 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2385 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2389 #extract the line range in the file after the patch is applied
2390 if (!$in_commit_log &&
2391 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2394 $first_line = $linenr + 1;
2404 %suppress_ifbraces = ();
2405 %suppress_whiletrailers = ();
2406 %suppress_export = ();
2407 $suppress_statement = 0;
2408 if ($context =~ /\b(\w+)\s*\(/) {
2409 $context_function = $1;
2411 undef $context_function;
2415 # track the line number as we move through the hunk, note that
2416 # new versions of GNU diff omit the leading space on completely
2417 # blank context lines so we need to count that too.
2418 } elsif ($line =~ /^( |\+|$)/) {
2420 $realcnt-- if ($realcnt != 0);
2422 # Measure the line length and indent.
2423 ($length, $indent) = line_stats($rawline);
2425 # Track the previous line.
2426 ($prevline, $stashline) = ($stashline, $line);
2427 ($previndent, $stashindent) = ($stashindent, $indent);
2428 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2430 #warn "line<$line>\n";
2432 } elsif ($realcnt == 1) {
2436 my $hunk_line = ($realcnt != 0);
2438 $here = "#$linenr: " if (!$file);
2439 $here = "#$realline: " if ($file);
2442 # extract the filename as it passes
2443 if ($line =~ /^diff --git.*?(\S+)$/) {
2445 $realfile =~ s@^([^/]*)/@@ if (!$file);
2448 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2450 $realfile =~ s@^([^/]*)/@@ if (!$file);
2454 if (!$file && $tree && $p1_prefix ne '' &&
2455 -e "$root/$p1_prefix") {
2456 WARN("PATCH_PREFIX",
2457 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2460 if ($realfile =~ m@^include/asm/@) {
2461 ERROR("MODIFIED_INCLUDE_ASM",
2462 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2467 #make up the handle for any error we report on this line
2469 $prefix = "$realfile:$realline: "
2472 $prefix = "$filename:$realline: ";
2474 $prefix = "$filename:$linenr: ";
2479 if (is_maintained_obsolete($realfile)) {
2481 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2483 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2486 $check = $check_orig;
2488 $checklicenseline = 1;
2492 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2494 my $hereline = "$here\n$rawline\n";
2495 my $herecurr = "$here\n$rawline\n";
2496 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2498 $cnt_lines++ if ($realcnt != 0);
2500 # Check if the commit log has what seems like a diff which can confuse patch
2501 if ($in_commit_log && !$commit_log_has_diff &&
2502 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2503 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2504 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2505 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2506 ERROR("DIFF_IN_COMMIT_MSG",
2507 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2508 $commit_log_has_diff = 1;
2511 # Check for incorrect file permissions
2512 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2513 my $permhere = $here . "FILE: $realfile\n";
2514 if ($realfile !~ m@scripts/@ &&
2515 $realfile !~ /\.(py|pl|awk|sh)$/) {
2516 ERROR("EXECUTE_PERMISSIONS",
2517 "do not set execute permissions for source files\n" . $permhere);
2521 # Check the patch for a signoff:
2522 if ($line =~ /^\s*signed-off-by:/i) {
2527 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2528 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2529 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2530 $reported_maintainer_file = 1;
2533 # Check signature styles
2534 if (!$in_header_lines &&
2535 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2536 my $space_before = $1;
2538 my $space_after = $3;
2540 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2542 if ($sign_off !~ /$signature_tags/) {
2543 WARN("BAD_SIGN_OFF",
2544 "Non-standard signature: $sign_off\n" . $herecurr);
2546 if (defined $space_before && $space_before ne "") {
2547 if (WARN("BAD_SIGN_OFF",
2548 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2550 $fixed[$fixlinenr] =
2551 "$ucfirst_sign_off $email";
2554 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2555 if (WARN("BAD_SIGN_OFF",
2556 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2558 $fixed[$fixlinenr] =
2559 "$ucfirst_sign_off $email";
2563 if (!defined $space_after || $space_after ne " ") {
2564 if (WARN("BAD_SIGN_OFF",
2565 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2567 $fixed[$fixlinenr] =
2568 "$ucfirst_sign_off $email";
2572 my ($email_name, $email_address, $comment) = parse_email($email);
2573 my $suggested_email = format_email(($email_name, $email_address));
2574 if ($suggested_email eq "") {
2575 ERROR("BAD_SIGN_OFF",
2576 "Unrecognized email address: '$email'\n" . $herecurr);
2578 my $dequoted = $suggested_email;
2579 $dequoted =~ s/^"//;
2580 $dequoted =~ s/" </ </;
2581 # Don't force email to have quotes
2582 # Allow just an angle bracketed address
2583 if ("$dequoted$comment" ne $email &&
2584 "<$email_address>$comment" ne $email &&
2585 "$suggested_email$comment" ne $email) {
2586 WARN("BAD_SIGN_OFF",
2587 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2591 # Check for duplicate signatures
2592 my $sig_nospace = $line;
2593 $sig_nospace =~ s/\s//g;
2594 $sig_nospace = lc($sig_nospace);
2595 if (defined $signatures{$sig_nospace}) {
2596 WARN("BAD_SIGN_OFF",
2597 "Duplicate signature\n" . $herecurr);
2599 $signatures{$sig_nospace} = 1;
2603 # Check email subject for common tools that don't need to be mentioned
2604 if ($in_header_lines &&
2605 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2606 WARN("EMAIL_SUBJECT",
2607 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2610 # Check for unwanted Gerrit info
2611 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2612 ERROR("GERRIT_CHANGE_ID",
2613 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2616 # Check if the commit log is in a possible stack dump
2617 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2618 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2619 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2621 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2622 # stack dump address
2623 $commit_log_possible_stack_dump = 1;
2626 # Check for line lengths > 75 in commit log, warn once
2627 if ($in_commit_log && !$commit_log_long_line &&
2628 length($line) > 75 &&
2629 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2630 # file delta changes
2631 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2633 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2634 # A Fixes: or Link: line
2635 $commit_log_possible_stack_dump)) {
2636 WARN("COMMIT_LOG_LONG_LINE",
2637 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2638 $commit_log_long_line = 1;
2641 # Reset possible stack dump if a blank line is found
2642 if ($in_commit_log && $commit_log_possible_stack_dump &&
2644 $commit_log_possible_stack_dump = 0;
2647 # Check for git id commit length and improperly formed commit descriptions
2648 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2649 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2650 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2651 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2652 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2653 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2654 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2655 my $init_char = "c";
2656 my $orig_commit = "";
2663 my $id = '0123456789ab';
2664 my $orig_desc = "commit description";
2665 my $description = "";
2667 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2669 $orig_commit = lc($2);
2670 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2671 $orig_commit = lc($1);
2674 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2675 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2676 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2677 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2678 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2681 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2682 defined $rawlines[$linenr] &&
2683 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2686 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2687 defined $rawlines[$linenr] &&
2688 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2689 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2691 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2692 $orig_desc .= " " . $1;
2696 ($id, $description) = git_commit_info($orig_commit,
2700 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2701 ERROR("GIT_COMMIT_ID",
2702 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2706 # Check for added, moved or deleted files
2707 if (!$reported_maintainer_file && !$in_commit_log &&
2708 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2709 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2710 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2711 (defined($1) || defined($2))))) {
2713 $reported_maintainer_file = 1;
2714 WARN("FILE_PATH_CHANGES",
2715 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2718 # Check for wrappage within a valid hunk of the file
2719 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2720 ERROR("CORRUPTED_PATCH",
2721 "patch seems to be corrupt (line wrapped?)\n" .
2722 $herecurr) if (!$emitted_corrupt++);
2725 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2726 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2727 $rawline !~ m/^$UTF8*$/) {
2728 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2730 my $blank = copy_spacing($rawline);
2731 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2732 my $hereptr = "$hereline$ptr\n";
2735 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2738 # Check if it's the start of a commit log
2739 # (not a header line and we haven't seen the patch filename)
2740 if ($in_header_lines && $realfile =~ /^$/ &&
2741 !($rawline =~ /^\s+(?:\S|$)/ ||
2742 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2743 $in_header_lines = 0;
2745 $has_commit_log = 1;
2748 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2749 # declined it, i.e defined some charset where it is missing.
2750 if ($in_header_lines &&
2751 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2753 $non_utf8_charset = 1;
2756 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2757 $rawline =~ /$NON_ASCII_UTF8/) {
2758 WARN("UTF8_BEFORE_PATCH",
2759 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2762 # Check for absolute kernel paths in commit message
2763 if ($tree && $in_commit_log) {
2764 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2767 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2768 check_absolute_file($1, $herecurr)) {
2771 check_absolute_file($file, $herecurr);
2776 # Check for various typo / spelling mistakes
2777 if (defined($misspellings) &&
2778 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2779 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2781 my $typo_fix = $spelling_fix{lc($typo)};
2782 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2783 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2784 my $msg_level = \&WARN;
2785 $msg_level = \&CHK if ($file);
2786 if (&{$msg_level}("TYPO_SPELLING",
2787 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2789 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2794 # ignore non-hunk lines and lines being removed
2795 next if (!$hunk_line || $line =~ /^-/);
2797 #trailing whitespace
2798 if ($line =~ /^\+.*\015/) {
2799 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2800 if (ERROR("DOS_LINE_ENDINGS",
2801 "DOS line endings\n" . $herevet) &&
2803 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2805 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2806 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2807 if (ERROR("TRAILING_WHITESPACE",
2808 "trailing whitespace\n" . $herevet) &&
2810 $fixed[$fixlinenr] =~ s/\s+$//;
2816 # Check for FSF mailing addresses.
2817 if ($rawline =~ /\bwrite to the Free/i ||
2818 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2819 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2820 $rawline =~ /\b51\s+Franklin\s+St/i) {
2821 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2822 my $msg_level = \&ERROR;
2823 $msg_level = \&CHK if ($file);
2824 &{$msg_level}("FSF_MAILING_ADDRESS",
2825 "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)
2828 # check for Kconfig help text having a real description
2829 # Only applies when adding the entry originally, after that we do not have
2830 # sufficient context to determine whether it is indeed long enough.
2831 if ($realfile =~ /Kconfig/ &&
2832 # 'choice' is usually the last thing on the line (though
2833 # Kconfig supports named choices), so use a word boundary
2834 # (\b) rather than a whitespace character (\s)
2835 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2838 my $ln = $linenr + 1;
2842 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2843 $f = $lines[$ln - 1];
2844 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2845 $is_end = $lines[$ln - 1] =~ /^\+/;
2847 next if ($f =~ /^-/);
2848 last if (!$file && $f =~ /^\@\@/);
2850 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2852 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2853 if ($lines[$ln - 1] =~ "---help---") {
2854 WARN("CONFIG_DESCRIPTION",
2855 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2863 next if ($f =~ /^$/);
2865 # This only checks context lines in the patch
2866 # and so hopefully shouldn't trigger false
2867 # positives, even though some of these are
2868 # common words in help texts
2869 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2870 if|endif|menu|endmenu|source)\b/x) {
2876 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2877 WARN("CONFIG_DESCRIPTION",
2878 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2880 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2883 # check for MAINTAINERS entries that don't have the right form
2884 if ($realfile =~ /^MAINTAINERS$/ &&
2885 $rawline =~ /^\+[A-Z]:/ &&
2886 $rawline !~ /^\+[A-Z]:\t\S/) {
2887 if (WARN("MAINTAINERS_STYLE",
2888 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2890 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2894 # discourage the use of boolean for type definition attributes of Kconfig options
2895 if ($realfile =~ /Kconfig/ &&
2896 $line =~ /^\+\s*\bboolean\b/) {
2897 WARN("CONFIG_TYPE_BOOLEAN",
2898 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2901 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2902 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2905 'EXTRA_AFLAGS' => 'asflags-y',
2906 'EXTRA_CFLAGS' => 'ccflags-y',
2907 'EXTRA_CPPFLAGS' => 'cppflags-y',
2908 'EXTRA_LDFLAGS' => 'ldflags-y',
2911 WARN("DEPRECATED_VARIABLE",
2912 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2915 # check for DT compatible documentation
2916 if (defined $root &&
2917 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2918 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2920 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2922 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2923 my $vp_file = $dt_path . "vendor-prefixes.txt";
2925 foreach my $compat (@compats) {
2926 my $compat2 = $compat;
2927 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2928 my $compat3 = $compat;
2929 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2930 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2932 WARN("UNDOCUMENTED_DT_STRING",
2933 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2936 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2938 `grep -Eq "^$vendor\\b" $vp_file`;
2940 WARN("UNDOCUMENTED_DT_STRING",
2941 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2946 # check for using SPDX license tag at beginning of files
2947 if ($realline == $checklicenseline) {
2948 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
2949 $checklicenseline = 2;
2950 } elsif ($rawline =~ /^\+/) {
2952 if ($realfile =~ /\.(h|s|S)$/) {
2954 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
2956 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
2958 } elsif ($realfile =~ /\.rst$/) {
2962 if ($comment !~ /^$/ &&
2963 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
2964 WARN("SPDX_LICENSE_TAG",
2965 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
2970 # check we are in a valid source file if not then ignore this hunk
2971 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
2973 # line length limit (with some exclusions)
2975 # There are a few types of lines that may extend beyond $max_line_length:
2976 # logging functions like pr_info that end in a string
2977 # lines with a single string
2978 # #defines that are a single string
2979 # lines with an RFC3986 like URL
2981 # There are 3 different line length message types:
2982 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
2983 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
2984 # LONG_LINE all other lines longer than $max_line_length
2986 # if LONG_LINE is ignored, the other 2 types are also ignored
2989 if ($line =~ /^\+/ && $length > $max_line_length) {
2990 my $msg_type = "LONG_LINE";
2992 # Check the allowed long line types first
2994 # logging functions that end in a string that starts
2995 # before $max_line_length
2996 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2997 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3000 # lines with only strings (w/ possible termination)
3001 # #defines with only strings
3002 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3003 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3006 # More special cases
3007 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3008 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3011 # URL ($rawline is used in case the URL is in a comment)
3012 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3015 # Otherwise set the alternate message types
3017 # a comment starts before $max_line_length
3018 } elsif ($line =~ /($;[\s$;]*)$/ &&
3019 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3020 $msg_type = "LONG_LINE_COMMENT"
3022 # a quoted string starts before $max_line_length
3023 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3024 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3025 $msg_type = "LONG_LINE_STRING"
3028 if ($msg_type ne "" &&
3029 (show_type("LONG_LINE") || show_type($msg_type))) {
3031 "line over $max_line_length characters\n" . $herecurr);
3035 # check for adding lines without a newline.
3036 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3037 WARN("MISSING_EOF_NEWLINE",
3038 "adding a line without newline at end of file\n" . $herecurr);
3041 # check we are in a valid source file C or perl if not then ignore this hunk
3042 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3044 # at the beginning of a line any tabs must come first and anything
3045 # more than 8 must use tabs.
3046 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3047 $rawline =~ /^\+\s* \s*/) {
3048 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3050 if (ERROR("CODE_INDENT",
3051 "code indent should use tabs where possible\n" . $herevet) &&
3053 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3057 # check for space before tabs.
3058 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3059 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3060 if (WARN("SPACE_BEFORE_TAB",
3061 "please, no space before tabs\n" . $herevet) &&
3063 while ($fixed[$fixlinenr] =~
3064 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3065 while ($fixed[$fixlinenr] =~
3066 s/(^\+.*) +\t/$1\t/) {}
3070 # check for assignments on the start of a line
3071 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3072 CHK("ASSIGNMENT_CONTINUATIONS",
3073 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3076 # check for && or || at the start of a line
3077 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3078 CHK("LOGICAL_CONTINUATIONS",
3079 "Logical continuations should be on the previous line\n" . $hereprev);
3082 # check indentation starts on a tab stop
3083 if ($perl_version_ok &&
3084 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3085 my $indent = length($1);
3088 "Statements should start on a tabstop\n" . $herecurr) &&
3090 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3095 # check multi-line statement indentation matches previous line
3096 if ($perl_version_ok &&
3097 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3098 $prevline =~ /^\+(\t*)(.*)$/;
3102 my $pos = pos_last_openparen($rest);
3104 $line =~ /^(\+| )([ \t]*)/;
3107 my $goodtabindent = $oldindent .
3110 my $goodspaceindent = $oldindent . " " x $pos;
3112 if ($newindent ne $goodtabindent &&
3113 $newindent ne $goodspaceindent) {
3115 if (CHK("PARENTHESIS_ALIGNMENT",
3116 "Alignment should match open parenthesis\n" . $hereprev) &&
3117 $fix && $line =~ /^\+/) {
3118 $fixed[$fixlinenr] =~
3119 s/^\+[ \t]*/\+$goodtabindent/;
3125 # check for space after cast like "(int) foo" or "(struct foo) bar"
3126 # avoid checking a few false positives:
3127 # "sizeof(<type>)" or "__alignof__(<type>)"
3128 # function pointer declarations like "(*foo)(int) = bar;"
3129 # structure definitions like "(struct foo) { 0 };"
3130 # multiline macros that define functions
3131 # known attributes or the __attribute__ keyword
3132 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3133 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3135 "No space is necessary after a cast\n" . $herecurr) &&
3137 $fixed[$fixlinenr] =~
3138 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3142 # Block comment styles
3143 # Networking with an initial /*
3144 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3145 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3146 $rawline =~ /^\+[ \t]*\*/ &&
3148 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3149 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3152 # Block comments use * on subsequent lines
3153 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3154 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3155 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3156 $rawline =~ /^\+/ && #line is new
3157 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3158 WARN("BLOCK_COMMENT_STYLE",
3159 "Block comments use * on subsequent lines\n" . $hereprev);
3162 # Block comments use */ on trailing lines
3163 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3164 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3165 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3166 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3167 WARN("BLOCK_COMMENT_STYLE",
3168 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3171 # Block comment * alignment
3172 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3173 $line =~ /^\+[ \t]*$;/ && #leading comment
3174 $rawline =~ /^\+[ \t]*\*/ && #leading *
3175 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3176 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3177 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3179 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3181 $oldindent = expand_tabs($1);
3183 $prevrawline =~ m@^\+(.*/?)\*@;
3184 $oldindent = expand_tabs($1);
3186 $rawline =~ m@^\+([ \t]*)\*@;
3188 $newindent = expand_tabs($newindent);
3189 if (length($oldindent) ne length($newindent)) {
3190 WARN("BLOCK_COMMENT_STYLE",
3191 "Block comments should align the * on each line\n" . $hereprev);
3195 # check for missing blank lines after struct/union declarations
3196 # with exceptions for various attributes and macros
3197 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3199 !($line =~ /^\+\s*$/ ||
3200 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3201 $line =~ /^\+\s*MODULE_/i ||
3202 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3203 $line =~ /^\+[a-z_]*init/ ||
3204 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3205 $line =~ /^\+\s*DECLARE/ ||
3206 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3207 $line =~ /^\+\s*__setup/)) {
3208 if (CHK("LINE_SPACING",
3209 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3211 fix_insert_line($fixlinenr, "\+");
3215 # check for multiple consecutive blank lines
3216 if ($prevline =~ /^[\+ ]\s*$/ &&
3217 $line =~ /^\+\s*$/ &&
3218 $last_blank_line != ($linenr - 1)) {
3219 if (CHK("LINE_SPACING",
3220 "Please don't use multiple blank lines\n" . $hereprev) &&
3222 fix_delete_line($fixlinenr, $rawline);
3225 $last_blank_line = $linenr;
3228 # check for missing blank lines after declarations
3229 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3230 # actual declarations
3231 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3232 # function pointer declarations
3233 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3234 # foo bar; where foo is some local typedef or #define
3235 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3236 # known declaration macros
3237 $prevline =~ /^\+\s+$declaration_macros/) &&
3238 # for "else if" which can look like "$Ident $Ident"
3239 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3240 # other possible extensions of declaration lines
3241 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3242 # not starting a section or a macro "\" extended line
3243 $prevline =~ /(?:\{\s*|\\)$/) &&
3244 # looks like a declaration
3245 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3246 # function pointer declarations
3247 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3248 # foo bar; where foo is some local typedef or #define
3249 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3250 # known declaration macros
3251 $sline =~ /^\+\s+$declaration_macros/ ||
3252 # start of struct or union or enum
3253 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3254 # start or end of block or continuation of declaration
3255 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3256 # bitfield continuation
3257 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3258 # other possible extensions of declaration lines
3259 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3260 # indentation of previous and current line are the same
3261 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3262 if (WARN("LINE_SPACING",
3263 "Missing a blank line after declarations\n" . $hereprev) &&
3265 fix_insert_line($fixlinenr, "\+");
3269 # check for spaces at the beginning of a line.
3271 # 1) within comments
3272 # 2) indented preprocessor commands
3274 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3275 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3276 if (WARN("LEADING_SPACE",
3277 "please, no spaces at the start of a line\n" . $herevet) &&
3279 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3283 # check we are in a valid C source file if not then ignore this hunk
3284 next if ($realfile !~ /\.(h|c)$/);
3286 # check for unusual line ending [ or (
3287 if ($line =~ /^\+.*([\[\(])\s*$/) {
3288 CHK("OPEN_ENDED_LINE",
3289 "Lines should not end with a '$1'\n" . $herecurr);
3292 # check if this appears to be the start function declaration, save the name
3293 if ($sline =~ /^\+\{\s*$/ &&
3294 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3295 $context_function = $1;
3298 # check if this appears to be the end of function declaration
3299 if ($sline =~ /^\+\}\s*$/) {
3300 undef $context_function;
3303 # check indentation of any line with a bare else
3304 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3305 # if the previous line is a break or return and is indented 1 tab more...
3306 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3307 my $tabs = length($1) + 1;
3308 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3309 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3310 defined $lines[$linenr] &&
3311 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3312 WARN("UNNECESSARY_ELSE",
3313 "else is not generally useful after a break or return\n" . $hereprev);
3317 # check indentation of a line with a break;
3318 # if the previous line is a goto or return and is indented the same # of tabs
3319 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3321 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3322 WARN("UNNECESSARY_BREAK",
3323 "break is not useful after a goto or return\n" . $hereprev);
3327 # check for RCS/CVS revision markers
3328 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3330 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3333 # check for old HOTPLUG __dev<foo> section markings
3334 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3335 WARN("HOTPLUG_SECTION",
3336 "Using $1 is unnecessary\n" . $herecurr);
3339 # Check for potential 'bare' types
3340 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3342 #print "LINE<$line>\n";
3343 if ($linenr > $suppress_statement &&
3344 $realcnt && $sline =~ /.\s*\S/) {
3345 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3346 ctx_statement_block($linenr, $realcnt, 0);
3347 $stat =~ s/\n./\n /g;
3348 $cond =~ s/\n./\n /g;
3350 #print "linenr<$linenr> <$stat>\n";
3351 # If this statement has no statement boundaries within
3352 # it there is no point in retrying a statement scan
3353 # until we hit end of it.
3354 my $frag = $stat; $frag =~ s/;+\s*$//;
3355 if ($frag !~ /(?:{|;)/) {
3356 #print "skip<$line_nr_next>\n";
3357 $suppress_statement = $line_nr_next;
3360 # Find the real next line.
3361 $realline_next = $line_nr_next;
3362 if (defined $realline_next &&
3363 (!defined $lines[$realline_next - 1] ||
3364 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3371 # Ignore goto labels.
3372 if ($s =~ /$Ident:\*$/s) {
3374 # Ignore functions being called
3375 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3377 } elsif ($s =~ /^.\s*else\b/s) {
3379 # declarations always start with types
3380 } 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) {
3383 possible($type, "A:" . $s);
3385 # definitions in global scope can only start with types
3386 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3387 possible($1, "B:" . $s);
3390 # any (foo ... *) is a pointer cast, and foo is a type
3391 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3392 possible($1, "C:" . $s);
3395 # Check for any sort of function declaration.
3396 # int foo(something bar, other baz);
3397 # void (*store_gdt)(x86_descr_ptr *);
3398 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3399 my ($name_len) = length($1);
3402 substr($ctx, 0, $name_len + 1, '');
3403 $ctx =~ s/\)[^\)]*$//;
3405 for my $arg (split(/\s*,\s*/, $ctx)) {
3406 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3408 possible($1, "D:" . $s);
3416 # Checks which may be anchored in the context.
3419 # Check for switch () and associated case and default
3420 # statements should be at the same indent.
3421 if ($line=~/\bswitch\s*\(.*\)/) {
3424 my @ctx = ctx_block_outer($linenr, $realcnt);
3426 for my $ctx (@ctx) {
3427 my ($clen, $cindent) = line_stats($ctx);
3428 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3429 $indent != $cindent) {
3430 $err .= "$sep$ctx\n";
3437 ERROR("SWITCH_CASE_INDENT_LEVEL",
3438 "switch and case should be at the same indent\n$hereline$err");
3442 # if/while/etc brace do not go on next line, unless defining a do while loop,
3443 # or if that brace on the next line is for something else
3444 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3445 my $pre_ctx = "$1$2";
3447 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3449 if ($line =~ /^\+\t{6,}/) {
3450 WARN("DEEP_INDENTATION",
3451 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3454 my $ctx_cnt = $realcnt - $#ctx - 1;
3455 my $ctx = join("\n", @ctx);
3457 my $ctx_ln = $linenr;
3458 my $ctx_skip = $realcnt;
3460 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3461 defined $lines[$ctx_ln - 1] &&
3462 $lines[$ctx_ln - 1] =~ /^-/)) {
3463 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3464 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3468 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3469 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3471 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3473 "that open brace { should be on the previous line\n" .
3474 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3476 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3477 $ctx =~ /\)\s*\;\s*$/ &&
3478 defined $lines[$ctx_ln - 1])
3480 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3481 if ($nindent > $indent) {
3482 WARN("TRAILING_SEMICOLON",
3483 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3484 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3489 # Check relative indent for conditionals and blocks.
3490 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3491 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3492 ctx_statement_block($linenr, $realcnt, 0)
3493 if (!defined $stat);
3494 my ($s, $c) = ($stat, $cond);
3496 substr($s, 0, length($c), '');
3498 # remove inline comments
3502 # Find out how long the conditional actually is.
3503 my @newlines = ($c =~ /\n/gs);
3504 my $cond_lines = 1 + $#newlines;
3506 # Make sure we remove the line prefixes as we have
3507 # none on the first line, and are going to readd them
3510 while ($s =~ /\n\s+\\\n/) {
3511 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3514 # We want to check the first line inside the block
3515 # starting at the end of the conditional, so remove:
3516 # 1) any blank line termination
3517 # 2) any opening brace { on end of the line
3519 my $continuation = 0;
3521 $s =~ s/^.*\bdo\b//;
3523 if ($s =~ s/^\s*\\//) {
3526 if ($s =~ s/^\s*?\n//) {
3531 # Also ignore a loop construct at the end of a
3532 # preprocessor statement.
3533 if (($prevline =~ /^.\s*#\s*define\s/ ||
3534 $prevline =~ /\\\s*$/) && $continuation == 0) {
3540 while ($cond_ptr != $cond_lines) {
3541 $cond_ptr = $cond_lines;
3543 # If we see an #else/#elif then the code
3545 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3550 # 1) blank lines, they should be at 0,
3551 # 2) preprocessor lines, and
3553 if ($continuation ||
3555 $s =~ /^\s*#\s*?/ ||
3556 $s =~ /^\s*$Ident\s*:/) {
3557 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3558 if ($s =~ s/^.*?\n//) {
3564 my (undef, $sindent) = line_stats("+" . $s);
3565 my $stat_real = raw_line($linenr, $cond_lines);
3567 # Check if either of these lines are modified, else
3568 # this is not this patch's fault.
3569 if (!defined($stat_real) ||
3570 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3573 if (defined($stat_real) && $cond_lines > 1) {
3574 $stat_real = "[...]\n$stat_real";
3577 #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";
3579 if ($check && $s ne '' &&
3580 (($sindent % 8) != 0 ||
3581 ($sindent < $indent) ||
3582 ($sindent == $indent &&
3583 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3584 ($sindent > $indent + 8))) {
3585 WARN("SUSPECT_CODE_INDENT",
3586 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3590 # Track the 'values' across context and added lines.
3591 my $opline = $line; $opline =~ s/^./ /;
3592 my ($curr_values, $curr_vars) =
3593 annotate_values($opline . "\n", $prev_values);
3594 $curr_values = $prev_values . $curr_values;
3596 my $outline = $opline; $outline =~ s/\t/ /g;
3597 print "$linenr > .$outline\n";
3598 print "$linenr > $curr_values\n";
3599 print "$linenr > $curr_vars\n";
3601 $prev_values = substr($curr_values, -1);
3603 #ignore lines not being added
3604 next if ($line =~ /^[^\+]/);
3606 # check for dereferences that span multiple lines
3607 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3608 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3609 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3611 $line =~ /^.\s*($Lval)/;
3614 WARN("MULTILINE_DEREFERENCE",
3615 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3618 # check for declarations of signed or unsigned without int
3619 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3622 $var = "" if (!defined $var);
3623 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3627 $pointer = "" if (!defined $pointer);
3629 if (WARN("UNSPECIFIED_INT",
3630 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3632 my $decl = trim($sign) . " int ";
3633 my $comp_pointer = $pointer;
3634 $comp_pointer =~ s/\s//g;
3635 $decl .= $comp_pointer;
3636 $decl = rtrim($decl) if ($var eq "");
3637 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3642 # TEST: allow direct testing of the type matcher.
3644 if ($line =~ /^.\s*$Declare\s*$/) {
3646 "TEST: is type\n" . $herecurr);
3647 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3648 ERROR("TEST_NOT_TYPE",
3649 "TEST: is not type ($1 is)\n". $herecurr);
3653 # TEST: allow direct testing of the attribute matcher.
3655 if ($line =~ /^.\s*$Modifier\s*$/) {
3657 "TEST: is attr\n" . $herecurr);
3658 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3659 ERROR("TEST_NOT_ATTR",
3660 "TEST: is not attr ($1 is)\n". $herecurr);
3665 # check for initialisation to aggregates open brace on the next line
3666 if ($line =~ /^.\s*{/ &&
3667 $prevline =~ /(?:^|[^=])=\s*$/) {
3668 if (ERROR("OPEN_BRACE",
3669 "that open brace { should be on the previous line\n" . $hereprev) &&
3670 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3671 fix_delete_line($fixlinenr - 1, $prevrawline);
3672 fix_delete_line($fixlinenr, $rawline);
3673 my $fixedline = $prevrawline;
3674 $fixedline =~ s/\s*=\s*$/ = {/;
3675 fix_insert_line($fixlinenr, $fixedline);
3677 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3678 fix_insert_line($fixlinenr, $fixedline);
3683 # Checks which are anchored on the added line.
3686 # check for malformed paths in #include statements (uses RAW line)
3687 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3689 if ($path =~ m{//}) {
3690 ERROR("MALFORMED_INCLUDE",
3691 "malformed #include filename\n" . $herecurr);
3693 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3694 ERROR("UAPI_INCLUDE",
3695 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3699 # no C99 // comments
3700 if ($line =~ m{//}) {
3701 if (ERROR("C99_COMMENTS",
3702 "do not use C99 // comments\n" . $herecurr) &&
3704 my $line = $fixed[$fixlinenr];
3705 if ($line =~ /\/\/(.*)$/) {
3706 my $comment = trim($1);
3707 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3711 # Remove C99 comments.
3713 $opline =~ s@//.*@@;
3715 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3716 # the whole statement.
3717 #print "APW <$lines[$realline_next - 1]>\n";
3718 if (defined $realline_next &&
3719 exists $lines[$realline_next - 1] &&
3720 !defined $suppress_export{$realline_next} &&
3721 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3722 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3723 # Handle definitions which produce identifiers with
3726 # EXPORT_SYMBOL(something_foo);
3728 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3729 $name =~ /^${Ident}_$2/) {
3730 #print "FOO C name<$name>\n";
3731 $suppress_export{$realline_next} = 1;
3733 } elsif ($stat !~ /(?:
3735 ^.DEFINE_$Ident\(\Q$name\E\)|
3736 ^.DECLARE_$Ident\(\Q$name\E\)|
3737 ^.LIST_HEAD\(\Q$name\E\)|
3738 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3739 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3741 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3742 $suppress_export{$realline_next} = 2;
3744 $suppress_export{$realline_next} = 1;
3747 if (!defined $suppress_export{$linenr} &&
3748 $prevline =~ /^.\s*$/ &&
3749 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3750 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3751 #print "FOO B <$lines[$linenr - 1]>\n";
3752 $suppress_export{$linenr} = 2;
3754 if (defined $suppress_export{$linenr} &&
3755 $suppress_export{$linenr} == 2) {
3756 WARN("EXPORT_SYMBOL",
3757 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3760 # check for global initialisers.
3761 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3762 if (ERROR("GLOBAL_INITIALISERS",
3763 "do not initialise globals to $1\n" . $herecurr) &&
3765 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3768 # check for static initialisers.
3769 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3770 if (ERROR("INITIALISED_STATIC",
3771 "do not initialise statics to $1\n" .
3774 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3778 # check for misordered declarations of char/short/int/long with signed/unsigned
3779 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3781 WARN("MISORDERED_TYPE",
3782 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3785 # check for static const char * arrays.
3786 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3787 WARN("STATIC_CONST_CHAR_ARRAY",
3788 "static const char * array should probably be static const char * const\n" .
3792 # check for static char foo[] = "bar" declarations.
3793 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3794 WARN("STATIC_CONST_CHAR_ARRAY",
3795 "static char array declaration should probably be static const char\n" .
3799 # check for const <foo> const where <foo> is not a pointer or array type
3800 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3802 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3804 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3805 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3807 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3811 # check for non-global char *foo[] = {"bar", ...} declarations.
3812 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3813 WARN("STATIC_CONST_CHAR_ARRAY",
3814 "char * array declaration might be better as static const\n" .
3818 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3819 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3821 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3823 if (WARN("ARRAY_SIZE",
3824 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3826 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3831 # check for function declarations without arguments like "int foo()"
3832 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3833 if (ERROR("FUNCTION_WITHOUT_ARGS",
3834 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3836 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3840 # check for new typedefs, only function parameters and sparse annotations
3842 if ($line =~ /\btypedef\s/ &&
3843 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3844 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3845 $line !~ /\b$typeTypedefs\b/ &&
3846 $line !~ /\b__bitwise\b/) {
3847 WARN("NEW_TYPEDEFS",
3848 "do not add new typedefs\n" . $herecurr);
3851 # * goes on variable not on type
3853 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3855 my ($ident, $from, $to) = ($1, $2, $2);
3857 # Should start with a space.
3858 $to =~ s/^(\S)/ $1/;
3859 # Should not end with a space.
3861 # '*'s should not have spaces between.
3862 while ($to =~ s/\*\s+\*/\*\*/) {
3865 ## print "1: from<$from> to<$to> ident<$ident>\n";
3867 if (ERROR("POINTER_LOCATION",
3868 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3870 my $sub_from = $ident;
3871 my $sub_to = $ident;
3872 $sub_to =~ s/\Q$from\E/$to/;
3873 $fixed[$fixlinenr] =~
3874 s@\Q$sub_from\E@$sub_to@;
3878 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3880 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3882 # Should start with a space.
3883 $to =~ s/^(\S)/ $1/;
3884 # Should not end with a space.
3886 # '*'s should not have spaces between.
3887 while ($to =~ s/\*\s+\*/\*\*/) {
3889 # Modifiers should have spaces.
3890 $to =~ s/(\b$Modifier$)/$1 /;
3892 ## print "2: from<$from> to<$to> ident<$ident>\n";
3893 if ($from ne $to && $ident !~ /^$Modifier$/) {
3894 if (ERROR("POINTER_LOCATION",
3895 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3898 my $sub_from = $match;
3899 my $sub_to = $match;
3900 $sub_to =~ s/\Q$from\E/$to/;
3901 $fixed[$fixlinenr] =~
3902 s@\Q$sub_from\E@$sub_to@;
3907 # avoid BUG() or BUG_ON()
3908 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3909 my $msg_level = \&WARN;
3910 $msg_level = \&CHK if ($file);
3911 &{$msg_level}("AVOID_BUG",
3912 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3915 # avoid LINUX_VERSION_CODE
3916 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3917 WARN("LINUX_VERSION_CODE",
3918 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3921 # check for uses of printk_ratelimit
3922 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3923 WARN("PRINTK_RATELIMITED",
3924 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3927 # printk should use KERN_* levels
3928 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
3929 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3930 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
3933 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3935 my $level = lc($orig);
3936 $level = "warn" if ($level eq "warning");
3937 my $level2 = $level;
3938 $level2 = "dbg" if ($level eq "debug");
3939 WARN("PREFER_PR_LEVEL",
3940 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3943 if ($line =~ /\bpr_warning\s*\(/) {
3944 if (WARN("PREFER_PR_LEVEL",
3945 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3947 $fixed[$fixlinenr] =~
3948 s/\bpr_warning\b/pr_warn/;
3952 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3954 my $level = lc($orig);
3955 $level = "warn" if ($level eq "warning");
3956 $level = "dbg" if ($level eq "debug");
3957 WARN("PREFER_DEV_LEVEL",
3958 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3961 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
3962 # number of false positives, but assembly files are not checked, so at
3963 # least the arch entry code will not trigger this warning.
3964 if ($line =~ /\bENOSYS\b/) {
3966 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
3969 # function brace can't be on same line, except for #defines of do while,
3970 # or if closed on same line
3971 if ($perl_version_ok &&
3972 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
3973 $sline !~ /\#\s*define\b.*do\s*\{/ &&
3975 if (ERROR("OPEN_BRACE",
3976 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
3978 fix_delete_line($fixlinenr, $rawline);
3979 my $fixed_line = $rawline;
3980 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3983 fix_insert_line($fixlinenr, ltrim($line1));
3984 fix_insert_line($fixlinenr, "\+{");
3985 if ($line2 !~ /^\s*$/) {
3986 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3991 # open braces for enum, union and struct go on the same line.
3992 if ($line =~ /^.\s*{/ &&
3993 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3994 if (ERROR("OPEN_BRACE",
3995 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3996 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3997 fix_delete_line($fixlinenr - 1, $prevrawline);
3998 fix_delete_line($fixlinenr, $rawline);
3999 my $fixedline = rtrim($prevrawline) . " {";
4000 fix_insert_line($fixlinenr, $fixedline);
4001 $fixedline = $rawline;
4002 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4003 if ($fixedline !~ /^\+\s*$/) {
4004 fix_insert_line($fixlinenr, $fixedline);
4009 # missing space after union, struct or enum definition
4010 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4012 "missing space after $1 definition\n" . $herecurr) &&
4014 $fixed[$fixlinenr] =~
4015 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4019 # Function pointer declarations
4020 # check spacing between type, funcptr, and args
4021 # canonical declaration is "type (*funcptr)(args...)"
4022 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4024 my $pre_pointer_space = $2;
4025 my $post_pointer_space = $3;
4027 my $post_funcname_space = $5;
4028 my $pre_args_space = $6;
4030 # the $Declare variable will capture all spaces after the type
4031 # so check it for a missing trailing missing space but pointer return types
4032 # don't need a space so don't warn for those.
4033 my $post_declare_space = "";
4034 if ($declare =~ /(\s+)$/) {
4035 $post_declare_space = $1;
4036 $declare = rtrim($declare);
4038 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4040 "missing space after return type\n" . $herecurr);
4041 $post_declare_space = " ";
4044 # unnecessary space "type (*funcptr)(args...)"
4045 # This test is not currently implemented because these declarations are
4047 # int foo(int bar, ...)
4048 # and this is form shouldn't/doesn't generate a checkpatch warning.
4050 # elsif ($declare =~ /\s{2,}$/) {
4052 # "Multiple spaces after return type\n" . $herecurr);
4055 # unnecessary space "type ( *funcptr)(args...)"
4056 if (defined $pre_pointer_space &&
4057 $pre_pointer_space =~ /^\s/) {
4059 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4062 # unnecessary space "type (* funcptr)(args...)"
4063 if (defined $post_pointer_space &&
4064 $post_pointer_space =~ /^\s/) {
4066 "Unnecessary space before function pointer name\n" . $herecurr);
4069 # unnecessary space "type (*funcptr )(args...)"
4070 if (defined $post_funcname_space &&
4071 $post_funcname_space =~ /^\s/) {
4073 "Unnecessary space after function pointer name\n" . $herecurr);
4076 # unnecessary space "type (*funcptr) (args...)"
4077 if (defined $pre_args_space &&
4078 $pre_args_space =~ /^\s/) {
4080 "Unnecessary space before function pointer arguments\n" . $herecurr);
4083 if (show_type("SPACING") && $fix) {
4084 $fixed[$fixlinenr] =~
4085 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4089 # check for spacing round square brackets; allowed:
4090 # 1. with a type on the left -- int [] a;
4091 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4092 # 3. inside a curly brace -- = { [0...10] = 5 }
4093 while ($line =~ /(.*?\s)\[/g) {
4094 my ($where, $prefix) = ($-[1], $1);
4095 if ($prefix !~ /$Type\s+$/ &&
4096 ($where != 0 || $prefix !~ /^.\s+$/) &&
4097 $prefix !~ /[{,:]\s+$/) {
4098 if (ERROR("BRACKET_SPACE",
4099 "space prohibited before open square bracket '['\n" . $herecurr) &&
4101 $fixed[$fixlinenr] =~
4102 s/^(\+.*?)\s+\[/$1\[/;
4107 # check for spaces between functions and their parentheses.
4108 while ($line =~ /($Ident)\s+\(/g) {
4110 my $ctx_before = substr($line, 0, $-[1]);
4111 my $ctx = "$ctx_before$name";
4113 # Ignore those directives where spaces _are_ permitted.
4115 if|for|while|switch|return|case|
4116 volatile|__volatile__|
4117 __attribute__|format|__extension__|
4120 # cpp #define statements have non-optional spaces, ie
4121 # if there is a space between the name and the open
4122 # parenthesis it is simply not a parameter group.
4123 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4125 # cpp #elif statement condition may start with a (
4126 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4128 # If this whole things ends with a type its most
4129 # likely a typedef for a function.
4130 } elsif ($ctx =~ /$Type$/) {
4134 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4136 $fixed[$fixlinenr] =~
4137 s/\b$name\s+\(/$name\(/;
4142 # Check operator spacing.
4143 if (!($line=~/\#\s*include/)) {
4144 my $fixed_line = "";
4148 <<=|>>=|<=|>=|==|!=|
4149 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4150 =>|->|<<|>>|<|>|=|!|~|
4151 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4154 my @elements = split(/($ops|;)/, $opline);
4156 ## print("element count: <" . $#elements . ">\n");
4157 ## foreach my $el (@elements) {
4158 ## print("el: <$el>\n");
4161 my @fix_elements = ();
4164 foreach my $el (@elements) {
4165 push(@fix_elements, substr($rawline, $off, length($el)));
4166 $off += length($el);
4171 my $blank = copy_spacing($opline);
4172 my $last_after = -1;
4174 for (my $n = 0; $n < $#elements; $n += 2) {
4176 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4178 ## print("n: <$n> good: <$good>\n");
4180 $off += length($elements[$n]);
4182 # Pick up the preceding and succeeding characters.
4183 my $ca = substr($opline, 0, $off);
4185 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4186 $cc = substr($opline, $off + length($elements[$n + 1]));
4188 my $cb = "$ca$;$cc";
4191 $a = 'V' if ($elements[$n] ne '');
4192 $a = 'W' if ($elements[$n] =~ /\s$/);
4193 $a = 'C' if ($elements[$n] =~ /$;$/);
4194 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4195 $a = 'O' if ($elements[$n] eq '');
4196 $a = 'E' if ($ca =~ /^\s*$/);
4198 my $op = $elements[$n + 1];
4201 if (defined $elements[$n + 2]) {
4202 $c = 'V' if ($elements[$n + 2] ne '');
4203 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4204 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4205 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4206 $c = 'O' if ($elements[$n + 2] eq '');
4207 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4212 my $ctx = "${a}x${c}";
4214 my $at = "(ctx:$ctx)";
4216 my $ptr = substr($blank, 0, $off) . "^";
4217 my $hereptr = "$hereline$ptr\n";
4219 # Pull out the value of this operator.
4220 my $op_type = substr($curr_values, $off + 1, 1);
4222 # Get the full operator variant.
4223 my $opv = $op . substr($curr_vars, $off, 1);
4225 # Ignore operators passed as parameters.
4226 if ($op_type ne 'V' &&
4227 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4230 # } elsif ($op =~ /^$;+$/) {
4232 # ; should have either the end of line or a space or \ after it
4233 } elsif ($op eq ';') {
4234 if ($ctx !~ /.x[WEBC]/ &&
4235 $cc !~ /^\\/ && $cc !~ /^;/) {
4236 if (ERROR("SPACING",
4237 "space required after that '$op' $at\n" . $hereptr)) {
4238 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4244 } elsif ($op eq '//') {
4246 # : when part of a bitfield
4247 } elsif ($opv eq ':B') {
4248 # skip the bitfield test for now
4252 } elsif ($op eq '->') {
4253 if ($ctx =~ /Wx.|.xW/) {
4254 if (ERROR("SPACING",
4255 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4256 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4257 if (defined $fix_elements[$n + 2]) {
4258 $fix_elements[$n + 2] =~ s/^\s+//;
4264 # , must not have a space before and must have a space on the right.
4265 } elsif ($op eq ',') {
4266 my $rtrim_before = 0;
4267 my $space_after = 0;
4268 if ($ctx =~ /Wx./) {
4269 if (ERROR("SPACING",
4270 "space prohibited before that '$op' $at\n" . $hereptr)) {
4275 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4276 if (ERROR("SPACING",
4277 "space required after that '$op' $at\n" . $hereptr)) {
4283 if ($rtrim_before || $space_after) {
4284 if ($rtrim_before) {
4285 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4287 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4294 # '*' as part of a type definition -- reported already.
4295 } elsif ($opv eq '*_') {
4296 #warn "'*' is part of type\n";
4298 # unary operators should have a space before and
4299 # none after. May be left adjacent to another
4300 # unary operator, or a cast
4301 } elsif ($op eq '!' || $op eq '~' ||
4302 $opv eq '*U' || $opv eq '-U' ||
4303 $opv eq '&U' || $opv eq '&&U') {
4304 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4305 if (ERROR("SPACING",
4306 "space required before that '$op' $at\n" . $hereptr)) {
4307 if ($n != $last_after + 2) {
4308 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4313 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4314 # A unary '*' may be const
4316 } elsif ($ctx =~ /.xW/) {
4317 if (ERROR("SPACING",
4318 "space prohibited after that '$op' $at\n" . $hereptr)) {
4319 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4320 if (defined $fix_elements[$n + 2]) {
4321 $fix_elements[$n + 2] =~ s/^\s+//;
4327 # unary ++ and unary -- are allowed no space on one side.
4328 } elsif ($op eq '++' or $op eq '--') {
4329 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4330 if (ERROR("SPACING",
4331 "space required one side of that '$op' $at\n" . $hereptr)) {
4332 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4336 if ($ctx =~ /Wx[BE]/ ||
4337 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4338 if (ERROR("SPACING",
4339 "space prohibited before that '$op' $at\n" . $hereptr)) {
4340 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4344 if ($ctx =~ /ExW/) {
4345 if (ERROR("SPACING",
4346 "space prohibited after that '$op' $at\n" . $hereptr)) {
4347 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4348 if (defined $fix_elements[$n + 2]) {
4349 $fix_elements[$n + 2] =~ s/^\s+//;
4355 # << and >> may either have or not have spaces both sides
4356 } elsif ($op eq '<<' or $op eq '>>' or
4357 $op eq '&' or $op eq '^' or $op eq '|' or
4358 $op eq '+' or $op eq '-' or
4359 $op eq '*' or $op eq '/' or
4363 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4365 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4366 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4367 $fix_elements[$n + 2] =~ s/^\s+//;
4370 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4372 "space preferred before that '$op' $at\n" . $hereptr)) {
4373 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4377 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4378 if (ERROR("SPACING",
4379 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4380 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4381 if (defined $fix_elements[$n + 2]) {
4382 $fix_elements[$n + 2] =~ s/^\s+//;
4388 # A colon needs no spaces before when it is
4389 # terminating a case value or a label.
4390 } elsif ($opv eq ':C' || $opv eq ':L') {
4391 if ($ctx =~ /Wx./) {
4392 if (ERROR("SPACING",
4393 "space prohibited before that '$op' $at\n" . $hereptr)) {
4394 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4399 # All the others need spaces both sides.
4400 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4403 # Ignore email addresses <foo@bar>
4405 $cc =~ /^\S+\@\S+>/) ||
4407 $ca =~ /<\S+\@\S+$/))
4412 # for asm volatile statements
4413 # ignore a colon with another
4414 # colon immediately before or after
4416 ($ca =~ /:$/ || $cc =~ /^:/)) {
4420 # messages are ERROR, but ?: are CHK
4422 my $msg_level = \&ERROR;
4423 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4425 if (&{$msg_level}("SPACING",
4426 "spaces required around that '$op' $at\n" . $hereptr)) {
4427 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4428 if (defined $fix_elements[$n + 2]) {
4429 $fix_elements[$n + 2] =~ s/^\s+//;
4435 $off += length($elements[$n + 1]);
4437 ## print("n: <$n> GOOD: <$good>\n");
4439 $fixed_line = $fixed_line . $good;
4442 if (($#elements % 2) == 0) {
4443 $fixed_line = $fixed_line . $fix_elements[$#elements];
4446 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4447 $fixed[$fixlinenr] = $fixed_line;
4453 # check for whitespace before a non-naked semicolon
4454 if ($line =~ /^\+.*\S\s+;\s*$/) {
4456 "space prohibited before semicolon\n" . $herecurr) &&
4458 1 while $fixed[$fixlinenr] =~
4459 s/^(\+.*\S)\s+;/$1;/;
4463 # check for multiple assignments
4464 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4465 CHK("MULTIPLE_ASSIGNMENTS",
4466 "multiple assignments should be avoided\n" . $herecurr);
4469 ## # check for multiple declarations, allowing for a function declaration
4471 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4472 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4474 ## # Remove any bracketed sections to ensure we do not
4475 ## # falsly report the parameters of functions.
4477 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4479 ## if ($ln =~ /,/) {
4480 ## WARN("MULTIPLE_DECLARATION",
4481 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4485 #need space before brace following if, while, etc
4486 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4488 if (ERROR("SPACING",
4489 "space required before the open brace '{'\n" . $herecurr) &&
4491 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\)))\{/$1 {/;
4495 ## # check for blank lines before declarations
4496 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4497 ## $prevrawline =~ /^.\s*$/) {
4499 ## "No blank lines before declarations\n" . $hereprev);
4503 # closing brace should have a space following it when it has anything
4505 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4506 if (ERROR("SPACING",
4507 "space required after that close brace '}'\n" . $herecurr) &&
4509 $fixed[$fixlinenr] =~
4510 s/}((?!(?:,|;|\)))\S)/} $1/;
4514 # check spacing on square brackets
4515 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4516 if (ERROR("SPACING",
4517 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4519 $fixed[$fixlinenr] =~
4523 if ($line =~ /\s\]/) {
4524 if (ERROR("SPACING",
4525 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4527 $fixed[$fixlinenr] =~
4532 # check spacing on parentheses
4533 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4534 $line !~ /for\s*\(\s+;/) {
4535 if (ERROR("SPACING",
4536 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4538 $fixed[$fixlinenr] =~
4542 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4543 $line !~ /for\s*\(.*;\s+\)/ &&
4544 $line !~ /:\s+\)/) {
4545 if (ERROR("SPACING",
4546 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4548 $fixed[$fixlinenr] =~
4553 # check unnecessary parentheses around addressof/dereference single $Lvals
4554 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4556 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4558 if (CHK("UNNECESSARY_PARENTHESES",
4559 "Unnecessary parentheses around $var\n" . $herecurr) &&
4561 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4565 # check for unnecessary parentheses around function pointer uses
4566 # ie: (foo->bar)(); should be foo->bar();
4567 # but not "if (foo->bar) (" to avoid some false positives
4568 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4570 if (CHK("UNNECESSARY_PARENTHESES",
4571 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4573 my $var2 = deparenthesize($var);
4575 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4579 # check for unnecessary parentheses around comparisons in if uses
4580 # when !drivers/staging or command-line uses --strict
4581 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4582 $perl_version_ok && defined($stat) &&
4583 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4585 my $test = substr($2, 1, -1);
4587 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4589 # avoid parentheses around potential macro args
4590 next if ($match =~ /^\s*\w+\s*$/);
4591 if (!defined($herectx)) {
4592 $herectx = $here . "\n";
4593 my $cnt = statement_rawlines($if_stat);
4594 for (my $n = 0; $n < $cnt; $n++) {
4595 my $rl = raw_line($linenr, $n);
4596 $herectx .= $rl . "\n";
4597 last if $rl =~ /^[ \+].*\{/;
4600 CHK("UNNECESSARY_PARENTHESES",
4601 "Unnecessary parentheses around '$match'\n" . $herectx);
4605 #goto labels aren't indented, allow a single space however
4606 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4607 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4608 if (WARN("INDENTED_LABEL",
4609 "labels should not be indented\n" . $herecurr) &&
4611 $fixed[$fixlinenr] =~
4616 # return is not a function
4617 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4619 if ($perl_version_ok &&
4620 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4622 $value = deparenthesize($value);
4623 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4624 ERROR("RETURN_PARENTHESES",
4625 "return is not a function, parentheses are not required\n" . $herecurr);
4627 } elsif ($spacing !~ /\s+/) {
4629 "space required before the open parenthesis '('\n" . $herecurr);
4633 # unnecessary return in a void function
4634 # at end-of-function, with the previous line a single leading tab, then return;
4635 # and the line before that not a goto label target like "out:"
4636 if ($sline =~ /^[ \+]}\s*$/ &&
4637 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4639 $lines[$linenr - 3] =~ /^[ +]/ &&
4640 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4642 "void function return statements are not generally useful\n" . $hereprev);
4645 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4646 if ($perl_version_ok &&
4647 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4648 my $openparens = $1;
4649 my $count = $openparens =~ tr@\(@\(@;
4651 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4652 my $comp = $4; #Not $1 because of $LvalOrFunc
4653 $msg = " - maybe == should be = ?" if ($comp eq "==");
4654 WARN("UNNECESSARY_PARENTHESES",
4655 "Unnecessary parentheses$msg\n" . $herecurr);
4659 # comparisons with a constant or upper case identifier on the left
4660 # avoid cases like "foo + BAR < baz"
4661 # only fix matches surrounded by parentheses to avoid incorrect
4662 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4663 if ($perl_version_ok &&
4664 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4669 my $newcomp = $comp;
4670 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4671 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4672 WARN("CONSTANT_COMPARISON",
4673 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4677 } elsif ($comp eq "<=") {
4679 } elsif ($comp eq ">") {
4681 } elsif ($comp eq ">=") {
4684 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4688 # Return of what appears to be an errno should normally be negative
4689 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4691 if ($name ne 'EOF' && $name ne 'ERROR') {
4692 WARN("USE_NEGATIVE_ERRNO",
4693 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4697 # Need a space before open parenthesis after if, while etc
4698 if ($line =~ /\b(if|while|for|switch)\(/) {
4699 if (ERROR("SPACING",
4700 "space required before the open parenthesis '('\n" . $herecurr) &&
4702 $fixed[$fixlinenr] =~
4703 s/\b(if|while|for|switch)\(/$1 \(/;
4707 # Check for illegal assignment in if conditional -- and check for trailing
4708 # statements after the conditional.
4709 if ($line =~ /do\s*(?!{)/) {
4710 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4711 ctx_statement_block($linenr, $realcnt, 0)
4712 if (!defined $stat);
4713 my ($stat_next) = ctx_statement_block($line_nr_next,
4714 $remain_next, $off_next);
4715 $stat_next =~ s/\n./\n /g;
4716 ##print "stat<$stat> stat_next<$stat_next>\n";
4718 if ($stat_next =~ /^\s*while\b/) {
4719 # If the statement carries leading newlines,
4720 # then count those as offsets.
4722 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4724 statement_rawlines($whitespace) - 1;
4726 $suppress_whiletrailers{$line_nr_next +
4730 if (!defined $suppress_whiletrailers{$linenr} &&
4731 defined($stat) && defined($cond) &&
4732 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4733 my ($s, $c) = ($stat, $cond);
4735 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4736 ERROR("ASSIGN_IN_IF",
4737 "do not use assignment in if condition\n" . $herecurr);
4740 # Find out what is on the end of the line after the
4742 substr($s, 0, length($c), '');
4744 $s =~ s/$;//g; # Remove any comments
4745 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4746 $c !~ /}\s*while\s*/)
4748 # Find out how long the conditional actually is.
4749 my @newlines = ($c =~ /\n/gs);
4750 my $cond_lines = 1 + $#newlines;
4753 $stat_real = raw_line($linenr, $cond_lines)
4754 . "\n" if ($cond_lines);
4755 if (defined($stat_real) && $cond_lines > 1) {
4756 $stat_real = "[...]\n$stat_real";
4759 ERROR("TRAILING_STATEMENTS",
4760 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4764 # Check for bitwise tests written as boolean
4776 WARN("HEXADECIMAL_BOOLEAN_TEST",
4777 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4780 # if and else should not have general statements after it
4781 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4783 $s =~ s/$;//g; # Remove any comments
4784 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4785 ERROR("TRAILING_STATEMENTS",
4786 "trailing statements should be on next line\n" . $herecurr);
4789 # if should not continue a brace
4790 if ($line =~ /}\s*if\b/) {
4791 ERROR("TRAILING_STATEMENTS",
4792 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4795 # case and default should not have general statements after them
4796 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4798 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4802 ERROR("TRAILING_STATEMENTS",
4803 "trailing statements should be on next line\n" . $herecurr);
4806 # Check for }<nl>else {, these must be at the same
4807 # indent level to be relevant to each other.
4808 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4809 $previndent == $indent) {
4810 if (ERROR("ELSE_AFTER_BRACE",
4811 "else should follow close brace '}'\n" . $hereprev) &&
4812 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4813 fix_delete_line($fixlinenr - 1, $prevrawline);
4814 fix_delete_line($fixlinenr, $rawline);
4815 my $fixedline = $prevrawline;
4816 $fixedline =~ s/}\s*$//;
4817 if ($fixedline !~ /^\+\s*$/) {
4818 fix_insert_line($fixlinenr, $fixedline);
4820 $fixedline = $rawline;
4821 $fixedline =~ s/^(.\s*)else/$1} else/;
4822 fix_insert_line($fixlinenr, $fixedline);
4826 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4827 $previndent == $indent) {
4828 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4830 # Find out what is on the end of the line after the
4832 substr($s, 0, length($c), '');
4835 if ($s =~ /^\s*;/) {
4836 if (ERROR("WHILE_AFTER_BRACE",
4837 "while should follow close brace '}'\n" . $hereprev) &&
4838 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4839 fix_delete_line($fixlinenr - 1, $prevrawline);
4840 fix_delete_line($fixlinenr, $rawline);
4841 my $fixedline = $prevrawline;
4842 my $trailing = $rawline;
4843 $trailing =~ s/^\+//;
4844 $trailing = trim($trailing);
4845 $fixedline =~ s/}\s*$/} $trailing/;
4846 fix_insert_line($fixlinenr, $fixedline);
4851 #Specific variable tests
4852 while ($line =~ m{($Constant|$Lval)}g) {
4855 #gcc binary extension
4856 if ($var =~ /^$Binary$/) {
4857 if (WARN("GCC_BINARY_CONSTANT",
4858 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4860 my $hexval = sprintf("0x%x", oct($var));
4861 $fixed[$fixlinenr] =~
4862 s/\b$var\b/$hexval/;
4867 if ($var !~ /^$Constant$/ &&
4868 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4869 #Ignore Page<foo> variants
4870 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4871 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4872 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4873 #Ignore some three character SI units explicitly, like MiB and KHz
4874 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4875 while ($var =~ m{($Ident)}g) {
4877 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4879 seed_camelcase_includes();
4880 if (!$file && !$camelcase_file_seeded) {
4881 seed_camelcase_file($realfile);
4882 $camelcase_file_seeded = 1;
4885 if (!defined $camelcase{$word}) {
4886 $camelcase{$word} = 1;
4888 "Avoid CamelCase: <$word>\n" . $herecurr);
4894 #no spaces allowed after \ in define
4895 if ($line =~ /\#\s*define.*\\\s+$/) {
4896 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4897 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4899 $fixed[$fixlinenr] =~ s/\s+$//;
4903 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4904 # itself <asm/foo.h> (uses RAW line)
4905 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4907 my $checkfile = "include/linux/$file";
4908 if (-f "$root/$checkfile" &&
4909 $realfile ne $checkfile &&
4910 $1 !~ /$allowed_asm_includes/)
4912 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4913 if ($asminclude > 0) {
4914 if ($realfile =~ m{^arch/}) {
4915 CHK("ARCH_INCLUDE_LINUX",
4916 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4918 WARN("INCLUDE_LINUX",
4919 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4925 # multi-statement macros should be enclosed in a do while loop, grab the
4926 # first statement and ensure its the whole macro if its not enclosed
4927 # in a known good container
4928 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4929 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4932 my ($off, $dstat, $dcond, $rest);
4934 my $has_flow_statement = 0;
4935 my $has_arg_concat = 0;
4936 ($dstat, $dcond, $ln, $cnt, $off) =
4937 ctx_statement_block($linenr, $realcnt, 0);
4939 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4940 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4942 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4943 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
4945 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
4946 my $define_args = $1;
4947 my $define_stmt = $dstat;
4950 if (defined $define_args && $define_args ne "") {
4951 $define_args = substr($define_args, 1, length($define_args) - 2);
4952 $define_args =~ s/\s*//g;
4953 @def_args = split(",", $define_args);
4957 $dstat =~ s/\\\n.//g;
4958 $dstat =~ s/^\s*//s;
4959 $dstat =~ s/\s*$//s;
4961 # Flatten any parentheses and braces
4962 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4963 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4964 $dstat =~ s/.\[[^\[\]]*\]/1/)
4968 # Flatten any obvious string concatentation.
4969 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
4970 $dstat =~ s/$Ident\s*($String)/$1/)
4974 # Make asm volatile uses seem like a generic function
4975 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
4977 my $exceptions = qr{
4990 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4993 my $stmt_cnt = statement_rawlines($ctx);
4994 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
4997 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4998 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4999 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5000 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5001 $dstat !~ /$exceptions/ &&
5002 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5003 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5004 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5005 $dstat !~ /^for\s*$Constant$/ && # for (...)
5006 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5007 $dstat !~ /^do\s*{/ && # do {...
5008 $dstat !~ /^\(\{/ && # ({...
5009 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5011 if ($dstat =~ /^\s*if\b/) {
5012 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5013 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5014 } elsif ($dstat =~ /;/) {
5015 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5016 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5018 ERROR("COMPLEX_MACRO",
5019 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5024 # Make $define_stmt single line, comment-free, etc
5025 my @stmt_array = split('\n', $define_stmt);
5028 foreach my $l (@stmt_array) {
5033 } elsif ($l =~ /^[\+ ]/) {
5034 $define_stmt .= substr($l, 1);
5037 $define_stmt =~ s/$;//g;
5038 $define_stmt =~ s/\s+/ /g;
5039 $define_stmt = trim($define_stmt);
5041 # check if any macro arguments are reused (ignore '...' and 'type')
5042 foreach my $arg (@def_args) {
5043 next if ($arg =~ /\.\.\./);
5044 next if ($arg =~ /^type$/i);
5045 my $tmp_stmt = $define_stmt;
5046 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5047 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5048 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5049 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5051 CHK("MACRO_ARG_REUSE",
5052 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5054 # check if any macro arguments may have other precedence issues
5055 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5056 ((defined($1) && $1 ne ',') ||
5057 (defined($2) && $2 ne ','))) {
5058 CHK("MACRO_ARG_PRECEDENCE",
5059 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5063 # check for macros with flow control, but without ## concatenation
5064 # ## concatenation is commonly a macro that defines a function so ignore those
5065 if ($has_flow_statement && !$has_arg_concat) {
5066 my $cnt = statement_rawlines($ctx);
5067 my $herectx = get_stat_here($linenr, $cnt, $here);
5069 WARN("MACRO_WITH_FLOW_CONTROL",
5070 "Macros with flow control statements should be avoided\n" . "$herectx");
5073 # check for line continuations outside of #defines, preprocessor #, and asm
5076 if ($prevline !~ /^..*\\$/ &&
5077 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5078 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5079 $line =~ /^\+.*\\$/) {
5080 WARN("LINE_CONTINUATIONS",
5081 "Avoid unnecessary line continuations\n" . $herecurr);
5085 # do {} while (0) macro tests:
5086 # single-statement macros do not need to be enclosed in do while (0) loop,
5087 # macro should not end with a semicolon
5088 if ($perl_version_ok &&
5089 $realfile !~ m@/vmlinux.lds.h$@ &&
5090 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5093 my ($off, $dstat, $dcond, $rest);
5095 ($dstat, $dcond, $ln, $cnt, $off) =
5096 ctx_statement_block($linenr, $realcnt, 0);
5099 $dstat =~ s/\\\n.//g;
5102 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5107 my $cnt = statement_rawlines($ctx);
5108 my $herectx = get_stat_here($linenr, $cnt, $here);
5110 if (($stmts =~ tr/;/;/) == 1 &&
5111 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5112 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5113 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5115 if (defined $semis && $semis ne "") {
5116 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5117 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5119 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5121 my $cnt = statement_rawlines($ctx);
5122 my $herectx = get_stat_here($linenr, $cnt, $here);
5124 WARN("TRAILING_SEMICOLON",
5125 "macros should not use a trailing semicolon\n" . "$herectx");
5129 # check for redundant bracing round if etc
5130 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5131 my ($level, $endln, @chunks) =
5132 ctx_statement_full($linenr, $realcnt, 1);
5133 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5134 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5135 if ($#chunks > 0 && $level == 0) {
5139 my $herectx = $here . "\n";
5140 my $ln = $linenr - 1;
5141 for my $chunk (@chunks) {
5142 my ($cond, $block) = @{$chunk};
5144 # If the condition carries leading newlines, then count those as offsets.
5145 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5146 my $offset = statement_rawlines($whitespace) - 1;
5148 $allowed[$allow] = 0;
5149 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5151 # We have looked at and allowed this specific line.
5152 $suppress_ifbraces{$ln + $offset} = 1;
5154 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5155 $ln += statement_rawlines($block) - 1;
5157 substr($block, 0, length($cond), '');
5159 $seen++ if ($block =~ /^\s*{/);
5161 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5162 if (statement_lines($cond) > 1) {
5163 #print "APW: ALLOWED: cond<$cond>\n";
5164 $allowed[$allow] = 1;
5166 if ($block =~/\b(?:if|for|while)\b/) {
5167 #print "APW: ALLOWED: block<$block>\n";
5168 $allowed[$allow] = 1;
5170 if (statement_block_size($block) > 1) {
5171 #print "APW: ALLOWED: lines block<$block>\n";
5172 $allowed[$allow] = 1;
5177 my $sum_allowed = 0;
5178 foreach (@allowed) {
5181 if ($sum_allowed == 0) {
5183 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5184 } elsif ($sum_allowed != $allow &&
5187 "braces {} should be used on all arms of this statement\n" . $herectx);
5192 if (!defined $suppress_ifbraces{$linenr - 1} &&
5193 $line =~ /\b(if|while|for|else)\b/) {
5196 # Check the pre-context.
5197 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5198 #print "APW: ALLOWED: pre<$1>\n";
5202 my ($level, $endln, @chunks) =
5203 ctx_statement_full($linenr, $realcnt, $-[0]);
5205 # Check the condition.
5206 my ($cond, $block) = @{$chunks[0]};
5207 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5208 if (defined $cond) {
5209 substr($block, 0, length($cond), '');
5211 if (statement_lines($cond) > 1) {
5212 #print "APW: ALLOWED: cond<$cond>\n";
5215 if ($block =~/\b(?:if|for|while)\b/) {
5216 #print "APW: ALLOWED: block<$block>\n";
5219 if (statement_block_size($block) > 1) {
5220 #print "APW: ALLOWED: lines block<$block>\n";
5223 # Check the post-context.
5224 if (defined $chunks[1]) {
5225 my ($cond, $block) = @{$chunks[1]};
5226 if (defined $cond) {
5227 substr($block, 0, length($cond), '');
5229 if ($block =~ /^\s*\{/) {
5230 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5234 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5235 my $cnt = statement_rawlines($block);
5236 my $herectx = get_stat_here($linenr, $cnt, $here);
5239 "braces {} are not necessary for single statement blocks\n" . $herectx);
5243 # check for single line unbalanced braces
5244 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5245 $sline =~ /^.\s*else\s*\{\s*$/) {
5246 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5249 # check for unnecessary blank lines around braces
5250 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5252 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5253 $fix && $prevrawline =~ /^\+/) {
5254 fix_delete_line($fixlinenr - 1, $prevrawline);
5257 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5259 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5261 fix_delete_line($fixlinenr, $rawline);
5265 # no volatiles please
5266 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5267 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5269 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5272 # Check for user-visible strings broken across lines, which breaks the ability
5273 # to grep for the string. Make exceptions when the previous string ends in a
5274 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5275 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5276 if ($line =~ /^\+\s*$String/ &&
5277 $prevline =~ /"\s*$/ &&
5278 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5279 if (WARN("SPLIT_STRING",
5280 "quoted string split across lines\n" . $hereprev) &&
5282 $prevrawline =~ /^\+.*"\s*$/ &&
5283 $last_coalesced_string_linenr != $linenr - 1) {
5284 my $extracted_string = get_quoted_string($line, $rawline);
5285 my $comma_close = "";
5286 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5290 fix_delete_line($fixlinenr - 1, $prevrawline);
5291 fix_delete_line($fixlinenr, $rawline);
5292 my $fixedline = $prevrawline;
5293 $fixedline =~ s/"\s*$//;
5294 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5295 fix_insert_line($fixlinenr - 1, $fixedline);
5296 $fixedline = $rawline;
5297 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5298 if ($fixedline !~ /\+\s*$/) {
5299 fix_insert_line($fixlinenr, $fixedline);
5301 $last_coalesced_string_linenr = $linenr;
5305 # check for missing a space in a string concatenation
5306 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5307 WARN('MISSING_SPACE',
5308 "break quoted strings at a space character\n" . $hereprev);
5311 # check for an embedded function name in a string when the function is known
5312 # This does not work very well for -f --file checking as it depends on patch
5313 # context providing the function name or a single line form for in-file
5314 # function declarations
5315 if ($line =~ /^\+.*$String/ &&
5316 defined($context_function) &&
5317 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5318 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5319 WARN("EMBEDDED_FUNCTION_NAME",
5320 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5323 # check for spaces before a quoted newline
5324 if ($rawline =~ /^.*\".*\s\\n/) {
5325 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5326 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5328 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5333 # concatenated string without spaces between elements
5334 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5335 if (CHK("CONCATENATED_STRING",
5336 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5338 while ($line =~ /($String)/g) {
5339 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5340 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5341 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5346 # uncoalesced string fragments
5347 if ($line =~ /$String\s*"/) {
5348 if (WARN("STRING_FRAGMENTS",
5349 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5351 while ($line =~ /($String)(?=\s*")/g) {
5352 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5353 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5358 # check for non-standard and hex prefixed decimal printf formats
5359 my $show_L = 1; #don't show the same defect twice
5361 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5362 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5363 $string =~ s/%%/__/g;
5365 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5367 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5371 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5373 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5376 # check for 0x<decimal>
5377 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5378 ERROR("PRINTF_0XDECIMAL",
5379 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5383 # check for line continuations in quoted strings with odd counts of "
5384 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5385 WARN("LINE_CONTINUATIONS",
5386 "Avoid line continuations in quoted strings\n" . $herecurr);
5390 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5391 CHK("REDUNDANT_CODE",
5392 "if this code is redundant consider removing it\n" .
5396 # check for needless "if (<foo>) fn(<foo>)" uses
5397 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5398 my $tested = quotemeta($1);
5399 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5400 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5402 if (WARN('NEEDLESS_IF',
5403 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5406 my $leading_tabs = "";
5407 my $new_leading_tabs = "";
5408 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5413 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5414 $new_leading_tabs = $1;
5415 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5422 fix_delete_line($fixlinenr - 1, $prevrawline);
5423 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5429 # check for unnecessary "Out of Memory" messages
5430 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5431 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5432 (defined $1 || defined $3) &&
5435 my $testline = $lines[$linenr - 3];
5437 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5438 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5440 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)/) {
5442 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5446 # check for logging functions with KERN_<LEVEL>
5447 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5448 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5450 if (WARN("UNNECESSARY_KERN_LEVEL",
5451 "Possible unnecessary $level\n" . $herecurr) &&
5453 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5457 # check for logging continuations
5458 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5459 WARN("LOGGING_CONTINUATION",
5460 "Avoid logging continuation uses where feasible\n" . $herecurr);
5463 # check for mask then right shift without a parentheses
5464 if ($perl_version_ok &&
5465 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5466 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5467 WARN("MASK_THEN_SHIFT",
5468 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5471 # check for pointer comparisons to NULL
5472 if ($perl_version_ok) {
5473 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5476 $equal = "" if ($4 eq "!=");
5477 if (CHK("COMPARISON_TO_NULL",
5478 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5480 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5485 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5486 if ($line =~ /(\b$InitAttribute\b)/) {
5488 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5491 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5492 ERROR("MISPLACED_INIT",
5493 "$attr should be placed after $var\n" . $herecurr)) ||
5494 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5495 WARN("MISPLACED_INIT",
5496 "$attr should be placed after $var\n" . $herecurr))) &&
5498 $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;
5503 # check for $InitAttributeData (ie: __initdata) with const
5504 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5506 $attr =~ /($InitAttributePrefix)(.*)/;
5507 my $attr_prefix = $1;
5509 if (ERROR("INIT_ATTRIBUTE",
5510 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5512 $fixed[$fixlinenr] =~
5513 s/$InitAttributeData/${attr_prefix}initconst/;
5517 # check for $InitAttributeConst (ie: __initconst) without const
5518 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5520 if (ERROR("INIT_ATTRIBUTE",
5521 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5523 my $lead = $fixed[$fixlinenr] =~
5524 /(^\+\s*(?:static\s+))/;
5526 $lead = "$lead " if ($lead !~ /^\+$/);
5527 $lead = "${lead}const ";
5528 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5532 # check for __read_mostly with const non-pointer (should just be const)
5533 if ($line =~ /\b__read_mostly\b/ &&
5534 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5535 if (ERROR("CONST_READ_MOSTLY",
5536 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5538 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5542 # don't use __constant_<foo> functions outside of include/uapi/
5543 if ($realfile !~ m@^include/uapi/@ &&
5544 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5545 my $constant_func = $1;
5546 my $func = $constant_func;
5547 $func =~ s/^__constant_//;
5548 if (WARN("CONSTANT_CONVERSION",
5549 "$constant_func should be $func\n" . $herecurr) &&
5551 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5555 # prefer usleep_range over udelay
5556 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5558 # ignore udelay's < 10, however
5559 if (! ($delay < 10) ) {
5561 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5563 if ($delay > 2000) {
5565 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5569 # warn about unexpectedly long msleep's
5570 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5573 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5577 # check for comparisons of jiffies
5578 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5579 WARN("JIFFIES_COMPARISON",
5580 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5583 # check for comparisons of get_jiffies_64()
5584 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5585 WARN("JIFFIES_COMPARISON",
5586 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5589 # warn about #ifdefs in C files
5590 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5591 # print "#ifdef in C files should be avoided\n";
5592 # print "$herecurr";
5596 # warn about spacing in #ifdefs
5597 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5598 if (ERROR("SPACING",
5599 "exactly one space required after that #$1\n" . $herecurr) &&
5601 $fixed[$fixlinenr] =~
5602 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5607 # check for spinlock_t definitions without a comment.
5608 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5609 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5611 if (!ctx_has_comment($first_line, $linenr)) {
5612 CHK("UNCOMMENTED_DEFINITION",
5613 "$1 definition without comment\n" . $herecurr);
5616 # check for memory barriers without a comment.
5622 read_barrier_depends
5624 my $barrier_stems = qr{
5632 my $all_barriers = qr{
5634 smp_(?:$barrier_stems)|
5635 virt_(?:$barrier_stems)
5638 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5639 if (!ctx_has_comment($first_line, $linenr)) {
5640 WARN("MEMORY_BARRIER",
5641 "memory barrier without comment\n" . $herecurr);
5645 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5647 if ($realfile !~ m@^include/asm-generic/@ &&
5648 $realfile !~ m@/barrier\.h$@ &&
5649 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5650 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5651 WARN("MEMORY_BARRIER",
5652 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5655 # check for waitqueue_active without a comment.
5656 if ($line =~ /\bwaitqueue_active\s*\(/) {
5657 if (!ctx_has_comment($first_line, $linenr)) {
5658 WARN("WAITQUEUE_ACTIVE",
5659 "waitqueue_active without comment\n" . $herecurr);
5663 # check for smp_read_barrier_depends and read_barrier_depends
5664 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5665 WARN("READ_BARRIER_DEPENDS",
5666 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5669 # check of hardware specific defines
5670 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5672 "architecture specific defines should be avoided\n" . $herecurr);
5675 # check that the storage class is not after a type
5676 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5677 WARN("STORAGE_CLASS",
5678 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5680 # Check that the storage class is at the beginning of a declaration
5681 if ($line =~ /\b$Storage\b/ &&
5682 $line !~ /^.\s*$Storage/ &&
5683 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5684 $1 !~ /[\,\)]\s*$/) {
5685 WARN("STORAGE_CLASS",
5686 "storage class should be at the beginning of the declaration\n" . $herecurr);
5689 # check the location of the inline attribute, that it is between
5690 # storage class and type.
5691 if ($line =~ /\b$Type\s+$Inline\b/ ||
5692 $line =~ /\b$Inline\s+$Storage\b/) {
5693 ERROR("INLINE_LOCATION",
5694 "inline keyword should sit between storage class and type\n" . $herecurr);
5697 # Check for __inline__ and __inline, prefer inline
5698 if ($realfile !~ m@\binclude/uapi/@ &&
5699 $line =~ /\b(__inline__|__inline)\b/) {
5701 "plain inline is preferred over $1\n" . $herecurr) &&
5703 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5708 # Check for __attribute__ packed, prefer __packed
5709 if ($realfile !~ m@\binclude/uapi/@ &&
5710 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5711 WARN("PREFER_PACKED",
5712 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5715 # Check for __attribute__ aligned, prefer __aligned
5716 if ($realfile !~ m@\binclude/uapi/@ &&
5717 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5718 WARN("PREFER_ALIGNED",
5719 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5722 # Check for __attribute__ format(printf, prefer __printf
5723 if ($realfile !~ m@\binclude/uapi/@ &&
5724 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5725 if (WARN("PREFER_PRINTF",
5726 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5728 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5733 # Check for __attribute__ format(scanf, prefer __scanf
5734 if ($realfile !~ m@\binclude/uapi/@ &&
5735 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5736 if (WARN("PREFER_SCANF",
5737 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5739 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5743 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5744 if ($perl_version_ok &&
5745 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5746 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5747 $line =~ /\b__weak\b/)) {
5748 ERROR("WEAK_DECLARATION",
5749 "Using weak declarations can have unintended link defects\n" . $herecurr);
5752 # check for c99 types like uint8_t used outside of uapi/ and tools/
5753 if ($realfile !~ m@\binclude/uapi/@ &&
5754 $realfile !~ m@\btools/@ &&
5755 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5757 if ($type =~ /\b($typeC99Typedefs)\b/) {
5759 my $kernel_type = 'u';
5760 $kernel_type = 's' if ($type =~ /^_*[si]/);
5763 if (CHK("PREFER_KERNEL_TYPES",
5764 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5766 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5771 # check for cast of C90 native int or longer types constants
5772 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5775 if (WARN("TYPECAST_INT_CONSTANT",
5776 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5779 my $newconst = $const;
5780 $newconst =~ s/${Int_type}$//;
5781 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5782 if ($cast =~ /\blong\s+long\b/) {
5784 } elsif ($cast =~ /\blong\b/) {
5787 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5791 # check for sizeof(&)
5792 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5793 WARN("SIZEOF_ADDRESS",
5794 "sizeof(& should be avoided\n" . $herecurr);
5797 # check for sizeof without parenthesis
5798 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5799 if (WARN("SIZEOF_PARENTHESIS",
5800 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5802 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5806 # check for struct spinlock declarations
5807 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5808 WARN("USE_SPINLOCK_T",
5809 "struct spinlock should be spinlock_t\n" . $herecurr);
5812 # check for seq_printf uses that could be seq_puts
5813 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5814 my $fmt = get_quoted_string($line, $rawline);
5817 if (WARN("PREFER_SEQ_PUTS",
5818 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5820 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5825 # check for vsprintf extension %p<foo> misuses
5826 if ($perl_version_ok &&
5828 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5829 $1 !~ /^_*volatile_*$/) {
5832 my $lc = $stat =~ tr@\n@@;
5833 $lc = $lc + $linenr;
5834 for (my $count = $linenr; $count <= $lc; $count++) {
5837 my $bad_specifier = "";
5838 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5841 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5844 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5845 $bad_specifier = $specifier;
5848 if ($extension eq "x" && !defined($stat_real)) {
5849 if (!defined($stat_real)) {
5850 $stat_real = get_stat_real($linenr, $lc);
5852 WARN("VSPRINTF_SPECIFIER_PX",
5853 "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");
5856 if ($bad_specifier ne "") {
5857 my $stat_real = get_stat_real($linenr, $lc);
5858 my $ext_type = "Invalid";
5860 if ($bad_specifier =~ /p[Ff]/) {
5861 $ext_type = "Deprecated";
5862 $use = " - use %pS instead";
5863 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5866 WARN("VSPRINTF_POINTER_EXTENSION",
5867 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5872 # Check for misused memsets
5873 if ($perl_version_ok &&
5875 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5881 if ($ms_size =~ /^(0x|)0$/i) {
5883 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5884 } elsif ($ms_size =~ /^(0x|)1$/i) {
5886 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5890 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5891 # if ($perl_version_ok &&
5893 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5894 # if (WARN("PREFER_ETHER_ADDR_COPY",
5895 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5897 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5901 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5902 # if ($perl_version_ok &&
5904 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5905 # WARN("PREFER_ETHER_ADDR_EQUAL",
5906 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5909 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5910 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5911 # if ($perl_version_ok &&
5913 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5917 # if ($ms_val =~ /^(?:0x|)0+$/i) {
5918 # if (WARN("PREFER_ETH_ZERO_ADDR",
5919 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5921 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5923 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5924 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
5925 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
5927 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
5932 # typecasts on min/max could be min_t/max_t
5933 if ($perl_version_ok &&
5935 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5936 if (defined $2 || defined $7) {
5938 my $cast1 = deparenthesize($2);
5940 my $cast2 = deparenthesize($7);
5944 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5945 $cast = "$cast1 or $cast2";
5946 } elsif ($cast1 ne "") {
5952 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5956 # check usleep_range arguments
5957 if ($perl_version_ok &&
5959 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5963 WARN("USLEEP_RANGE",
5964 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5965 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5967 WARN("USLEEP_RANGE",
5968 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5972 # check for naked sscanf
5973 if ($perl_version_ok &&
5975 $line =~ /\bsscanf\b/ &&
5976 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5977 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5978 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5979 my $lc = $stat =~ tr@\n@@;
5980 $lc = $lc + $linenr;
5981 my $stat_real = get_stat_real($linenr, $lc);
5982 WARN("NAKED_SSCANF",
5983 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5986 # check for simple sscanf that should be kstrto<foo>
5987 if ($perl_version_ok &&
5989 $line =~ /\bsscanf\b/) {
5990 my $lc = $stat =~ tr@\n@@;
5991 $lc = $lc + $linenr;
5992 my $stat_real = get_stat_real($linenr, $lc);
5993 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5995 my $count = $format =~ tr@%@%@;
5997 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5998 WARN("SSCANF_TO_KSTRTO",
5999 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6004 # check for new externs in .h files.
6005 if ($realfile =~ /\.h$/ &&
6006 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6007 if (CHK("AVOID_EXTERNS",
6008 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6010 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6014 # check for new externs in .c files.
6015 if ($realfile =~ /\.c$/ && defined $stat &&
6016 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6018 my $function_name = $1;
6019 my $paren_space = $2;
6022 if (defined $cond) {
6023 substr($s, 0, length($cond), '');
6025 if ($s =~ /^\s*;/ &&
6026 $function_name ne 'uninitialized_var')
6028 WARN("AVOID_EXTERNS",
6029 "externs should be avoided in .c files\n" . $herecurr);
6032 if ($paren_space =~ /\n/) {
6033 WARN("FUNCTION_ARGUMENTS",
6034 "arguments for function declarations should follow identifier\n" . $herecurr);
6037 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6038 $stat =~ /^.\s*extern\s+/)
6040 WARN("AVOID_EXTERNS",
6041 "externs should be avoided in .c files\n" . $herecurr);
6044 # check for function declarations that have arguments without identifier names
6045 if (defined $stat &&
6046 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6048 my $args = trim($1);
6049 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6051 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6052 WARN("FUNCTION_ARGUMENTS",
6053 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6058 # check for function definitions
6059 if ($perl_version_ok &&
6061 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6062 $context_function = $1;
6064 # check for multiline function definition with misplaced open brace
6066 my $cnt = statement_rawlines($stat);
6067 my $herectx = $here . "\n";
6068 for (my $n = 0; $n < $cnt; $n++) {
6069 my $rl = raw_line($linenr, $n);
6070 $herectx .= $rl . "\n";
6071 $ok = 1 if ($rl =~ /^[ \+]\{/);
6072 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6073 last if $rl =~ /^[ \+].*\{/;
6077 "open brace '{' following function definitions go on the next line\n" . $herectx);
6081 # checks for new __setup's
6082 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6085 if (!grep(/$name/, @setup_docs)) {
6086 CHK("UNDOCUMENTED_SETUP",
6087 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6091 # check for pointless casting of kmalloc return
6092 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6093 WARN("UNNECESSARY_CASTS",
6094 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6098 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6099 if ($perl_version_ok &&
6100 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6101 CHK("ALLOC_SIZEOF_STRUCT",
6102 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6105 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6106 if ($perl_version_ok &&
6108 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6112 my $newfunc = "kmalloc_array";
6113 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6116 if ($a1 =~ /^sizeof\s*\S/) {
6120 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6121 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6122 my $cnt = statement_rawlines($stat);
6123 my $herectx = get_stat_here($linenr, $cnt, $here);
6125 if (WARN("ALLOC_WITH_MULTIPLY",
6126 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6129 $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;
6134 # check for krealloc arg reuse
6135 if ($perl_version_ok &&
6136 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
6137 WARN("KREALLOC_ARG_REUSE",
6138 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6141 # check for alloc argument mismatch
6142 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6143 WARN("ALLOC_ARRAY_ARGS",
6144 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6147 # check for multiple semicolons
6148 if ($line =~ /;\s*;\s*$/) {
6149 if (WARN("ONE_SEMICOLON",
6150 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6152 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6156 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6157 if ($realfile !~ m@^include/uapi/@ &&
6158 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6160 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6161 if (CHK("BIT_MACRO",
6162 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6164 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6168 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6169 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6171 if (WARN("PREFER_IS_ENABLED",
6172 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6174 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6178 # check for case / default statements not preceded by break/fallthrough/switch
6179 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6181 my $has_statement = 0;
6183 my $prevline = $linenr;
6184 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6186 my $rline = $rawlines[$prevline - 1];
6187 my $fline = $lines[$prevline - 1];
6188 last if ($fline =~ /^\@\@/);
6189 next if ($fline =~ /^\-/);
6190 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6191 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6192 next if ($fline =~ /^.[\s$;]*$/);
6195 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6197 if (!$has_break && $has_statement) {
6198 WARN("MISSING_BREAK",
6199 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6203 # check for switch/default statements without a break;
6204 if ($perl_version_ok &&
6206 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6207 my $cnt = statement_rawlines($stat);
6208 my $herectx = get_stat_here($linenr, $cnt, $here);
6210 WARN("DEFAULT_NO_BREAK",
6211 "switch default: should use break\n" . $herectx);
6214 # check for gcc specific __FUNCTION__
6215 if ($line =~ /\b__FUNCTION__\b/) {
6216 if (WARN("USE_FUNC",
6217 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6219 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6223 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6224 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6226 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6229 # check for use of yield()
6230 if ($line =~ /\byield\s*\(\s*\)/) {
6232 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6235 # check for comparisons against true and false
6236 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6244 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6246 my $type = lc($otype);
6247 if ($type =~ /^(?:true|false)$/) {
6248 if (("$test" eq "==" && "$type" eq "true") ||
6249 ("$test" eq "!=" && "$type" eq "false")) {
6253 CHK("BOOL_COMPARISON",
6254 "Using comparison to $otype is error prone\n" . $herecurr);
6256 ## maybe suggesting a correct construct would better
6257 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6262 # check for bool bitfields
6263 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6264 WARN("BOOL_BITFIELD",
6265 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6268 # check for bool use in .h files
6269 if ($realfile =~ /\.h$/ &&
6270 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6272 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6275 # check for semaphores initialized locked
6276 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6277 WARN("CONSIDER_COMPLETION",
6278 "consider using a completion\n" . $herecurr);
6281 # recommend kstrto* over simple_strto* and strict_strto*
6282 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6283 WARN("CONSIDER_KSTRTO",
6284 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6287 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6288 if ($line =~ /^.\s*__initcall\s*\(/) {
6289 WARN("USE_DEVICE_INITCALL",
6290 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6293 # check for various structs that are normally const (ops, kgdb, device_tree)
6294 # and avoid what seem like struct definitions 'struct foo {'
6295 if ($line !~ /\bconst\b/ &&
6296 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6297 WARN("CONST_STRUCT",
6298 "struct $1 should normally be const\n" . $herecurr);
6301 # use of NR_CPUS is usually wrong
6302 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6303 if ($line =~ /\bNR_CPUS\b/ &&
6304 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6305 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6306 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6307 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6308 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6311 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6314 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6315 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6316 ERROR("DEFINE_ARCH_HAS",
6317 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6320 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6321 if ($perl_version_ok &&
6322 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6323 WARN("LIKELY_MISUSE",
6324 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6327 # whine mightly about in_atomic
6328 if ($line =~ /\bin_atomic\s*\(/) {
6329 if ($realfile =~ m@^drivers/@) {
6331 "do not use in_atomic in drivers\n" . $herecurr);
6332 } elsif ($realfile !~ m@^kernel/@) {
6334 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6338 # check for mutex_trylock_recursive usage
6339 if ($line =~ /mutex_trylock_recursive/) {
6341 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6344 # check for lockdep_set_novalidate_class
6345 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6346 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6347 if ($realfile !~ m@^kernel/lockdep@ &&
6348 $realfile !~ m@^include/linux/lockdep@ &&
6349 $realfile !~ m@^drivers/base/core@) {
6351 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6355 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6356 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6357 WARN("EXPORTED_WORLD_WRITABLE",
6358 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6361 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6362 # and whether or not function naming is typical and if
6363 # DEVICE_ATTR permissions uses are unusual too
6364 if ($perl_version_ok &&
6366 $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*\)/) {
6371 my $octal_perms = perms_to_octal($perms);
6372 if ($show =~ /^${var}_show$/ &&
6373 $store =~ /^${var}_store$/ &&
6374 $octal_perms eq "0644") {
6375 if (WARN("DEVICE_ATTR_RW",
6376 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6378 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6380 } elsif ($show =~ /^${var}_show$/ &&
6381 $store =~ /^NULL$/ &&
6382 $octal_perms eq "0444") {
6383 if (WARN("DEVICE_ATTR_RO",
6384 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6386 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6388 } elsif ($show =~ /^NULL$/ &&
6389 $store =~ /^${var}_store$/ &&
6390 $octal_perms eq "0200") {
6391 if (WARN("DEVICE_ATTR_WO",
6392 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6394 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6396 } elsif ($octal_perms eq "0644" ||
6397 $octal_perms eq "0444" ||
6398 $octal_perms eq "0200") {
6399 my $newshow = "$show";
6400 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6401 my $newstore = $store;
6402 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6404 if ($show ne $newshow) {
6405 $rename .= " '$show' to '$newshow'";
6407 if ($store ne $newstore) {
6408 $rename .= " '$store' to '$newstore'";
6410 WARN("DEVICE_ATTR_FUNCTIONS",
6411 "Consider renaming function(s)$rename\n" . $herecurr);
6413 WARN("DEVICE_ATTR_PERMS",
6414 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6418 # Mode permission misuses where it seems decimal should be octal
6419 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6420 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6421 # specific definition of not visible in sysfs.
6422 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6423 # use the default permissions
6424 if ($perl_version_ok &&
6426 $line =~ /$mode_perms_search/) {
6427 foreach my $entry (@mode_permission_funcs) {
6428 my $func = $entry->[0];
6429 my $arg_pos = $entry->[1];
6431 my $lc = $stat =~ tr@\n@@;
6432 $lc = $lc + $linenr;
6433 my $stat_real = get_stat_real($linenr, $lc);
6438 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6440 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6441 if ($stat =~ /$test/) {
6443 $val = $6 if ($skip_args ne "");
6444 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6445 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6446 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6447 ERROR("NON_OCTAL_PERMISSIONS",
6448 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6450 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6451 ERROR("EXPORTED_WORLD_WRITABLE",
6452 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6458 # check for uses of S_<PERMS> that could be octal for readability
6459 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6461 my $octal = perms_to_octal($oval);
6462 if (WARN("SYMBOLIC_PERMS",
6463 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6465 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6469 # validate content of MODULE_LICENSE against list from include/linux/module.h
6470 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6471 my $extracted_string = get_quoted_string($line, $rawline);
6472 my $valid_licenses = qr{
6475 GPL\ and\ additional\ rights|
6481 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6482 WARN("MODULE_LICENSE",
6483 "unknown module license " . $extracted_string . "\n" . $herecurr);
6488 # If we have no input at all, then there is nothing to report on
6489 # so just keep quiet.
6490 if ($#rawlines == -1) {
6494 # In mailback mode only produce a report in the negative, for
6495 # things that appear to be patches.
6496 if ($mailback && ($clean == 1 || !$is_patch)) {
6500 # This is not a patch, and we are are in 'no-patch' mode so
6502 if (!$chk_patch && !$is_patch) {
6506 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6507 ERROR("NOT_UNIFIED_DIFF",
6508 "Does not appear to be a unified-diff format patch\n");
6510 if ($is_patch && $has_commit_log && $chk_signoff && $signoff == 0) {
6511 ERROR("MISSING_SIGN_OFF",
6512 "Missing Signed-off-by: line(s)\n");
6515 print report_dump();
6516 if ($summary && !($clean == 1 && $quiet == 1)) {
6517 print "$filename " if ($summary_file);
6518 print "total: $cnt_error errors, $cnt_warn warnings, " .
6519 (($check)? "$cnt_chk checks, " : "") .
6520 "$cnt_lines lines checked\n";
6524 # If there were any defects found and not already fixing them
6525 if (!$clean and !$fix) {
6528 NOTE: For some of the reported defects, checkpatch may be able to
6529 mechanically convert to the typical style using --fix or --fix-inplace.
6532 # If there were whitespace errors which cleanpatch can fix
6533 # then suggest that.
6534 if ($rpt_cleaners) {
6538 NOTE: Whitespace errors detected.
6539 You may wish to use scripts/cleanpatch or scripts/cleanfile
6544 if ($clean == 0 && $fix &&
6545 ("@rawlines" ne "@fixed" ||
6546 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6547 my $newfile = $filename;
6548 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6552 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6554 open($f, '>', $newfile)
6555 or die "$P: Can't open $newfile for write\n";
6556 foreach my $fixed_line (@fixed) {
6559 if ($linecount > 3) {
6560 $fixed_line =~ s/^\+//;
6561 print $f $fixed_line . "\n";
6564 print $f $fixed_line . "\n";
6572 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6574 Do _NOT_ trust the results written to this file.
6575 Do _NOT_ submit these changes without inspecting them for correctness.
6577 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6578 No warranties, expressed or implied...
6586 print "$vname has no obvious style problems and is ready for submission.\n";
6588 print "$vname has style problems, please review.\n";