2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 100;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile = "";
65 my $allow_c99_comments = 1;
71 Usage: $P [OPTION]... [FILE]...
76 --no-tree run without a kernel tree
77 --no-signoff do not check for 'Signed-off-by' line
78 --patch treat FILE as patchfile (default)
79 --emacs emacs compile window format
80 --terse one line per report
81 --showfile emit diffed file position, not input file position
82 -g, --git treat FILE as a single commit or git revision range
83 single git commit with:
87 multiple git commits with:
91 git merges are ignored
92 -f, --file treat FILE as regular source file
93 --subjective, --strict enable more subjective tests
94 --list-types list the possible message types
95 --types TYPE(,TYPE2...) show only these comma separated message types
96 --ignore TYPE(,TYPE2...) ignore various comma separated message types
97 --show-types show the specific message type in the output
98 --max-line-length=n set the maximum line length, (default $max_line_length)
99 if exceeded, warn on patches
100 requires --strict for use with --file
101 --min-conf-desc-length=n set the min description length, if shorter, warn
102 --root=PATH PATH to the kernel tree root
103 --no-summary suppress the per-file summary
104 --mailback only produce a report in case of warnings/errors
105 --summary-file include the filename in summary
106 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
107 'values', 'possible', 'type', and 'attr' (default
109 --test-only=WORD report only warnings/errors containing WORD
111 --fix EXPERIMENTAL - may create horrible results
112 If correctable single-line errors exist, create
113 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
114 with potential errors corrected to the preferred
116 --fix-inplace EXPERIMENTAL - may create horrible results
117 Is the same as --fix, but overwrites the input
118 file. It's your fault if there's no backup or git
119 --ignore-perl-version override checking of perl version. expect
121 --codespell Use the codespell dictionary for spelling/typos
122 (default:/usr/share/codespell/dictionary.txt)
123 --codespellfile Use this codespell dictionary
124 --typedefsfile Read additional types from this file
125 --color[=WHEN] Use colors 'always', 'never', or only when output
126 is a terminal ('auto'). Default is 'auto'.
127 --u-boot Run additional checks for U-Boot
128 -h, --help, --version display this help and exit
130 When FILE is - read standard input.
138 return grep { !$seen{$_}++ } @_;
148 open(my $script, '<', abs_path($P)) or
149 die "$P: Can't read '$P' $!\n";
151 my $text = <$script>;
155 # Also catch when type or level is passed through a variable
156 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
159 @types = sort(uniq(@types));
160 print("#\tMessage type\n\n");
161 foreach my $type (@types) {
162 print(++$count . "\t" . $type . "\n");
168 my $conf = which_conf($configuration_file);
171 open(my $conffile, '<', "$conf")
172 or warn "$P: Can't find a readable $configuration_file file $!\n";
174 while (<$conffile>) {
177 $line =~ s/\s*\n?$//g;
181 next if ($line =~ m/^\s*#/);
182 next if ($line =~ m/^\s*$/);
184 my @words = split(" ", $line);
185 foreach my $word (@words) {
186 last if ($word =~ m/^#/);
187 push (@conf_args, $word);
191 unshift(@ARGV, @conf_args) if @conf_args;
194 # Perl's Getopt::Long allows options to take optional arguments after a space.
195 # Prevent --color by itself from consuming other arguments
197 if ($_ eq "--color" || $_ eq "-color") {
198 $_ = "--color=$color";
203 'q|quiet+' => \$quiet,
205 'signoff!' => \$chk_signoff,
206 'patch!' => \$chk_patch,
209 'showfile!' => \$showfile,
212 'subjective!' => \$check,
213 'strict!' => \$check,
214 'ignore=s' => \@ignore,
216 'show-types!' => \$show_types,
217 'list-types!' => \$list_types,
218 'max-line-length=i' => \$max_line_length,
219 'min-conf-desc-length=i' => \$min_conf_desc_length,
221 'summary!' => \$summary,
222 'mailback!' => \$mailback,
223 'summary-file!' => \$summary_file,
225 'fix-inplace!' => \$fix_inplace,
226 'ignore-perl-version!' => \$ignore_perl_version,
227 'debug=s' => \%debug,
228 'test-only=s' => \$tst_only,
229 'codespell!' => \$codespell,
230 'codespellfile=s' => \$codespellfile,
231 'typedefsfile=s' => \$typedefsfile,
232 'u-boot' => \$u_boot,
233 'color=s' => \$color,
234 'no-color' => \$color, #keep old behaviors of -nocolor
235 'nocolor' => \$color, #keep old behaviors of -nocolor
242 list_types(0) if ($list_types);
244 $fix = 1 if ($fix_inplace);
245 $check_orig = $check;
249 my $perl_version_ok = 1;
250 if ($^V && $^V lt $minimum_perl_version) {
251 $perl_version_ok = 0;
252 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
253 exit(1) if (!$ignore_perl_version);
256 #if no filenames are given, push '-' to read patch from stdin
261 if ($color =~ /^[01]$/) {
263 } elsif ($color =~ /^always$/i) {
265 } elsif ($color =~ /^never$/i) {
267 } elsif ($color =~ /^auto$/i) {
268 $color = (-t STDOUT);
270 die "Invalid color mode: $color\n";
273 sub hash_save_array_words {
274 my ($hashRef, $arrayRef) = @_;
276 my @array = split(/,/, join(',', @$arrayRef));
277 foreach my $word (@array) {
278 $word =~ s/\s*\n?$//g;
281 $word =~ tr/[a-z]/[A-Z]/;
283 next if ($word =~ m/^\s*#/);
284 next if ($word =~ m/^\s*$/);
290 sub hash_show_words {
291 my ($hashRef, $prefix) = @_;
293 if (keys %$hashRef) {
294 print "\nNOTE: $prefix message types:";
295 foreach my $word (sort keys %$hashRef) {
302 hash_save_array_words(\%ignore_type, \@ignore);
303 hash_save_array_words(\%use_type, \@use);
306 my $dbg_possible = 0;
309 for my $key (keys %debug) {
311 eval "\${dbg_$key} = '$debug{$key}';";
315 my $rpt_cleaners = 0;
324 if (!top_of_kernel_tree($root)) {
325 die "$P: $root: --root does not point at a valid tree\n";
328 if (top_of_kernel_tree('.')) {
330 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
331 top_of_kernel_tree($1)) {
336 if (!defined $root) {
337 print "Must be run from the top-level dir. of a kernel tree\n";
342 my $emitted_corrupt = 0;
345 [A-Za-z_][A-Za-z\d_]*
346 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
348 our $Storage = qr{extern|static|asmlinkage};
362 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
363 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
364 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
365 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
366 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
368 # Notes to $Attribute:
369 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
391 ____cacheline_aligned|
392 ____cacheline_aligned_in_smp|
393 ____cacheline_internodealigned_in_smp|
397 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
398 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
399 our $Lval = qr{$Ident(?:$Member)*};
401 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
402 our $Binary = qr{(?i)0b[01]+$Int_type?};
403 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
404 our $Int = qr{[0-9]+$Int_type?};
405 our $Octal = qr{0[0-7]+$Int_type?};
406 our $String = qr{"[X\t]*"};
407 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
408 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
409 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
410 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
411 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
412 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
413 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
414 our $Arithmetic = qr{\+|-|\*|\/|%};
418 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
421 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
425 our $NonptrTypeMisordered;
426 our $NonptrTypeWithAttr;
430 our $DeclareMisordered;
432 our $NON_ASCII_UTF8 = qr{
433 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
434 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
435 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
436 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
437 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
438 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
439 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
443 [\x09\x0A\x0D\x20-\x7E] # ASCII
447 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
448 our $typeOtherOSTypedefs = qr{(?x:
449 u_(?:char|short|int|long) | # bsd
450 u(?:nchar|short|int|long) # sysv
452 our $typeKernelTypedefs = qr{(?x:
453 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
456 our $typeTypedefs = qr{(?x:
458 $typeOtherOSTypedefs\b|
459 $typeKernelTypedefs\b
462 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
464 our $logFunctions = qr{(?x:
465 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
466 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
468 WARN(?:_RATELIMIT|_ONCE|)|
473 seq_vprintf|seq_printf|seq_puts
476 our $signature_tags = qr{(?xi:
487 our @typeListMisordered = (
488 qr{char\s+(?:un)?signed},
489 qr{int\s+(?:(?:un)?signed\s+)?short\s},
490 qr{int\s+short(?:\s+(?:un)?signed)},
491 qr{short\s+int(?:\s+(?:un)?signed)},
492 qr{(?:un)?signed\s+int\s+short},
493 qr{short\s+(?:un)?signed},
494 qr{long\s+int\s+(?:un)?signed},
495 qr{int\s+long\s+(?:un)?signed},
496 qr{long\s+(?:un)?signed\s+int},
497 qr{int\s+(?:un)?signed\s+long},
498 qr{int\s+(?:un)?signed},
499 qr{int\s+long\s+long\s+(?:un)?signed},
500 qr{long\s+long\s+int\s+(?:un)?signed},
501 qr{long\s+long\s+(?:un)?signed\s+int},
502 qr{long\s+long\s+(?:un)?signed},
503 qr{long\s+(?:un)?signed},
508 qr{(?:(?:un)?signed\s+)?char},
509 qr{(?:(?:un)?signed\s+)?short\s+int},
510 qr{(?:(?:un)?signed\s+)?short},
511 qr{(?:(?:un)?signed\s+)?int},
512 qr{(?:(?:un)?signed\s+)?long\s+int},
513 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
514 qr{(?:(?:un)?signed\s+)?long\s+long},
515 qr{(?:(?:un)?signed\s+)?long},
524 qr{${Ident}_handler},
525 qr{${Ident}_handler_fn},
529 our $C90_int_types = qr{(?x:
530 long\s+long\s+int\s+(?:un)?signed|
531 long\s+long\s+(?:un)?signed\s+int|
532 long\s+long\s+(?:un)?signed|
533 (?:(?:un)?signed\s+)?long\s+long\s+int|
534 (?:(?:un)?signed\s+)?long\s+long|
535 int\s+long\s+long\s+(?:un)?signed|
536 int\s+(?:(?:un)?signed\s+)?long\s+long|
538 long\s+int\s+(?:un)?signed|
539 long\s+(?:un)?signed\s+int|
540 long\s+(?:un)?signed|
541 (?:(?:un)?signed\s+)?long\s+int|
542 (?:(?:un)?signed\s+)?long|
543 int\s+long\s+(?:un)?signed|
544 int\s+(?:(?:un)?signed\s+)?long|
547 (?:(?:un)?signed\s+)?int
550 our @typeListFile = ();
551 our @typeListWithAttr = (
553 qr{struct\s+$InitAttribute\s+$Ident},
554 qr{union\s+$InitAttribute\s+$Ident},
557 our @modifierList = (
560 our @modifierListFile = ();
562 our @mode_permission_funcs = (
564 ["module_param_(?:array|named|string)", 4],
565 ["module_param_array_named", 5],
566 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
567 ["proc_create(?:_data|)", 2],
568 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
569 ["IIO_DEV_ATTR_[A-Z_]+", 1],
570 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
571 ["SENSOR_TEMPLATE(?:_2|)", 3],
575 #Create a search pattern for all these functions to speed up a loop below
576 our $mode_perms_search = "";
577 foreach my $entry (@mode_permission_funcs) {
578 $mode_perms_search .= '|' if ($mode_perms_search ne "");
579 $mode_perms_search .= $entry->[0];
581 $mode_perms_search = "(?:${mode_perms_search})";
583 our $mode_perms_world_writable = qr{
591 our %mode_permission_string_types = (
610 #Create a search pattern for all these strings to speed up a loop below
611 our $mode_perms_string_search = "";
612 foreach my $entry (keys %mode_permission_string_types) {
613 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
614 $mode_perms_string_search .= $entry;
616 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
617 our $multi_mode_perms_string_search = qr{
618 ${single_mode_perms_string_search}
619 (?:\s*\|\s*${single_mode_perms_string_search})*
625 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
632 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
633 $curpos = pos($string);
636 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
638 $to |= $mode_permission_string_types{$match};
639 $val .= '\s*\|\s*' if ($val ne "");
643 $oval =~ s/^\s*\|\s*//;
644 $oval =~ s/\s*\|\s*$//;
645 return sprintf("%04o", $to);
648 our $allowed_asm_includes = qr{(?x:
654 # memory.h: ARM has a custom one
656 # Load common spelling mistakes and build regular expression list.
660 if (open(my $spelling, '<', $spelling_file)) {
661 while (<$spelling>) {
664 $line =~ s/\s*\n?$//g;
667 next if ($line =~ m/^\s*#/);
668 next if ($line =~ m/^\s*$/);
670 my ($suspect, $fix) = split(/\|\|/, $line);
672 $spelling_fix{$suspect} = $fix;
676 warn "No typos will be found - file '$spelling_file': $!\n";
680 if (open(my $spelling, '<', $codespellfile)) {
681 while (<$spelling>) {
684 $line =~ s/\s*\n?$//g;
687 next if ($line =~ m/^\s*#/);
688 next if ($line =~ m/^\s*$/);
689 next if ($line =~ m/, disabled/i);
693 my ($suspect, $fix) = split(/->/, $line);
695 $spelling_fix{$suspect} = $fix;
699 warn "No codespell typos will be found - file '$codespellfile': $!\n";
703 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
706 my ($wordsRef, $file) = @_;
708 if (open(my $words, '<', $file)) {
712 $line =~ s/\s*\n?$//g;
715 next if ($line =~ m/^\s*#/);
716 next if ($line =~ m/^\s*$/);
718 print("$file: '$line' invalid - ignored\n");
722 $$wordsRef .= '|' if ($$wordsRef ne "");
732 my $const_structs = "";
733 read_words(\$const_structs, $conststructsfile)
734 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
736 my $typeOtherTypedefs = "";
737 if (length($typedefsfile)) {
738 read_words(\$typeOtherTypedefs, $typedefsfile)
739 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
741 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
744 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
745 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
746 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
747 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
748 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
754 (?:$Modifier\s+|const\s+)*
756 (?:typeof|__typeof__)\s*\([^\)]*\)|
760 (?:\s+$Modifier|\s+const)*
762 $NonptrTypeMisordered = qr{
763 (?:$Modifier\s+|const\s+)*
767 (?:\s+$Modifier|\s+const)*
769 $NonptrTypeWithAttr = qr{
770 (?:$Modifier\s+|const\s+)*
772 (?:typeof|__typeof__)\s*\([^\)]*\)|
776 (?:\s+$Modifier|\s+const)*
780 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
781 (?:\s+$Inline|\s+$Modifier)*
783 $TypeMisordered = qr{
784 $NonptrTypeMisordered
785 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
786 (?:\s+$Inline|\s+$Modifier)*
788 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
789 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
793 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
795 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
796 # requires at least perl version v5.10.0
797 # Any use must be runtime checked with $^V
799 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
800 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
801 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
803 our $declaration_macros = qr{(?x:
804 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
805 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
806 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
807 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
812 return "" if (!defined($string));
814 while ($string =~ /^\s*\(.*\)\s*$/) {
815 $string =~ s@^\s*\(\s*@@;
816 $string =~ s@\s*\)\s*$@@;
819 $string =~ s@\s+@ @g;
824 sub seed_camelcase_file {
827 return if (!(-f $file));
831 open(my $include_file, '<', "$file")
832 or warn "$P: Can't read '$file' $!\n";
833 my $text = <$include_file>;
834 close($include_file);
836 my @lines = split('\n', $text);
838 foreach my $line (@lines) {
839 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
840 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
842 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
844 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
850 sub is_maintained_obsolete {
853 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
855 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
857 return $status =~ /obsolete/i;
860 sub is_SPDX_License_valid {
863 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
865 my $root_path = abs_path($root);
866 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
867 return 0 if ($status ne "");
871 my $camelcase_seeded = 0;
872 sub seed_camelcase_includes {
873 return if ($camelcase_seeded);
876 my $camelcase_cache = "";
877 my @include_files = ();
879 $camelcase_seeded = 1;
882 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
883 chomp $git_last_include_commit;
884 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
886 my $last_mod_date = 0;
887 $files = `find $root/include -name "*.h"`;
888 @include_files = split('\n', $files);
889 foreach my $file (@include_files) {
890 my $date = POSIX::strftime("%Y%m%d%H%M",
891 localtime((stat $file)[9]));
892 $last_mod_date = $date if ($last_mod_date < $date);
894 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
897 if ($camelcase_cache ne "" && -f $camelcase_cache) {
898 open(my $camelcase_file, '<', "$camelcase_cache")
899 or warn "$P: Can't read '$camelcase_cache' $!\n";
900 while (<$camelcase_file>) {
904 close($camelcase_file);
910 $files = `git ls-files "include/*.h"`;
911 @include_files = split('\n', $files);
914 foreach my $file (@include_files) {
915 seed_camelcase_file($file);
918 if ($camelcase_cache ne "") {
919 unlink glob ".checkpatch-camelcase.*";
920 open(my $camelcase_file, '>', "$camelcase_cache")
921 or warn "$P: Can't write '$camelcase_cache' $!\n";
922 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
923 print $camelcase_file ("$_\n");
925 close($camelcase_file);
929 sub git_commit_info {
930 my ($commit, $id, $desc) = @_;
932 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
934 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
935 $output =~ s/^\s*//gm;
936 my @lines = split("\n", $output);
938 return ($id, $desc) if ($#lines < 0);
940 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
941 # Maybe one day convert this block of bash into something that returns
942 # all matching commit ids, but it's very slow...
944 # echo "checking commits $1..."
945 # git rev-list --remotes | grep -i "^$1" |
946 # while read line ; do
947 # git log --format='%H %s' -1 $line |
948 # echo "commit $(cut -c 1-12,41-)"
950 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
953 $id = substr($lines[0], 0, 12);
954 $desc = substr($lines[0], 41);
960 $chk_signoff = 0 if ($file);
965 my @fixed_inserted = ();
966 my @fixed_deleted = ();
969 # If input is git commits, extract all commits from the commit expressions.
970 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
971 die "$P: No git repository found\n" if ($git && !-e ".git");
975 foreach my $commit_expr (@ARGV) {
977 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
978 $git_range = "-$2 $1";
979 } elsif ($commit_expr =~ m/\.\./) {
980 $git_range = "$commit_expr";
982 $git_range = "-1 $commit_expr";
984 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
985 foreach my $line (split(/\n/, $lines)) {
986 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
987 next if (!defined($1) || !defined($2));
990 unshift(@commits, $sha1);
991 $git_commits{$sha1} = $subject;
994 die "$P: no git commits after extraction!\n" if (@commits == 0);
999 for my $filename (@ARGV) {
1002 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1003 die "$P: $filename: git format-patch failed - $!\n";
1005 open($FILE, '-|', "diff -u /dev/null $filename") ||
1006 die "$P: $filename: diff failed - $!\n";
1007 } elsif ($filename eq '-') {
1008 open($FILE, '<&STDIN');
1010 open($FILE, '<', "$filename") ||
1011 die "$P: $filename: open failed - $!\n";
1013 if ($filename eq '-') {
1014 $vname = 'Your patch';
1016 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1022 push(@rawlines, $_);
1026 if ($#ARGV > 0 && $quiet == 0) {
1027 print '-' x length($vname) . "\n";
1029 print '-' x length($vname) . "\n";
1032 if (!process($filename)) {
1038 @fixed_inserted = ();
1039 @fixed_deleted = ();
1041 @modifierListFile = ();
1047 hash_show_words(\%use_type, "Used");
1048 hash_show_words(\%ignore_type, "Ignored");
1050 if (!$perl_version_ok) {
1053 NOTE: perl $^V is not modern enough to detect all possible issues.
1054 An upgrade to at least perl $minimum_perl_version is suggested.
1060 NOTE: If any of the errors are false positives, please report
1061 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1068 sub top_of_kernel_tree {
1072 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1073 "README", "Documentation", "arch", "include", "drivers",
1074 "fs", "init", "ipc", "kernel", "lib", "scripts",
1077 foreach my $check (@tree_check) {
1078 if (! -e $root . '/' . $check) {
1086 my ($formatted_email) = @_;
1092 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1095 $comment = $3 if defined $3;
1096 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1098 $comment = $2 if defined $2;
1099 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1101 $comment = $2 if defined $2;
1102 $formatted_email =~ s/\Q$address\E.*$//;
1103 $name = $formatted_email;
1104 $name = trim($name);
1105 $name =~ s/^\"|\"$//g;
1106 # If there's a name left after stripping spaces and
1107 # leading quotes, and the address doesn't have both
1108 # leading and trailing angle brackets, the address
1110 # "joe smith joe@smith.com" bad
1111 # "joe smith <joe@smith.com" bad
1112 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1119 $name = trim($name);
1120 $name =~ s/^\"|\"$//g;
1121 $address = trim($address);
1122 $address =~ s/^\<|\>$//g;
1124 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1125 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1126 $name = "\"$name\"";
1129 return ($name, $address, $comment);
1133 my ($name, $address) = @_;
1135 my $formatted_email;
1137 $name = trim($name);
1138 $name =~ s/^\"|\"$//g;
1139 $address = trim($address);
1141 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1142 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1143 $name = "\"$name\"";
1146 if ("$name" eq "") {
1147 $formatted_email = "$address";
1149 $formatted_email = "$name <$address>";
1152 return $formatted_email;
1158 foreach my $path (split(/:/, $ENV{PATH})) {
1159 if (-e "$path/$bin") {
1160 return "$path/$bin";
1170 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1171 if (-e "$path/$conf") {
1172 return "$path/$conf";
1184 for my $c (split(//, $str)) {
1188 for (; ($n % 8) != 0; $n++) {
1200 (my $res = shift) =~ tr/\t/ /c;
1207 # Drop the diff line leader and expand tabs
1209 $line = expand_tabs($line);
1211 # Pick the indent from the front of the line.
1212 my ($white) = ($line =~ /^(\s*)/);
1214 return (length($line), length($white));
1217 my $sanitise_quote = '';
1219 sub sanitise_line_reset {
1220 my ($in_comment) = @_;
1223 $sanitise_quote = '*/';
1225 $sanitise_quote = '';
1238 # Always copy over the diff marker.
1239 $res = substr($line, 0, 1);
1241 for ($off = 1; $off < length($line); $off++) {
1242 $c = substr($line, $off, 1);
1244 # Comments we are whacking completely including the begin
1245 # and end, all to $;.
1246 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1247 $sanitise_quote = '*/';
1249 substr($res, $off, 2, "$;$;");
1253 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1254 $sanitise_quote = '';
1255 substr($res, $off, 2, "$;$;");
1259 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1260 $sanitise_quote = '//';
1262 substr($res, $off, 2, $sanitise_quote);
1267 # A \ in a string means ignore the next character.
1268 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1270 substr($res, $off, 2, 'XX');
1275 if ($c eq "'" || $c eq '"') {
1276 if ($sanitise_quote eq '') {
1277 $sanitise_quote = $c;
1279 substr($res, $off, 1, $c);
1281 } elsif ($sanitise_quote eq $c) {
1282 $sanitise_quote = '';
1286 #print "c<$c> SQ<$sanitise_quote>\n";
1287 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1288 substr($res, $off, 1, $;);
1289 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1290 substr($res, $off, 1, $;);
1291 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1292 substr($res, $off, 1, 'X');
1294 substr($res, $off, 1, $c);
1298 if ($sanitise_quote eq '//') {
1299 $sanitise_quote = '';
1302 # The pathname on a #include may be surrounded by '<' and '>'.
1303 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1304 my $clean = 'X' x length($1);
1305 $res =~ s@\<.*\>@<$clean>@;
1307 # The whole of a #error is a string.
1308 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1309 my $clean = 'X' x length($1);
1310 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1313 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1315 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1321 sub get_quoted_string {
1322 my ($line, $rawline) = @_;
1324 return "" if (!defined($line) || !defined($rawline));
1325 return "" if ($line !~ m/($String)/g);
1326 return substr($rawline, $-[0], $+[0] - $-[0]);
1329 sub ctx_statement_block {
1330 my ($linenr, $remain, $off) = @_;
1331 my $line = $linenr - 1;
1334 my $coff = $off - 1;
1348 @stack = (['', 0]) if ($#stack == -1);
1350 #warn "CSB: blk<$blk> remain<$remain>\n";
1351 # If we are about to drop off the end, pull in more
1354 for (; $remain > 0; $line++) {
1355 last if (!defined $lines[$line]);
1356 next if ($lines[$line] =~ /^-/);
1359 $blk .= $lines[$line] . "\n";
1360 $len = length($blk);
1364 # Bail if there is no further context.
1365 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1369 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1375 $c = substr($blk, $off, 1);
1376 $remainder = substr($blk, $off);
1378 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1380 # Handle nested #if/#else.
1381 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1382 push(@stack, [ $type, $level ]);
1383 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1384 ($type, $level) = @{$stack[$#stack - 1]};
1385 } elsif ($remainder =~ /^#\s*endif\b/) {
1386 ($type, $level) = @{pop(@stack)};
1389 # Statement ends at the ';' or a close '}' at the
1391 if ($level == 0 && $c eq ';') {
1395 # An else is really a conditional as long as its not else if
1396 if ($level == 0 && $coff_set == 0 &&
1397 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1398 $remainder =~ /^(else)(?:\s|{)/ &&
1399 $remainder !~ /^else\s+if\b/) {
1400 $coff = $off + length($1) - 1;
1402 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1403 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1406 if (($type eq '' || $type eq '(') && $c eq '(') {
1410 if ($type eq '(' && $c eq ')') {
1412 $type = ($level != 0)? '(' : '';
1414 if ($level == 0 && $coff < $soff) {
1417 #warn "CSB: mark coff<$coff>\n";
1420 if (($type eq '' || $type eq '{') && $c eq '{') {
1424 if ($type eq '{' && $c eq '}') {
1426 $type = ($level != 0)? '{' : '';
1429 if (substr($blk, $off + 1, 1) eq ';') {
1435 # Preprocessor commands end at the newline unless escaped.
1436 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1444 # We are truly at the end, so shuffle to the next line.
1451 my $statement = substr($blk, $soff, $off - $soff + 1);
1452 my $condition = substr($blk, $soff, $coff - $soff + 1);
1454 #warn "STATEMENT<$statement>\n";
1455 #warn "CONDITION<$condition>\n";
1457 #print "coff<$coff> soff<$off> loff<$loff>\n";
1459 return ($statement, $condition,
1460 $line, $remain + 1, $off - $loff + 1, $level);
1463 sub statement_lines {
1466 # Strip the diff line prefixes and rip blank lines at start and end.
1467 $stmt =~ s/(^|\n)./$1/g;
1471 my @stmt_lines = ($stmt =~ /\n/g);
1473 return $#stmt_lines + 2;
1476 sub statement_rawlines {
1479 my @stmt_lines = ($stmt =~ /\n/g);
1481 return $#stmt_lines + 2;
1484 sub statement_block_size {
1487 $stmt =~ s/(^|\n)./$1/g;
1493 my @stmt_lines = ($stmt =~ /\n/g);
1494 my @stmt_statements = ($stmt =~ /;/g);
1496 my $stmt_lines = $#stmt_lines + 2;
1497 my $stmt_statements = $#stmt_statements + 1;
1499 if ($stmt_lines > $stmt_statements) {
1502 return $stmt_statements;
1506 sub ctx_statement_full {
1507 my ($linenr, $remain, $off) = @_;
1508 my ($statement, $condition, $level);
1512 # Grab the first conditional/block pair.
1513 ($statement, $condition, $linenr, $remain, $off, $level) =
1514 ctx_statement_block($linenr, $remain, $off);
1515 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1516 push(@chunks, [ $condition, $statement ]);
1517 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1518 return ($level, $linenr, @chunks);
1521 # Pull in the following conditional/block pairs and see if they
1522 # could continue the statement.
1524 ($statement, $condition, $linenr, $remain, $off, $level) =
1525 ctx_statement_block($linenr, $remain, $off);
1526 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1527 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1529 push(@chunks, [ $condition, $statement ]);
1532 return ($level, $linenr, @chunks);
1536 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1538 my $start = $linenr - 1;
1545 my @stack = ($level);
1546 for ($line = $start; $remain > 0; $line++) {
1547 next if ($rawlines[$line] =~ /^-/);
1550 $blk .= $rawlines[$line];
1552 # Handle nested #if/#else.
1553 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1554 push(@stack, $level);
1555 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1556 $level = $stack[$#stack - 1];
1557 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1558 $level = pop(@stack);
1561 foreach my $c (split(//, $lines[$line])) {
1562 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1568 if ($c eq $close && $level > 0) {
1570 last if ($level == 0);
1571 } elsif ($c eq $open) {
1576 if (!$outer || $level <= 1) {
1577 push(@res, $rawlines[$line]);
1580 last if ($level == 0);
1583 return ($level, @res);
1585 sub ctx_block_outer {
1586 my ($linenr, $remain) = @_;
1588 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1592 my ($linenr, $remain) = @_;
1594 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1598 my ($linenr, $remain, $off) = @_;
1600 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1603 sub ctx_block_level {
1604 my ($linenr, $remain) = @_;
1606 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1608 sub ctx_statement_level {
1609 my ($linenr, $remain, $off) = @_;
1611 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1614 sub ctx_locate_comment {
1615 my ($first_line, $end_line) = @_;
1617 # Catch a comment on the end of the line itself.
1618 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1619 return $current_comment if (defined $current_comment);
1621 # Look through the context and try and figure out if there is a
1624 $current_comment = '';
1625 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1626 my $line = $rawlines[$linenr - 1];
1628 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1631 if ($line =~ m@/\*@) {
1634 if (!$in_comment && $current_comment ne '') {
1635 $current_comment = '';
1637 $current_comment .= $line . "\n" if ($in_comment);
1638 if ($line =~ m@\*/@) {
1643 chomp($current_comment);
1644 return($current_comment);
1646 sub ctx_has_comment {
1647 my ($first_line, $end_line) = @_;
1648 my $cmt = ctx_locate_comment($first_line, $end_line);
1650 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1651 ##print "CMMT: $cmt\n";
1653 return ($cmt ne '');
1657 my ($linenr, $cnt) = @_;
1659 my $offset = $linenr - 1;
1664 $line = $rawlines[$offset++];
1665 next if (defined($line) && $line =~ /^-/);
1673 my ($linenr, $lc) = @_;
1675 my $stat_real = raw_line($linenr, 0);
1676 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1677 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1684 my ($linenr, $cnt, $here) = @_;
1686 my $herectx = $here . "\n";
1687 for (my $n = 0; $n < $cnt; $n++) {
1688 $herectx .= raw_line($linenr, $n) . "\n";
1699 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1702 $coded = sprintf("^%c", unpack('C', $2) + 64);
1711 my $av_preprocessor = 0;
1716 sub annotate_reset {
1717 $av_preprocessor = 0;
1719 @av_paren_type = ('E');
1720 $av_pend_colon = 'O';
1723 sub annotate_values {
1724 my ($stream, $type) = @_;
1727 my $var = '_' x length($stream);
1730 print "$stream\n" if ($dbg_values > 1);
1732 while (length($cur)) {
1733 @av_paren_type = ('E') if ($#av_paren_type < 0);
1734 print " <" . join('', @av_paren_type) .
1735 "> <$type> <$av_pending>" if ($dbg_values > 1);
1736 if ($cur =~ /^(\s+)/o) {
1737 print "WS($1)\n" if ($dbg_values > 1);
1738 if ($1 =~ /\n/ && $av_preprocessor) {
1739 $type = pop(@av_paren_type);
1740 $av_preprocessor = 0;
1743 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1744 print "CAST($1)\n" if ($dbg_values > 1);
1745 push(@av_paren_type, $type);
1748 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1749 print "DECLARE($1)\n" if ($dbg_values > 1);
1752 } elsif ($cur =~ /^($Modifier)\s*/) {
1753 print "MODIFIER($1)\n" if ($dbg_values > 1);
1756 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1757 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1758 $av_preprocessor = 1;
1759 push(@av_paren_type, $type);
1765 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1766 print "UNDEF($1)\n" if ($dbg_values > 1);
1767 $av_preprocessor = 1;
1768 push(@av_paren_type, $type);
1770 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1771 print "PRE_START($1)\n" if ($dbg_values > 1);
1772 $av_preprocessor = 1;
1774 push(@av_paren_type, $type);
1775 push(@av_paren_type, $type);
1778 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1779 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1780 $av_preprocessor = 1;
1782 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1786 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1787 print "PRE_END($1)\n" if ($dbg_values > 1);
1789 $av_preprocessor = 1;
1791 # Assume all arms of the conditional end as this
1792 # one does, and continue as if the #endif was not here.
1793 pop(@av_paren_type);
1794 push(@av_paren_type, $type);
1797 } elsif ($cur =~ /^(\\\n)/o) {
1798 print "PRECONT($1)\n" if ($dbg_values > 1);
1800 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1801 print "ATTR($1)\n" if ($dbg_values > 1);
1802 $av_pending = $type;
1805 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1806 print "SIZEOF($1)\n" if ($dbg_values > 1);
1812 } elsif ($cur =~ /^(if|while|for)\b/o) {
1813 print "COND($1)\n" if ($dbg_values > 1);
1817 } elsif ($cur =~/^(case)/o) {
1818 print "CASE($1)\n" if ($dbg_values > 1);
1819 $av_pend_colon = 'C';
1822 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1823 print "KEYWORD($1)\n" if ($dbg_values > 1);
1826 } elsif ($cur =~ /^(\()/o) {
1827 print "PAREN('$1')\n" if ($dbg_values > 1);
1828 push(@av_paren_type, $av_pending);
1832 } elsif ($cur =~ /^(\))/o) {
1833 my $new_type = pop(@av_paren_type);
1834 if ($new_type ne '_') {
1836 print "PAREN('$1') -> $type\n"
1837 if ($dbg_values > 1);
1839 print "PAREN('$1')\n" if ($dbg_values > 1);
1842 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1843 print "FUNC($1)\n" if ($dbg_values > 1);
1847 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1848 if (defined $2 && $type eq 'C' || $type eq 'T') {
1849 $av_pend_colon = 'B';
1850 } elsif ($type eq 'E') {
1851 $av_pend_colon = 'L';
1853 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1856 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1857 print "IDENT($1)\n" if ($dbg_values > 1);
1860 } elsif ($cur =~ /^($Assignment)/o) {
1861 print "ASSIGN($1)\n" if ($dbg_values > 1);
1864 } elsif ($cur =~/^(;|{|})/) {
1865 print "END($1)\n" if ($dbg_values > 1);
1867 $av_pend_colon = 'O';
1869 } elsif ($cur =~/^(,)/) {
1870 print "COMMA($1)\n" if ($dbg_values > 1);
1873 } elsif ($cur =~ /^(\?)/o) {
1874 print "QUESTION($1)\n" if ($dbg_values > 1);
1877 } elsif ($cur =~ /^(:)/o) {
1878 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1880 substr($var, length($res), 1, $av_pend_colon);
1881 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1886 $av_pend_colon = 'O';
1888 } elsif ($cur =~ /^(\[)/o) {
1889 print "CLOSE($1)\n" if ($dbg_values > 1);
1892 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1895 print "OPV($1)\n" if ($dbg_values > 1);
1902 substr($var, length($res), 1, $variant);
1905 } elsif ($cur =~ /^($Operators)/o) {
1906 print "OP($1)\n" if ($dbg_values > 1);
1907 if ($1 ne '++' && $1 ne '--') {
1911 } elsif ($cur =~ /(^.)/o) {
1912 print "C($1)\n" if ($dbg_values > 1);
1915 $cur = substr($cur, length($1));
1916 $res .= $type x length($1);
1920 return ($res, $var);
1924 my ($possible, $line) = @_;
1925 my $notPermitted = qr{(?:
1942 ^(?:typedef|struct|enum)\b
1944 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1945 if ($possible !~ $notPermitted) {
1946 # Check for modifiers.
1947 $possible =~ s/\s*$Storage\s*//g;
1948 $possible =~ s/\s*$Sparse\s*//g;
1949 if ($possible =~ /^\s*$/) {
1951 } elsif ($possible =~ /\s/) {
1952 $possible =~ s/\s*$Type\s*//g;
1953 for my $modifier (split(' ', $possible)) {
1954 if ($modifier !~ $notPermitted) {
1955 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1956 push(@modifierListFile, $modifier);
1961 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1962 push(@typeListFile, $possible);
1966 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1975 $type =~ tr/[a-z]/[A-Z]/;
1977 return defined $use_type{$type} if (scalar keys %use_type > 0);
1979 return !defined $ignore_type{$type};
1983 my ($level, $type, $msg) = @_;
1985 if (!show_type($type) ||
1986 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1991 if ($level eq 'ERROR') {
1993 } elsif ($level eq 'WARNING') {
1999 $output .= $prefix . $level . ':';
2001 $output .= BLUE if ($color);
2002 $output .= "$type:";
2004 $output .= RESET if ($color);
2005 $output .= ' ' . $msg . "\n";
2008 my @lines = split("\n", $output, -1);
2009 splice(@lines, 1, 1);
2010 $output = join("\n", @lines);
2012 $output = (split('\n', $output))[0] . "\n" if ($terse);
2014 push(our @report, $output);
2023 sub fixup_current_range {
2024 my ($lineRef, $offset, $length) = @_;
2026 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2029 my $no = $o + $offset;
2030 my $nl = $l + $length;
2031 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2035 sub fix_inserted_deleted_lines {
2036 my ($linesRef, $insertedRef, $deletedRef) = @_;
2038 my $range_last_linenr = 0;
2039 my $delta_offset = 0;
2044 my $next_insert = 0;
2045 my $next_delete = 0;
2049 my $inserted = @{$insertedRef}[$next_insert++];
2050 my $deleted = @{$deletedRef}[$next_delete++];
2052 foreach my $old_line (@{$linesRef}) {
2054 my $line = $old_line; #don't modify the array
2055 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2057 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2058 $range_last_linenr = $new_linenr;
2059 fixup_current_range(\$line, $delta_offset, 0);
2062 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2063 $deleted = @{$deletedRef}[$next_delete++];
2065 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2068 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2069 push(@lines, ${$inserted}{'LINE'});
2070 $inserted = @{$insertedRef}[$next_insert++];
2072 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2076 push(@lines, $line);
2086 sub fix_insert_line {
2087 my ($linenr, $line) = @_;
2093 push(@fixed_inserted, $inserted);
2096 sub fix_delete_line {
2097 my ($linenr, $line) = @_;
2104 push(@fixed_deleted, $deleted);
2108 my ($type, $msg) = @_;
2110 if (report("ERROR", $type, $msg)) {
2118 my ($type, $msg) = @_;
2120 if (report("WARNING", $type, $msg)) {
2128 my ($type, $msg) = @_;
2130 if ($check && report("CHECK", $type, $msg)) {
2138 sub check_absolute_file {
2139 my ($absolute, $herecurr) = @_;
2140 my $file = $absolute;
2142 ##print "absolute<$absolute>\n";
2144 # See if any suffix of this path is a path within the tree.
2145 while ($file =~ s@^[^/]*/@@) {
2146 if (-f "$root/$file") {
2147 ##print "file<$file>\n";
2155 # It is, so see if the prefix is acceptable.
2156 my $prefix = $absolute;
2157 substr($prefix, -length($file)) = '';
2159 ##print "prefix<$prefix>\n";
2160 if ($prefix ne ".../") {
2161 WARN("USE_RELATIVE_PATH",
2162 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2169 $string =~ s/^\s+|\s+$//g;
2177 $string =~ s/^\s+//;
2185 $string =~ s/\s+$//;
2190 sub string_find_replace {
2191 my ($string, $find, $replace) = @_;
2193 $string =~ s/$find/$replace/g;
2201 my $source_indent = 8;
2202 my $max_spaces_before_tab = $source_indent - 1;
2203 my $spaces_to_tab = " " x $source_indent;
2205 #convert leading spaces to tabs
2206 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2207 #Remove spaces before a tab
2208 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2213 sub pos_last_openparen {
2218 my $opens = $line =~ tr/\(/\(/;
2219 my $closes = $line =~ tr/\)/\)/;
2221 my $last_openparen = 0;
2223 if (($opens == 0) || ($closes >= $opens)) {
2227 my $len = length($line);
2229 for ($pos = 0; $pos < $len; $pos++) {
2230 my $string = substr($line, $pos);
2231 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2232 $pos += length($1) - 1;
2233 } elsif (substr($line, $pos, 1) eq '(') {
2234 $last_openparen = $pos;
2235 } elsif (index($string, '(') == -1) {
2240 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2243 # Checks specific to U-Boot
2245 my ($realfile, $line, $herecurr) = @_;
2247 # ask for a test if a new uclass ID is added
2248 if ($realfile =~ /uclass-id.h/ && $line =~ /^\+/) {
2250 "Possible new uclass - make sure to add a sandbox driver, plus a test in test/dm/<name>.c\n" . $herecurr);
2253 # try to get people to use the livetree API
2254 if ($line =~ /^\+.*fdtdec_/) {
2256 "Use the livetree API (dev_read_...)\n" . $herecurr);
2259 # add tests for new commands
2260 if ($line =~ /^\+.*do_($Ident)\(struct cmd_tbl.*/) {
2262 "Possible new command - make sure you add a test\n" . $herecurr);
2265 # use if instead of #if
2266 if ($line =~ /^\+#if.*CONFIG.*/) {
2268 "Use 'if (IS_ENABLED(CONFIG...))' instead of '#if or #ifdef' where possible\n" . $herecurr);
2273 my $filename = shift;
2279 my $stashrawline="";
2289 my $authorsignoff = 0;
2291 my $is_binding_patch = -1;
2292 my $in_header_lines = $file ? 0 : 1;
2293 my $in_commit_log = 0; #Scanning lines before patch
2294 my $has_commit_log = 0; #Encountered lines before patch
2295 my $commit_log_lines = 0; #Number of commit log lines
2296 my $commit_log_possible_stack_dump = 0;
2297 my $commit_log_long_line = 0;
2298 my $commit_log_has_diff = 0;
2299 my $reported_maintainer_file = 0;
2300 my $non_utf8_charset = 0;
2302 my $last_blank_line = 0;
2303 my $last_coalesced_string_linenr = -1;
2311 # Trace the real file/line as we go.
2316 my $context_function; #undef'd unless there's a known function
2318 my $comment_edge = 0;
2322 my $prev_values = 'E';
2325 my %suppress_ifbraces;
2326 my %suppress_whiletrailers;
2327 my %suppress_export;
2328 my $suppress_statement = 0;
2330 my %signatures = ();
2332 # Pre-scan the patch sanitizing the lines.
2333 # Pre-scan the patch looking for any __setup documentation.
2335 my @setup_docs = ();
2338 my $camelcase_file_seeded = 0;
2340 my $checklicenseline = 1;
2342 sanitise_line_reset();
2344 foreach my $rawline (@rawlines) {
2348 push(@fixed, $rawline) if ($fix);
2350 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2352 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2357 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2366 # Guestimate if this is a continuing comment. Run
2367 # the context looking for a comment "edge". If this
2368 # edge is a close comment then we must be in a comment
2372 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2373 next if (defined $rawlines[$ln - 1] &&
2374 $rawlines[$ln - 1] =~ /^-/);
2376 #print "RAW<$rawlines[$ln - 1]>\n";
2377 last if (!defined $rawlines[$ln - 1]);
2378 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2379 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2384 if (defined $edge && $edge eq '*/') {
2388 # Guestimate if this is a continuing comment. If this
2389 # is the start of a diff block and this line starts
2390 # ' *' then it is very likely a comment.
2391 if (!defined $edge &&
2392 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2397 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2398 sanitise_line_reset($in_comment);
2400 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2401 # Standardise the strings and chars within the input to
2402 # simplify matching -- only bother with positive lines.
2403 $line = sanitise_line($rawline);
2405 push(@lines, $line);
2408 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2413 #print "==>$rawline\n";
2414 #print "-->$line\n";
2416 if ($setup_docs && $line =~ /^\+/) {
2417 push(@setup_docs, $line);
2426 foreach my $line (@lines) {
2429 my $sline = $line; #copy of $line
2430 $sline =~ s/$;/ /g; #with comments as spaces
2432 my $rawline = $rawlines[$linenr - 1];
2434 # check if it's a mode change, rename or start of a patch
2435 if (!$in_commit_log &&
2436 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2437 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2438 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2442 #extract the line range in the file after the patch is applied
2443 if (!$in_commit_log &&
2444 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2447 $first_line = $linenr + 1;
2457 %suppress_ifbraces = ();
2458 %suppress_whiletrailers = ();
2459 %suppress_export = ();
2460 $suppress_statement = 0;
2461 if ($context =~ /\b(\w+)\s*\(/) {
2462 $context_function = $1;
2464 undef $context_function;
2468 # track the line number as we move through the hunk, note that
2469 # new versions of GNU diff omit the leading space on completely
2470 # blank context lines so we need to count that too.
2471 } elsif ($line =~ /^( |\+|$)/) {
2473 $realcnt-- if ($realcnt != 0);
2475 # Measure the line length and indent.
2476 ($length, $indent) = line_stats($rawline);
2478 # Track the previous line.
2479 ($prevline, $stashline) = ($stashline, $line);
2480 ($previndent, $stashindent) = ($stashindent, $indent);
2481 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2483 #warn "line<$line>\n";
2485 } elsif ($realcnt == 1) {
2489 my $hunk_line = ($realcnt != 0);
2491 $here = "#$linenr: " if (!$file);
2492 $here = "#$realline: " if ($file);
2495 # extract the filename as it passes
2496 if ($line =~ /^diff --git.*?(\S+)$/) {
2498 $realfile =~ s@^([^/]*)/@@ if (!$file);
2501 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2503 $realfile =~ s@^([^/]*)/@@ if (!$file);
2507 if (!$file && $tree && $p1_prefix ne '' &&
2508 -e "$root/$p1_prefix") {
2509 WARN("PATCH_PREFIX",
2510 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2513 if ($realfile =~ m@^include/asm/@) {
2514 ERROR("MODIFIED_INCLUDE_ASM",
2515 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2520 #make up the handle for any error we report on this line
2522 $prefix = "$realfile:$realline: "
2525 $prefix = "$filename:$realline: ";
2527 $prefix = "$filename:$linenr: ";
2532 if (is_maintained_obsolete($realfile)) {
2534 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2536 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2539 $check = $check_orig;
2541 $checklicenseline = 1;
2543 if ($realfile !~ /^MAINTAINERS/) {
2544 my $last_binding_patch = $is_binding_patch;
2546 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2548 if (($last_binding_patch != -1) &&
2549 ($last_binding_patch ^ $is_binding_patch)) {
2550 WARN("DT_SPLIT_BINDING_PATCH",
2551 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2558 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2560 my $hereline = "$here\n$rawline\n";
2561 my $herecurr = "$here\n$rawline\n";
2562 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2564 $cnt_lines++ if ($realcnt != 0);
2566 # Verify the existence of a commit log if appropriate
2567 # 2 is used because a $signature is counted in $commit_log_lines
2568 if ($in_commit_log) {
2569 if ($line !~ /^\s*$/) {
2570 $commit_log_lines++; #could be a $signature
2572 } elsif ($has_commit_log && $commit_log_lines < 2) {
2573 WARN("COMMIT_MESSAGE",
2574 "Missing commit description - Add an appropriate one\n");
2575 $commit_log_lines = 2; #warn only once
2578 # Check if the commit log has what seems like a diff which can confuse patch
2579 if ($in_commit_log && !$commit_log_has_diff &&
2580 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2581 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2582 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2583 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2584 ERROR("DIFF_IN_COMMIT_MSG",
2585 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2586 $commit_log_has_diff = 1;
2589 # Check for incorrect file permissions
2590 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2591 my $permhere = $here . "FILE: $realfile\n";
2592 if ($realfile !~ m@scripts/@ &&
2593 $realfile !~ /\.(py|pl|awk|sh)$/) {
2594 ERROR("EXECUTE_PERMISSIONS",
2595 "do not set execute permissions for source files\n" . $permhere);
2599 # Check the patch for a From:
2600 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2602 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2606 # Check the patch for a signoff:
2607 if ($line =~ /^\s*signed-off-by:/i) {
2610 if ($author ne '') {
2613 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2619 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2620 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2621 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2622 $reported_maintainer_file = 1;
2625 # Check signature styles
2626 if (!$in_header_lines &&
2627 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2628 my $space_before = $1;
2630 my $space_after = $3;
2632 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2634 if ($sign_off !~ /$signature_tags/) {
2635 WARN("BAD_SIGN_OFF",
2636 "Non-standard signature: $sign_off\n" . $herecurr);
2638 if (defined $space_before && $space_before ne "") {
2639 if (WARN("BAD_SIGN_OFF",
2640 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2642 $fixed[$fixlinenr] =
2643 "$ucfirst_sign_off $email";
2646 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2647 if (WARN("BAD_SIGN_OFF",
2648 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2650 $fixed[$fixlinenr] =
2651 "$ucfirst_sign_off $email";
2655 if (!defined $space_after || $space_after ne " ") {
2656 if (WARN("BAD_SIGN_OFF",
2657 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2659 $fixed[$fixlinenr] =
2660 "$ucfirst_sign_off $email";
2664 my ($email_name, $email_address, $comment) = parse_email($email);
2665 my $suggested_email = format_email(($email_name, $email_address));
2666 if ($suggested_email eq "") {
2667 ERROR("BAD_SIGN_OFF",
2668 "Unrecognized email address: '$email'\n" . $herecurr);
2670 my $dequoted = $suggested_email;
2671 $dequoted =~ s/^"//;
2672 $dequoted =~ s/" </ </;
2673 # Don't force email to have quotes
2674 # Allow just an angle bracketed address
2675 if ("$dequoted$comment" ne $email &&
2676 "<$email_address>$comment" ne $email &&
2677 "$suggested_email$comment" ne $email) {
2678 WARN("BAD_SIGN_OFF",
2679 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2683 # Check for duplicate signatures
2684 my $sig_nospace = $line;
2685 $sig_nospace =~ s/\s//g;
2686 $sig_nospace = lc($sig_nospace);
2687 if (defined $signatures{$sig_nospace}) {
2688 WARN("BAD_SIGN_OFF",
2689 "Duplicate signature\n" . $herecurr);
2691 $signatures{$sig_nospace} = 1;
2695 # Check email subject for common tools that don't need to be mentioned
2696 if ($in_header_lines &&
2697 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2698 WARN("EMAIL_SUBJECT",
2699 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2702 # Check for unwanted Gerrit info
2703 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2704 ERROR("GERRIT_CHANGE_ID",
2705 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2708 # Check if the commit log is in a possible stack dump
2709 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2710 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2711 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2713 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2714 # stack dump address
2715 $commit_log_possible_stack_dump = 1;
2718 # Check for line lengths > 75 in commit log, warn once
2719 if ($in_commit_log && !$commit_log_long_line &&
2720 length($line) > 75 &&
2721 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2722 # file delta changes
2723 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2725 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2726 # A Fixes: or Link: line
2727 $commit_log_possible_stack_dump)) {
2728 WARN("COMMIT_LOG_LONG_LINE",
2729 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2730 $commit_log_long_line = 1;
2733 # Reset possible stack dump if a blank line is found
2734 if ($in_commit_log && $commit_log_possible_stack_dump &&
2736 $commit_log_possible_stack_dump = 0;
2739 # Check for git id commit length and improperly formed commit descriptions
2740 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2741 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2742 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2743 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2744 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2745 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2746 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2747 my $init_char = "c";
2748 my $orig_commit = "";
2755 my $id = '0123456789ab';
2756 my $orig_desc = "commit description";
2757 my $description = "";
2759 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2761 $orig_commit = lc($2);
2762 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2763 $orig_commit = lc($1);
2766 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2767 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2768 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2769 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2770 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2773 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2774 defined $rawlines[$linenr] &&
2775 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2778 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2779 defined $rawlines[$linenr] &&
2780 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2781 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2783 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2784 $orig_desc .= " " . $1;
2788 ($id, $description) = git_commit_info($orig_commit,
2792 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2793 ERROR("GIT_COMMIT_ID",
2794 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2798 # Check for added, moved or deleted files
2799 if (!$reported_maintainer_file && !$in_commit_log &&
2800 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2801 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2802 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2803 (defined($1) || defined($2))))) {
2805 $reported_maintainer_file = 1;
2806 WARN("FILE_PATH_CHANGES",
2807 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2810 # Check for wrappage within a valid hunk of the file
2811 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2812 ERROR("CORRUPTED_PATCH",
2813 "patch seems to be corrupt (line wrapped?)\n" .
2814 $herecurr) if (!$emitted_corrupt++);
2817 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2818 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2819 $rawline !~ m/^$UTF8*$/) {
2820 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2822 my $blank = copy_spacing($rawline);
2823 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2824 my $hereptr = "$hereline$ptr\n";
2827 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2830 # Check if it's the start of a commit log
2831 # (not a header line and we haven't seen the patch filename)
2832 if ($in_header_lines && $realfile =~ /^$/ &&
2833 !($rawline =~ /^\s+(?:\S|$)/ ||
2834 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2835 $in_header_lines = 0;
2837 $has_commit_log = 1;
2840 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2841 # declined it, i.e defined some charset where it is missing.
2842 if ($in_header_lines &&
2843 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2845 $non_utf8_charset = 1;
2848 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2849 $rawline =~ /$NON_ASCII_UTF8/) {
2850 WARN("UTF8_BEFORE_PATCH",
2851 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2854 # Check for absolute kernel paths in commit message
2855 if ($tree && $in_commit_log) {
2856 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2859 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2860 check_absolute_file($1, $herecurr)) {
2863 check_absolute_file($file, $herecurr);
2868 # Check for various typo / spelling mistakes
2869 if (defined($misspellings) &&
2870 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2871 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2873 my $typo_fix = $spelling_fix{lc($typo)};
2874 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2875 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2876 my $msg_level = \&WARN;
2877 $msg_level = \&CHK if ($file);
2878 if (&{$msg_level}("TYPO_SPELLING",
2879 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2881 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2886 # ignore non-hunk lines and lines being removed
2887 next if (!$hunk_line || $line =~ /^-/);
2889 #trailing whitespace
2890 if ($line =~ /^\+.*\015/) {
2891 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2892 if (ERROR("DOS_LINE_ENDINGS",
2893 "DOS line endings\n" . $herevet) &&
2895 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2897 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2898 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2899 if (ERROR("TRAILING_WHITESPACE",
2900 "trailing whitespace\n" . $herevet) &&
2902 $fixed[$fixlinenr] =~ s/\s+$//;
2908 # Check for FSF mailing addresses.
2909 if ($rawline =~ /\bwrite to the Free/i ||
2910 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2911 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2912 $rawline =~ /\b51\s+Franklin\s+St/i) {
2913 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2914 my $msg_level = \&ERROR;
2915 $msg_level = \&CHK if ($file);
2916 &{$msg_level}("FSF_MAILING_ADDRESS",
2917 "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)
2920 # check for Kconfig help text having a real description
2921 # Only applies when adding the entry originally, after that we do not have
2922 # sufficient context to determine whether it is indeed long enough.
2923 if ($realfile =~ /Kconfig/ &&
2924 # 'choice' is usually the last thing on the line (though
2925 # Kconfig supports named choices), so use a word boundary
2926 # (\b) rather than a whitespace character (\s)
2927 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2930 my $ln = $linenr + 1;
2934 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2935 $f = $lines[$ln - 1];
2936 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2937 $is_end = $lines[$ln - 1] =~ /^\+/;
2939 next if ($f =~ /^-/);
2940 last if (!$file && $f =~ /^\@\@/);
2942 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2944 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2945 if ($lines[$ln - 1] =~ "---help---") {
2946 WARN("CONFIG_DESCRIPTION",
2947 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2955 next if ($f =~ /^$/);
2957 # This only checks context lines in the patch
2958 # and so hopefully shouldn't trigger false
2959 # positives, even though some of these are
2960 # common words in help texts
2961 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2962 if|endif|menu|endmenu|source)\b/x) {
2968 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2969 WARN("CONFIG_DESCRIPTION",
2970 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2972 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2975 # check for MAINTAINERS entries that don't have the right form
2976 if ($realfile =~ /^MAINTAINERS$/ &&
2977 $rawline =~ /^\+[A-Z]:/ &&
2978 $rawline !~ /^\+[A-Z]:\t\S/) {
2979 if (WARN("MAINTAINERS_STYLE",
2980 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2982 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2986 # discourage the use of boolean for type definition attributes of Kconfig options
2987 if ($realfile =~ /Kconfig/ &&
2988 $line =~ /^\+\s*\bboolean\b/) {
2989 WARN("CONFIG_TYPE_BOOLEAN",
2990 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2993 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2994 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2997 'EXTRA_AFLAGS' => 'asflags-y',
2998 'EXTRA_CFLAGS' => 'ccflags-y',
2999 'EXTRA_CPPFLAGS' => 'cppflags-y',
3000 'EXTRA_LDFLAGS' => 'ldflags-y',
3003 WARN("DEPRECATED_VARIABLE",
3004 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3007 # check for DT compatible documentation
3008 if (defined $root &&
3009 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3010 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3012 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3014 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3015 my $vp_file = $dt_path . "vendor-prefixes.txt";
3017 foreach my $compat (@compats) {
3018 my $compat2 = $compat;
3019 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3020 my $compat3 = $compat;
3021 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3022 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3024 WARN("UNDOCUMENTED_DT_STRING",
3025 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3028 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3030 `grep -Eq "^$vendor\\b" $vp_file`;
3032 WARN("UNDOCUMENTED_DT_STRING",
3033 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3038 # check for using SPDX license tag at beginning of files
3039 if ($realline == $checklicenseline) {
3040 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3041 $checklicenseline = 2;
3042 } elsif ($rawline =~ /^\+/) {
3044 if ($realfile =~ /\.(h|s|S)$/) {
3046 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3048 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3050 } elsif ($realfile =~ /\.rst$/) {
3054 if ($comment !~ /^$/ &&
3055 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3056 WARN("SPDX_LICENSE_TAG",
3057 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3058 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3059 my $spdx_license = $1;
3060 if (!is_SPDX_License_valid($spdx_license)) {
3061 WARN("SPDX_LICENSE_TAG",
3062 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3068 # check we are in a valid source file if not then ignore this hunk
3069 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3071 # line length limit (with some exclusions)
3073 # There are a few types of lines that may extend beyond $max_line_length:
3074 # logging functions like pr_info that end in a string
3075 # lines with a single string
3076 # #defines that are a single string
3077 # lines with an RFC3986 like URL
3079 # There are 3 different line length message types:
3080 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3081 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3082 # LONG_LINE all other lines longer than $max_line_length
3084 # if LONG_LINE is ignored, the other 2 types are also ignored
3087 if ($line =~ /^\+/ && $length > $max_line_length) {
3088 my $msg_type = "LONG_LINE";
3090 # Check the allowed long line types first
3092 # logging functions that end in a string that starts
3093 # before $max_line_length
3094 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3095 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3098 # lines with only strings (w/ possible termination)
3099 # #defines with only strings
3100 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3101 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3104 # More special cases
3105 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3106 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3109 # URL ($rawline is used in case the URL is in a comment)
3110 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3113 # Otherwise set the alternate message types
3115 # a comment starts before $max_line_length
3116 } elsif ($line =~ /($;[\s$;]*)$/ &&
3117 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3118 $msg_type = "LONG_LINE_COMMENT"
3120 # a quoted string starts before $max_line_length
3121 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3122 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3123 $msg_type = "LONG_LINE_STRING"
3126 if ($msg_type ne "" &&
3127 (show_type("LONG_LINE") || show_type($msg_type))) {
3128 my $msg_level = \&WARN;
3129 $msg_level = \&CHK if ($file);
3130 &{$msg_level}($msg_type,
3131 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3135 # check for adding lines without a newline.
3136 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3137 WARN("MISSING_EOF_NEWLINE",
3138 "adding a line without newline at end of file\n" . $herecurr);
3142 u_boot_line($realfile, $line, $herecurr);
3145 # check we are in a valid source file C or perl if not then ignore this hunk
3146 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3148 # at the beginning of a line any tabs must come first and anything
3149 # more than 8 must use tabs.
3150 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3151 $rawline =~ /^\+\s* \s*/) {
3152 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3154 if (ERROR("CODE_INDENT",
3155 "code indent should use tabs where possible\n" . $herevet) &&
3157 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3161 # check for space before tabs.
3162 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3163 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3164 if (WARN("SPACE_BEFORE_TAB",
3165 "please, no space before tabs\n" . $herevet) &&
3167 while ($fixed[$fixlinenr] =~
3168 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3169 while ($fixed[$fixlinenr] =~
3170 s/(^\+.*) +\t/$1\t/) {}
3174 # check for assignments on the start of a line
3175 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3176 CHK("ASSIGNMENT_CONTINUATIONS",
3177 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3180 # check for && or || at the start of a line
3181 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3182 CHK("LOGICAL_CONTINUATIONS",
3183 "Logical continuations should be on the previous line\n" . $hereprev);
3186 # check indentation starts on a tab stop
3187 if ($perl_version_ok &&
3188 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3189 my $indent = length($1);
3192 "Statements should start on a tabstop\n" . $herecurr) &&
3194 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3199 # check multi-line statement indentation matches previous line
3200 if ($perl_version_ok &&
3201 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3202 $prevline =~ /^\+(\t*)(.*)$/;
3206 my $pos = pos_last_openparen($rest);
3208 $line =~ /^(\+| )([ \t]*)/;
3211 my $goodtabindent = $oldindent .
3214 my $goodspaceindent = $oldindent . " " x $pos;
3216 if ($newindent ne $goodtabindent &&
3217 $newindent ne $goodspaceindent) {
3219 if (CHK("PARENTHESIS_ALIGNMENT",
3220 "Alignment should match open parenthesis\n" . $hereprev) &&
3221 $fix && $line =~ /^\+/) {
3222 $fixed[$fixlinenr] =~
3223 s/^\+[ \t]*/\+$goodtabindent/;
3229 # check for space after cast like "(int) foo" or "(struct foo) bar"
3230 # avoid checking a few false positives:
3231 # "sizeof(<type>)" or "__alignof__(<type>)"
3232 # function pointer declarations like "(*foo)(int) = bar;"
3233 # structure definitions like "(struct foo) { 0 };"
3234 # multiline macros that define functions
3235 # known attributes or the __attribute__ keyword
3236 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3237 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3239 "No space is necessary after a cast\n" . $herecurr) &&
3241 $fixed[$fixlinenr] =~
3242 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3246 # Block comment styles
3247 # Networking with an initial /*
3248 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3249 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3250 $rawline =~ /^\+[ \t]*\*/ &&
3252 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3253 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3256 # Block comments use * on subsequent lines
3257 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3258 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3259 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3260 $rawline =~ /^\+/ && #line is new
3261 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3262 WARN("BLOCK_COMMENT_STYLE",
3263 "Block comments use * on subsequent lines\n" . $hereprev);
3266 # Block comments use */ on trailing lines
3267 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3268 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3269 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3270 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3271 WARN("BLOCK_COMMENT_STYLE",
3272 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3275 # Block comment * alignment
3276 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3277 $line =~ /^\+[ \t]*$;/ && #leading comment
3278 $rawline =~ /^\+[ \t]*\*/ && #leading *
3279 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3280 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3281 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3283 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3285 $oldindent = expand_tabs($1);
3287 $prevrawline =~ m@^\+(.*/?)\*@;
3288 $oldindent = expand_tabs($1);
3290 $rawline =~ m@^\+([ \t]*)\*@;
3292 $newindent = expand_tabs($newindent);
3293 if (length($oldindent) ne length($newindent)) {
3294 WARN("BLOCK_COMMENT_STYLE",
3295 "Block comments should align the * on each line\n" . $hereprev);
3299 # check for missing blank lines after struct/union declarations
3300 # with exceptions for various attributes and macros
3301 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3303 !($line =~ /^\+\s*$/ ||
3304 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3305 $line =~ /^\+\s*MODULE_/i ||
3306 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3307 $line =~ /^\+[a-z_]*init/ ||
3308 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3309 $line =~ /^\+\s*DECLARE/ ||
3310 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3311 $line =~ /^\+\s*__setup/)) {
3312 if (CHK("LINE_SPACING",
3313 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3315 fix_insert_line($fixlinenr, "\+");
3319 # check for multiple consecutive blank lines
3320 if ($prevline =~ /^[\+ ]\s*$/ &&
3321 $line =~ /^\+\s*$/ &&
3322 $last_blank_line != ($linenr - 1)) {
3323 if (CHK("LINE_SPACING",
3324 "Please don't use multiple blank lines\n" . $hereprev) &&
3326 fix_delete_line($fixlinenr, $rawline);
3329 $last_blank_line = $linenr;
3332 # check for missing blank lines after declarations
3333 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3334 # actual declarations
3335 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3336 # function pointer declarations
3337 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3338 # foo bar; where foo is some local typedef or #define
3339 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3340 # known declaration macros
3341 $prevline =~ /^\+\s+$declaration_macros/) &&
3342 # for "else if" which can look like "$Ident $Ident"
3343 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3344 # other possible extensions of declaration lines
3345 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3346 # not starting a section or a macro "\" extended line
3347 $prevline =~ /(?:\{\s*|\\)$/) &&
3348 # looks like a declaration
3349 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3350 # function pointer declarations
3351 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3352 # foo bar; where foo is some local typedef or #define
3353 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3354 # known declaration macros
3355 $sline =~ /^\+\s+$declaration_macros/ ||
3356 # start of struct or union or enum
3357 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3358 # start or end of block or continuation of declaration
3359 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3360 # bitfield continuation
3361 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3362 # other possible extensions of declaration lines
3363 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3364 # indentation of previous and current line are the same
3365 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3366 if (WARN("LINE_SPACING",
3367 "Missing a blank line after declarations\n" . $hereprev) &&
3369 fix_insert_line($fixlinenr, "\+");
3373 # check for spaces at the beginning of a line.
3375 # 1) within comments
3376 # 2) indented preprocessor commands
3378 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3379 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3380 if (WARN("LEADING_SPACE",
3381 "please, no spaces at the start of a line\n" . $herevet) &&
3383 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3387 # check we are in a valid C source file if not then ignore this hunk
3388 next if ($realfile !~ /\.(h|c)$/);
3390 # check for unusual line ending [ or (
3391 if ($line =~ /^\+.*([\[\(])\s*$/) {
3392 CHK("OPEN_ENDED_LINE",
3393 "Lines should not end with a '$1'\n" . $herecurr);
3396 # check if this appears to be the start function declaration, save the name
3397 if ($sline =~ /^\+\{\s*$/ &&
3398 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3399 $context_function = $1;
3402 # check if this appears to be the end of function declaration
3403 if ($sline =~ /^\+\}\s*$/) {
3404 undef $context_function;
3407 # check indentation of any line with a bare else
3408 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3409 # if the previous line is a break or return and is indented 1 tab more...
3410 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3411 my $tabs = length($1) + 1;
3412 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3413 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3414 defined $lines[$linenr] &&
3415 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3416 WARN("UNNECESSARY_ELSE",
3417 "else is not generally useful after a break or return\n" . $hereprev);
3421 # check indentation of a line with a break;
3422 # if the previous line is a goto or return and is indented the same # of tabs
3423 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3425 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3426 WARN("UNNECESSARY_BREAK",
3427 "break is not useful after a goto or return\n" . $hereprev);
3431 # check for RCS/CVS revision markers
3432 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3434 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3437 # check for old HOTPLUG __dev<foo> section markings
3438 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3439 WARN("HOTPLUG_SECTION",
3440 "Using $1 is unnecessary\n" . $herecurr);
3443 # Check for potential 'bare' types
3444 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3446 #print "LINE<$line>\n";
3447 if ($linenr > $suppress_statement &&
3448 $realcnt && $sline =~ /.\s*\S/) {
3449 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3450 ctx_statement_block($linenr, $realcnt, 0);
3451 $stat =~ s/\n./\n /g;
3452 $cond =~ s/\n./\n /g;
3454 #print "linenr<$linenr> <$stat>\n";
3455 # If this statement has no statement boundaries within
3456 # it there is no point in retrying a statement scan
3457 # until we hit end of it.
3458 my $frag = $stat; $frag =~ s/;+\s*$//;
3459 if ($frag !~ /(?:{|;)/) {
3460 #print "skip<$line_nr_next>\n";
3461 $suppress_statement = $line_nr_next;
3464 # Find the real next line.
3465 $realline_next = $line_nr_next;
3466 if (defined $realline_next &&
3467 (!defined $lines[$realline_next - 1] ||
3468 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3475 # Ignore goto labels.
3476 if ($s =~ /$Ident:\*$/s) {
3478 # Ignore functions being called
3479 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3481 } elsif ($s =~ /^.\s*else\b/s) {
3483 # declarations always start with types
3484 } 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) {
3487 possible($type, "A:" . $s);
3489 # definitions in global scope can only start with types
3490 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3491 possible($1, "B:" . $s);
3494 # any (foo ... *) is a pointer cast, and foo is a type
3495 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3496 possible($1, "C:" . $s);
3499 # Check for any sort of function declaration.
3500 # int foo(something bar, other baz);
3501 # void (*store_gdt)(x86_descr_ptr *);
3502 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3503 my ($name_len) = length($1);
3506 substr($ctx, 0, $name_len + 1, '');
3507 $ctx =~ s/\)[^\)]*$//;
3509 for my $arg (split(/\s*,\s*/, $ctx)) {
3510 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3512 possible($1, "D:" . $s);
3520 # Checks which may be anchored in the context.
3523 # Check for switch () and associated case and default
3524 # statements should be at the same indent.
3525 if ($line=~/\bswitch\s*\(.*\)/) {
3528 my @ctx = ctx_block_outer($linenr, $realcnt);
3530 for my $ctx (@ctx) {
3531 my ($clen, $cindent) = line_stats($ctx);
3532 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3533 $indent != $cindent) {
3534 $err .= "$sep$ctx\n";
3541 ERROR("SWITCH_CASE_INDENT_LEVEL",
3542 "switch and case should be at the same indent\n$hereline$err");
3546 # if/while/etc brace do not go on next line, unless defining a do while loop,
3547 # or if that brace on the next line is for something else
3548 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3549 my $pre_ctx = "$1$2";
3551 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3553 if ($line =~ /^\+\t{6,}/) {
3554 WARN("DEEP_INDENTATION",
3555 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3558 my $ctx_cnt = $realcnt - $#ctx - 1;
3559 my $ctx = join("\n", @ctx);
3561 my $ctx_ln = $linenr;
3562 my $ctx_skip = $realcnt;
3564 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3565 defined $lines[$ctx_ln - 1] &&
3566 $lines[$ctx_ln - 1] =~ /^-/)) {
3567 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3568 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3572 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3573 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3575 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3577 "that open brace { should be on the previous line\n" .
3578 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3580 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3581 $ctx =~ /\)\s*\;\s*$/ &&
3582 defined $lines[$ctx_ln - 1])
3584 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3585 if ($nindent > $indent) {
3586 WARN("TRAILING_SEMICOLON",
3587 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3588 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3593 # Check relative indent for conditionals and blocks.
3594 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3595 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3596 ctx_statement_block($linenr, $realcnt, 0)
3597 if (!defined $stat);
3598 my ($s, $c) = ($stat, $cond);
3600 substr($s, 0, length($c), '');
3602 # remove inline comments
3606 # Find out how long the conditional actually is.
3607 my @newlines = ($c =~ /\n/gs);
3608 my $cond_lines = 1 + $#newlines;
3610 # Make sure we remove the line prefixes as we have
3611 # none on the first line, and are going to readd them
3614 while ($s =~ /\n\s+\\\n/) {
3615 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3618 # We want to check the first line inside the block
3619 # starting at the end of the conditional, so remove:
3620 # 1) any blank line termination
3621 # 2) any opening brace { on end of the line
3623 my $continuation = 0;
3625 $s =~ s/^.*\bdo\b//;
3627 if ($s =~ s/^\s*\\//) {
3630 if ($s =~ s/^\s*?\n//) {
3635 # Also ignore a loop construct at the end of a
3636 # preprocessor statement.
3637 if (($prevline =~ /^.\s*#\s*define\s/ ||
3638 $prevline =~ /\\\s*$/) && $continuation == 0) {
3644 while ($cond_ptr != $cond_lines) {
3645 $cond_ptr = $cond_lines;
3647 # If we see an #else/#elif then the code
3649 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3654 # 1) blank lines, they should be at 0,
3655 # 2) preprocessor lines, and
3657 if ($continuation ||
3659 $s =~ /^\s*#\s*?/ ||
3660 $s =~ /^\s*$Ident\s*:/) {
3661 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3662 if ($s =~ s/^.*?\n//) {
3668 my (undef, $sindent) = line_stats("+" . $s);
3669 my $stat_real = raw_line($linenr, $cond_lines);
3671 # Check if either of these lines are modified, else
3672 # this is not this patch's fault.
3673 if (!defined($stat_real) ||
3674 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3677 if (defined($stat_real) && $cond_lines > 1) {
3678 $stat_real = "[...]\n$stat_real";
3681 #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";
3683 if ($check && $s ne '' &&
3684 (($sindent % 8) != 0 ||
3685 ($sindent < $indent) ||
3686 ($sindent == $indent &&
3687 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3688 ($sindent > $indent + 8))) {
3689 WARN("SUSPECT_CODE_INDENT",
3690 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3694 # Track the 'values' across context and added lines.
3695 my $opline = $line; $opline =~ s/^./ /;
3696 my ($curr_values, $curr_vars) =
3697 annotate_values($opline . "\n", $prev_values);
3698 $curr_values = $prev_values . $curr_values;
3700 my $outline = $opline; $outline =~ s/\t/ /g;
3701 print "$linenr > .$outline\n";
3702 print "$linenr > $curr_values\n";
3703 print "$linenr > $curr_vars\n";
3705 $prev_values = substr($curr_values, -1);
3707 #ignore lines not being added
3708 next if ($line =~ /^[^\+]/);
3710 # check for dereferences that span multiple lines
3711 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3712 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3713 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3715 $line =~ /^.\s*($Lval)/;
3718 WARN("MULTILINE_DEREFERENCE",
3719 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3722 # check for declarations of signed or unsigned without int
3723 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3726 $var = "" if (!defined $var);
3727 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3731 $pointer = "" if (!defined $pointer);
3733 if (WARN("UNSPECIFIED_INT",
3734 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3736 my $decl = trim($sign) . " int ";
3737 my $comp_pointer = $pointer;
3738 $comp_pointer =~ s/\s//g;
3739 $decl .= $comp_pointer;
3740 $decl = rtrim($decl) if ($var eq "");
3741 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3746 # TEST: allow direct testing of the type matcher.
3748 if ($line =~ /^.\s*$Declare\s*$/) {
3750 "TEST: is type\n" . $herecurr);
3751 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3752 ERROR("TEST_NOT_TYPE",
3753 "TEST: is not type ($1 is)\n". $herecurr);
3757 # TEST: allow direct testing of the attribute matcher.
3759 if ($line =~ /^.\s*$Modifier\s*$/) {
3761 "TEST: is attr\n" . $herecurr);
3762 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3763 ERROR("TEST_NOT_ATTR",
3764 "TEST: is not attr ($1 is)\n". $herecurr);
3769 # check for initialisation to aggregates open brace on the next line
3770 if ($line =~ /^.\s*{/ &&
3771 $prevline =~ /(?:^|[^=])=\s*$/) {
3772 if (ERROR("OPEN_BRACE",
3773 "that open brace { should be on the previous line\n" . $hereprev) &&
3774 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3775 fix_delete_line($fixlinenr - 1, $prevrawline);
3776 fix_delete_line($fixlinenr, $rawline);
3777 my $fixedline = $prevrawline;
3778 $fixedline =~ s/\s*=\s*$/ = {/;
3779 fix_insert_line($fixlinenr, $fixedline);
3781 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3782 fix_insert_line($fixlinenr, $fixedline);
3787 # Checks which are anchored on the added line.
3790 # check for malformed paths in #include statements (uses RAW line)
3791 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3793 if ($path =~ m{//}) {
3794 ERROR("MALFORMED_INCLUDE",
3795 "malformed #include filename\n" . $herecurr);
3797 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3798 ERROR("UAPI_INCLUDE",
3799 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3803 # no C99 // comments
3804 if ($line =~ m{//}) {
3805 if (ERROR("C99_COMMENTS",
3806 "do not use C99 // comments\n" . $herecurr) &&
3808 my $line = $fixed[$fixlinenr];
3809 if ($line =~ /\/\/(.*)$/) {
3810 my $comment = trim($1);
3811 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3815 # Remove C99 comments.
3817 $opline =~ s@//.*@@;
3819 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3820 # the whole statement.
3821 #print "APW <$lines[$realline_next - 1]>\n";
3822 if (defined $realline_next &&
3823 exists $lines[$realline_next - 1] &&
3824 !defined $suppress_export{$realline_next} &&
3825 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3826 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3827 # Handle definitions which produce identifiers with
3830 # EXPORT_SYMBOL(something_foo);
3832 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3833 $name =~ /^${Ident}_$2/) {
3834 #print "FOO C name<$name>\n";
3835 $suppress_export{$realline_next} = 1;
3837 } elsif ($stat !~ /(?:
3839 ^.DEFINE_$Ident\(\Q$name\E\)|
3840 ^.DECLARE_$Ident\(\Q$name\E\)|
3841 ^.LIST_HEAD\(\Q$name\E\)|
3842 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3843 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3845 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3846 $suppress_export{$realline_next} = 2;
3848 $suppress_export{$realline_next} = 1;
3851 if (!defined $suppress_export{$linenr} &&
3852 $prevline =~ /^.\s*$/ &&
3853 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3854 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3855 #print "FOO B <$lines[$linenr - 1]>\n";
3856 $suppress_export{$linenr} = 2;
3858 if (defined $suppress_export{$linenr} &&
3859 $suppress_export{$linenr} == 2) {
3860 WARN("EXPORT_SYMBOL",
3861 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3864 # check for global initialisers.
3865 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3866 if (ERROR("GLOBAL_INITIALISERS",
3867 "do not initialise globals to $1\n" . $herecurr) &&
3869 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3872 # check for static initialisers.
3873 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3874 if (ERROR("INITIALISED_STATIC",
3875 "do not initialise statics to $1\n" .
3878 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3882 # check for misordered declarations of char/short/int/long with signed/unsigned
3883 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3885 WARN("MISORDERED_TYPE",
3886 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3889 # check for unnecessary <signed> int declarations of short/long/long long
3890 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3891 my $type = trim($1);
3892 next if ($type !~ /\bint\b/);
3893 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3894 my $new_type = $type;
3895 $new_type =~ s/\b\s*int\s*\b/ /;
3896 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3897 $new_type =~ s/^const\s+//;
3898 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3899 $new_type = "const $new_type" if ($type =~ /^const\b/);
3900 $new_type =~ s/\s+/ /g;
3901 $new_type = trim($new_type);
3902 if (WARN("UNNECESSARY_INT",
3903 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3905 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3909 # check for static const char * arrays.
3910 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3911 WARN("STATIC_CONST_CHAR_ARRAY",
3912 "static const char * array should probably be static const char * const\n" .
3916 # check for static char foo[] = "bar" declarations.
3917 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3918 WARN("STATIC_CONST_CHAR_ARRAY",
3919 "static char array declaration should probably be static const char\n" .
3923 # check for const <foo> const where <foo> is not a pointer or array type
3924 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3926 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3928 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3929 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3931 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3935 # check for non-global char *foo[] = {"bar", ...} declarations.
3936 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3937 WARN("STATIC_CONST_CHAR_ARRAY",
3938 "char * array declaration might be better as static const\n" .
3942 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3943 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3945 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3947 if (WARN("ARRAY_SIZE",
3948 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3950 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3955 # check for function declarations without arguments like "int foo()"
3956 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3957 if (ERROR("FUNCTION_WITHOUT_ARGS",
3958 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3960 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3964 # check for new typedefs, only function parameters and sparse annotations
3966 if ($line =~ /\btypedef\s/ &&
3967 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3968 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3969 $line !~ /\b$typeTypedefs\b/ &&
3970 $line !~ /\b__bitwise\b/) {
3971 WARN("NEW_TYPEDEFS",
3972 "do not add new typedefs\n" . $herecurr);
3975 # * goes on variable not on type
3977 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3979 my ($ident, $from, $to) = ($1, $2, $2);
3981 # Should start with a space.
3982 $to =~ s/^(\S)/ $1/;
3983 # Should not end with a space.
3985 # '*'s should not have spaces between.
3986 while ($to =~ s/\*\s+\*/\*\*/) {
3989 ## print "1: from<$from> to<$to> ident<$ident>\n";
3991 if (ERROR("POINTER_LOCATION",
3992 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3994 my $sub_from = $ident;
3995 my $sub_to = $ident;
3996 $sub_to =~ s/\Q$from\E/$to/;
3997 $fixed[$fixlinenr] =~
3998 s@\Q$sub_from\E@$sub_to@;
4002 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4004 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4006 # Should start with a space.
4007 $to =~ s/^(\S)/ $1/;
4008 # Should not end with a space.
4010 # '*'s should not have spaces between.
4011 while ($to =~ s/\*\s+\*/\*\*/) {
4013 # Modifiers should have spaces.
4014 $to =~ s/(\b$Modifier$)/$1 /;
4016 ## print "2: from<$from> to<$to> ident<$ident>\n";
4017 if ($from ne $to && $ident !~ /^$Modifier$/) {
4018 if (ERROR("POINTER_LOCATION",
4019 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4022 my $sub_from = $match;
4023 my $sub_to = $match;
4024 $sub_to =~ s/\Q$from\E/$to/;
4025 $fixed[$fixlinenr] =~
4026 s@\Q$sub_from\E@$sub_to@;
4031 # avoid BUG() or BUG_ON()
4032 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4033 my $msg_level = \&WARN;
4034 $msg_level = \&CHK if ($file);
4035 &{$msg_level}("AVOID_BUG",
4036 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4039 # avoid LINUX_VERSION_CODE
4040 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4041 WARN("LINUX_VERSION_CODE",
4042 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4045 # check for uses of printk_ratelimit
4046 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4047 WARN("PRINTK_RATELIMITED",
4048 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4051 # printk should use KERN_* levels
4052 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4053 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4054 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4057 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4059 my $level = lc($orig);
4060 $level = "warn" if ($level eq "warning");
4061 my $level2 = $level;
4062 $level2 = "dbg" if ($level eq "debug");
4063 WARN("PREFER_PR_LEVEL",
4064 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4067 if ($line =~ /\bpr_warning\s*\(/) {
4068 if (WARN("PREFER_PR_LEVEL",
4069 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4071 $fixed[$fixlinenr] =~
4072 s/\bpr_warning\b/pr_warn/;
4076 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4078 my $level = lc($orig);
4079 $level = "warn" if ($level eq "warning");
4080 $level = "dbg" if ($level eq "debug");
4081 WARN("PREFER_DEV_LEVEL",
4082 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4085 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4086 # number of false positives, but assembly files are not checked, so at
4087 # least the arch entry code will not trigger this warning.
4088 if ($line =~ /\bENOSYS\b/) {
4090 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4093 # function brace can't be on same line, except for #defines of do while,
4094 # or if closed on same line
4095 if ($perl_version_ok &&
4096 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4097 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4099 if (ERROR("OPEN_BRACE",
4100 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4102 fix_delete_line($fixlinenr, $rawline);
4103 my $fixed_line = $rawline;
4104 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4107 fix_insert_line($fixlinenr, ltrim($line1));
4108 fix_insert_line($fixlinenr, "\+{");
4109 if ($line2 !~ /^\s*$/) {
4110 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4115 # open braces for enum, union and struct go on the same line.
4116 if ($line =~ /^.\s*{/ &&
4117 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4118 if (ERROR("OPEN_BRACE",
4119 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4120 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4121 fix_delete_line($fixlinenr - 1, $prevrawline);
4122 fix_delete_line($fixlinenr, $rawline);
4123 my $fixedline = rtrim($prevrawline) . " {";
4124 fix_insert_line($fixlinenr, $fixedline);
4125 $fixedline = $rawline;
4126 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4127 if ($fixedline !~ /^\+\s*$/) {
4128 fix_insert_line($fixlinenr, $fixedline);
4133 # missing space after union, struct or enum definition
4134 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4136 "missing space after $1 definition\n" . $herecurr) &&
4138 $fixed[$fixlinenr] =~
4139 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4143 # Function pointer declarations
4144 # check spacing between type, funcptr, and args
4145 # canonical declaration is "type (*funcptr)(args...)"
4146 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4148 my $pre_pointer_space = $2;
4149 my $post_pointer_space = $3;
4151 my $post_funcname_space = $5;
4152 my $pre_args_space = $6;
4154 # the $Declare variable will capture all spaces after the type
4155 # so check it for a missing trailing missing space but pointer return types
4156 # don't need a space so don't warn for those.
4157 my $post_declare_space = "";
4158 if ($declare =~ /(\s+)$/) {
4159 $post_declare_space = $1;
4160 $declare = rtrim($declare);
4162 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4164 "missing space after return type\n" . $herecurr);
4165 $post_declare_space = " ";
4168 # unnecessary space "type (*funcptr)(args...)"
4169 # This test is not currently implemented because these declarations are
4171 # int foo(int bar, ...)
4172 # and this is form shouldn't/doesn't generate a checkpatch warning.
4174 # elsif ($declare =~ /\s{2,}$/) {
4176 # "Multiple spaces after return type\n" . $herecurr);
4179 # unnecessary space "type ( *funcptr)(args...)"
4180 if (defined $pre_pointer_space &&
4181 $pre_pointer_space =~ /^\s/) {
4183 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4186 # unnecessary space "type (* funcptr)(args...)"
4187 if (defined $post_pointer_space &&
4188 $post_pointer_space =~ /^\s/) {
4190 "Unnecessary space before function pointer name\n" . $herecurr);
4193 # unnecessary space "type (*funcptr )(args...)"
4194 if (defined $post_funcname_space &&
4195 $post_funcname_space =~ /^\s/) {
4197 "Unnecessary space after function pointer name\n" . $herecurr);
4200 # unnecessary space "type (*funcptr) (args...)"
4201 if (defined $pre_args_space &&
4202 $pre_args_space =~ /^\s/) {
4204 "Unnecessary space before function pointer arguments\n" . $herecurr);
4207 if (show_type("SPACING") && $fix) {
4208 $fixed[$fixlinenr] =~
4209 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4213 # check for spacing round square brackets; allowed:
4214 # 1. with a type on the left -- int [] a;
4215 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4216 # 3. inside a curly brace -- = { [0...10] = 5 }
4217 while ($line =~ /(.*?\s)\[/g) {
4218 my ($where, $prefix) = ($-[1], $1);
4219 if ($prefix !~ /$Type\s+$/ &&
4220 ($where != 0 || $prefix !~ /^.\s+$/) &&
4221 $prefix !~ /[{,:]\s+$/) {
4222 if (ERROR("BRACKET_SPACE",
4223 "space prohibited before open square bracket '['\n" . $herecurr) &&
4225 $fixed[$fixlinenr] =~
4226 s/^(\+.*?)\s+\[/$1\[/;
4231 # check for spaces between functions and their parentheses.
4232 while ($line =~ /($Ident)\s+\(/g) {
4234 my $ctx_before = substr($line, 0, $-[1]);
4235 my $ctx = "$ctx_before$name";
4237 # Ignore those directives where spaces _are_ permitted.
4239 if|for|while|switch|return|case|
4240 volatile|__volatile__|
4241 __attribute__|format|__extension__|
4244 # cpp #define statements have non-optional spaces, ie
4245 # if there is a space between the name and the open
4246 # parenthesis it is simply not a parameter group.
4247 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4249 # cpp #elif statement condition may start with a (
4250 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4252 # If this whole things ends with a type its most
4253 # likely a typedef for a function.
4254 } elsif ($ctx =~ /$Type$/) {
4258 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4260 $fixed[$fixlinenr] =~
4261 s/\b$name\s+\(/$name\(/;
4266 # Check operator spacing.
4267 if (!($line=~/\#\s*include/)) {
4268 my $fixed_line = "";
4272 <<=|>>=|<=|>=|==|!=|
4273 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4274 =>|->|<<|>>|<|>|=|!|~|
4275 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4278 my @elements = split(/($ops|;)/, $opline);
4280 ## print("element count: <" . $#elements . ">\n");
4281 ## foreach my $el (@elements) {
4282 ## print("el: <$el>\n");
4285 my @fix_elements = ();
4288 foreach my $el (@elements) {
4289 push(@fix_elements, substr($rawline, $off, length($el)));
4290 $off += length($el);
4295 my $blank = copy_spacing($opline);
4296 my $last_after = -1;
4298 for (my $n = 0; $n < $#elements; $n += 2) {
4300 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4302 ## print("n: <$n> good: <$good>\n");
4304 $off += length($elements[$n]);
4306 # Pick up the preceding and succeeding characters.
4307 my $ca = substr($opline, 0, $off);
4309 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4310 $cc = substr($opline, $off + length($elements[$n + 1]));
4312 my $cb = "$ca$;$cc";
4315 $a = 'V' if ($elements[$n] ne '');
4316 $a = 'W' if ($elements[$n] =~ /\s$/);
4317 $a = 'C' if ($elements[$n] =~ /$;$/);
4318 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4319 $a = 'O' if ($elements[$n] eq '');
4320 $a = 'E' if ($ca =~ /^\s*$/);
4322 my $op = $elements[$n + 1];
4325 if (defined $elements[$n + 2]) {
4326 $c = 'V' if ($elements[$n + 2] ne '');
4327 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4328 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4329 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4330 $c = 'O' if ($elements[$n + 2] eq '');
4331 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4336 my $ctx = "${a}x${c}";
4338 my $at = "(ctx:$ctx)";
4340 my $ptr = substr($blank, 0, $off) . "^";
4341 my $hereptr = "$hereline$ptr\n";
4343 # Pull out the value of this operator.
4344 my $op_type = substr($curr_values, $off + 1, 1);
4346 # Get the full operator variant.
4347 my $opv = $op . substr($curr_vars, $off, 1);
4349 # Ignore operators passed as parameters.
4350 if ($op_type ne 'V' &&
4351 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4354 # } elsif ($op =~ /^$;+$/) {
4356 # ; should have either the end of line or a space or \ after it
4357 } elsif ($op eq ';') {
4358 if ($ctx !~ /.x[WEBC]/ &&
4359 $cc !~ /^\\/ && $cc !~ /^;/) {
4360 if (ERROR("SPACING",
4361 "space required after that '$op' $at\n" . $hereptr)) {
4362 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4368 } elsif ($op eq '//') {
4370 # : when part of a bitfield
4371 } elsif ($opv eq ':B') {
4372 # skip the bitfield test for now
4376 } elsif ($op eq '->') {
4377 if ($ctx =~ /Wx.|.xW/) {
4378 if (ERROR("SPACING",
4379 "spaces prohibited around that '$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 # , must not have a space before and must have a space on the right.
4389 } elsif ($op eq ',') {
4390 my $rtrim_before = 0;
4391 my $space_after = 0;
4392 if ($ctx =~ /Wx./) {
4393 if (ERROR("SPACING",
4394 "space prohibited before that '$op' $at\n" . $hereptr)) {
4399 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4400 if (ERROR("SPACING",
4401 "space required after that '$op' $at\n" . $hereptr)) {
4407 if ($rtrim_before || $space_after) {
4408 if ($rtrim_before) {
4409 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4411 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4418 # '*' as part of a type definition -- reported already.
4419 } elsif ($opv eq '*_') {
4420 #warn "'*' is part of type\n";
4422 # unary operators should have a space before and
4423 # none after. May be left adjacent to another
4424 # unary operator, or a cast
4425 } elsif ($op eq '!' || $op eq '~' ||
4426 $opv eq '*U' || $opv eq '-U' ||
4427 $opv eq '&U' || $opv eq '&&U') {
4428 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4429 if (ERROR("SPACING",
4430 "space required before that '$op' $at\n" . $hereptr)) {
4431 if ($n != $last_after + 2) {
4432 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4437 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4438 # A unary '*' may be const
4440 } elsif ($ctx =~ /.xW/) {
4441 if (ERROR("SPACING",
4442 "space prohibited after that '$op' $at\n" . $hereptr)) {
4443 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4444 if (defined $fix_elements[$n + 2]) {
4445 $fix_elements[$n + 2] =~ s/^\s+//;
4451 # unary ++ and unary -- are allowed no space on one side.
4452 } elsif ($op eq '++' or $op eq '--') {
4453 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4454 if (ERROR("SPACING",
4455 "space required one side of that '$op' $at\n" . $hereptr)) {
4456 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4460 if ($ctx =~ /Wx[BE]/ ||
4461 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4462 if (ERROR("SPACING",
4463 "space prohibited before that '$op' $at\n" . $hereptr)) {
4464 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4468 if ($ctx =~ /ExW/) {
4469 if (ERROR("SPACING",
4470 "space prohibited after that '$op' $at\n" . $hereptr)) {
4471 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4472 if (defined $fix_elements[$n + 2]) {
4473 $fix_elements[$n + 2] =~ s/^\s+//;
4479 # << and >> may either have or not have spaces both sides
4480 } elsif ($op eq '<<' or $op eq '>>' or
4481 $op eq '&' or $op eq '^' or $op eq '|' or
4482 $op eq '+' or $op eq '-' or
4483 $op eq '*' or $op eq '/' or
4487 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4489 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4490 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4491 $fix_elements[$n + 2] =~ s/^\s+//;
4494 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4496 "space preferred before that '$op' $at\n" . $hereptr)) {
4497 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4501 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4502 if (ERROR("SPACING",
4503 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4504 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4505 if (defined $fix_elements[$n + 2]) {
4506 $fix_elements[$n + 2] =~ s/^\s+//;
4512 # A colon needs no spaces before when it is
4513 # terminating a case value or a label.
4514 } elsif ($opv eq ':C' || $opv eq ':L') {
4515 if ($ctx =~ /Wx./) {
4516 if (ERROR("SPACING",
4517 "space prohibited before that '$op' $at\n" . $hereptr)) {
4518 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4523 # All the others need spaces both sides.
4524 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4527 # Ignore email addresses <foo@bar>
4529 $cc =~ /^\S+\@\S+>/) ||
4531 $ca =~ /<\S+\@\S+$/))
4536 # for asm volatile statements
4537 # ignore a colon with another
4538 # colon immediately before or after
4540 ($ca =~ /:$/ || $cc =~ /^:/)) {
4544 # messages are ERROR, but ?: are CHK
4546 my $msg_level = \&ERROR;
4547 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4549 if (&{$msg_level}("SPACING",
4550 "spaces required around that '$op' $at\n" . $hereptr)) {
4551 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4552 if (defined $fix_elements[$n + 2]) {
4553 $fix_elements[$n + 2] =~ s/^\s+//;
4559 $off += length($elements[$n + 1]);
4561 ## print("n: <$n> GOOD: <$good>\n");
4563 $fixed_line = $fixed_line . $good;
4566 if (($#elements % 2) == 0) {
4567 $fixed_line = $fixed_line . $fix_elements[$#elements];
4570 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4571 $fixed[$fixlinenr] = $fixed_line;
4577 # check for whitespace before a non-naked semicolon
4578 if ($line =~ /^\+.*\S\s+;\s*$/) {
4580 "space prohibited before semicolon\n" . $herecurr) &&
4582 1 while $fixed[$fixlinenr] =~
4583 s/^(\+.*\S)\s+;/$1;/;
4587 # check for multiple assignments
4588 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4589 CHK("MULTIPLE_ASSIGNMENTS",
4590 "multiple assignments should be avoided\n" . $herecurr);
4593 ## # check for multiple declarations, allowing for a function declaration
4595 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4596 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4598 ## # Remove any bracketed sections to ensure we do not
4599 ## # falsly report the parameters of functions.
4601 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4603 ## if ($ln =~ /,/) {
4604 ## WARN("MULTIPLE_DECLARATION",
4605 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4609 #need space before brace following if, while, etc
4610 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4611 $line =~ /\b(?:else|do)\{/) {
4612 if (ERROR("SPACING",
4613 "space required before the open brace '{'\n" . $herecurr) &&
4615 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4619 ## # check for blank lines before declarations
4620 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4621 ## $prevrawline =~ /^.\s*$/) {
4623 ## "No blank lines before declarations\n" . $hereprev);
4627 # closing brace should have a space following it when it has anything
4629 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4630 if (ERROR("SPACING",
4631 "space required after that close brace '}'\n" . $herecurr) &&
4633 $fixed[$fixlinenr] =~
4634 s/}((?!(?:,|;|\)))\S)/} $1/;
4638 # check spacing on square brackets
4639 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4640 if (ERROR("SPACING",
4641 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4643 $fixed[$fixlinenr] =~
4647 if ($line =~ /\s\]/) {
4648 if (ERROR("SPACING",
4649 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4651 $fixed[$fixlinenr] =~
4656 # check spacing on parentheses
4657 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4658 $line !~ /for\s*\(\s+;/) {
4659 if (ERROR("SPACING",
4660 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4662 $fixed[$fixlinenr] =~
4666 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4667 $line !~ /for\s*\(.*;\s+\)/ &&
4668 $line !~ /:\s+\)/) {
4669 if (ERROR("SPACING",
4670 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4672 $fixed[$fixlinenr] =~
4677 # check unnecessary parentheses around addressof/dereference single $Lvals
4678 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4680 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4682 if (CHK("UNNECESSARY_PARENTHESES",
4683 "Unnecessary parentheses around $var\n" . $herecurr) &&
4685 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4689 # check for unnecessary parentheses around function pointer uses
4690 # ie: (foo->bar)(); should be foo->bar();
4691 # but not "if (foo->bar) (" to avoid some false positives
4692 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4694 if (CHK("UNNECESSARY_PARENTHESES",
4695 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4697 my $var2 = deparenthesize($var);
4699 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4703 # check for unnecessary parentheses around comparisons in if uses
4704 # when !drivers/staging or command-line uses --strict
4705 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4706 $perl_version_ok && defined($stat) &&
4707 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4709 my $test = substr($2, 1, -1);
4711 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4713 # avoid parentheses around potential macro args
4714 next if ($match =~ /^\s*\w+\s*$/);
4715 if (!defined($herectx)) {
4716 $herectx = $here . "\n";
4717 my $cnt = statement_rawlines($if_stat);
4718 for (my $n = 0; $n < $cnt; $n++) {
4719 my $rl = raw_line($linenr, $n);
4720 $herectx .= $rl . "\n";
4721 last if $rl =~ /^[ \+].*\{/;
4724 CHK("UNNECESSARY_PARENTHESES",
4725 "Unnecessary parentheses around '$match'\n" . $herectx);
4729 #goto labels aren't indented, allow a single space however
4730 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4731 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4732 if (WARN("INDENTED_LABEL",
4733 "labels should not be indented\n" . $herecurr) &&
4735 $fixed[$fixlinenr] =~
4740 # return is not a function
4741 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4743 if ($perl_version_ok &&
4744 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4746 $value = deparenthesize($value);
4747 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4748 ERROR("RETURN_PARENTHESES",
4749 "return is not a function, parentheses are not required\n" . $herecurr);
4751 } elsif ($spacing !~ /\s+/) {
4753 "space required before the open parenthesis '('\n" . $herecurr);
4757 # unnecessary return in a void function
4758 # at end-of-function, with the previous line a single leading tab, then return;
4759 # and the line before that not a goto label target like "out:"
4760 if ($sline =~ /^[ \+]}\s*$/ &&
4761 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4763 $lines[$linenr - 3] =~ /^[ +]/ &&
4764 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4766 "void function return statements are not generally useful\n" . $hereprev);
4769 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4770 if ($perl_version_ok &&
4771 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4772 my $openparens = $1;
4773 my $count = $openparens =~ tr@\(@\(@;
4775 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4776 my $comp = $4; #Not $1 because of $LvalOrFunc
4777 $msg = " - maybe == should be = ?" if ($comp eq "==");
4778 WARN("UNNECESSARY_PARENTHESES",
4779 "Unnecessary parentheses$msg\n" . $herecurr);
4783 # comparisons with a constant or upper case identifier on the left
4784 # avoid cases like "foo + BAR < baz"
4785 # only fix matches surrounded by parentheses to avoid incorrect
4786 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4787 if ($perl_version_ok &&
4788 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4793 my $newcomp = $comp;
4794 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4795 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4796 WARN("CONSTANT_COMPARISON",
4797 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4801 } elsif ($comp eq "<=") {
4803 } elsif ($comp eq ">") {
4805 } elsif ($comp eq ">=") {
4808 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4812 # Return of what appears to be an errno should normally be negative
4813 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4815 if ($name ne 'EOF' && $name ne 'ERROR') {
4816 WARN("USE_NEGATIVE_ERRNO",
4817 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4821 # Need a space before open parenthesis after if, while etc
4822 if ($line =~ /\b(if|while|for|switch)\(/) {
4823 if (ERROR("SPACING",
4824 "space required before the open parenthesis '('\n" . $herecurr) &&
4826 $fixed[$fixlinenr] =~
4827 s/\b(if|while|for|switch)\(/$1 \(/;
4831 # Check for illegal assignment in if conditional -- and check for trailing
4832 # statements after the conditional.
4833 if ($line =~ /do\s*(?!{)/) {
4834 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4835 ctx_statement_block($linenr, $realcnt, 0)
4836 if (!defined $stat);
4837 my ($stat_next) = ctx_statement_block($line_nr_next,
4838 $remain_next, $off_next);
4839 $stat_next =~ s/\n./\n /g;
4840 ##print "stat<$stat> stat_next<$stat_next>\n";
4842 if ($stat_next =~ /^\s*while\b/) {
4843 # If the statement carries leading newlines,
4844 # then count those as offsets.
4846 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4848 statement_rawlines($whitespace) - 1;
4850 $suppress_whiletrailers{$line_nr_next +
4854 if (!defined $suppress_whiletrailers{$linenr} &&
4855 defined($stat) && defined($cond) &&
4856 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4857 my ($s, $c) = ($stat, $cond);
4859 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4860 ERROR("ASSIGN_IN_IF",
4861 "do not use assignment in if condition\n" . $herecurr);
4864 # Find out what is on the end of the line after the
4866 substr($s, 0, length($c), '');
4868 $s =~ s/$;//g; # Remove any comments
4869 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4870 $c !~ /}\s*while\s*/)
4872 # Find out how long the conditional actually is.
4873 my @newlines = ($c =~ /\n/gs);
4874 my $cond_lines = 1 + $#newlines;
4877 $stat_real = raw_line($linenr, $cond_lines)
4878 . "\n" if ($cond_lines);
4879 if (defined($stat_real) && $cond_lines > 1) {
4880 $stat_real = "[...]\n$stat_real";
4883 ERROR("TRAILING_STATEMENTS",
4884 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4888 # Check for bitwise tests written as boolean
4900 WARN("HEXADECIMAL_BOOLEAN_TEST",
4901 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4904 # if and else should not have general statements after it
4905 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4907 $s =~ s/$;//g; # Remove any comments
4908 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4909 ERROR("TRAILING_STATEMENTS",
4910 "trailing statements should be on next line\n" . $herecurr);
4913 # if should not continue a brace
4914 if ($line =~ /}\s*if\b/) {
4915 ERROR("TRAILING_STATEMENTS",
4916 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4919 # case and default should not have general statements after them
4920 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4922 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4926 ERROR("TRAILING_STATEMENTS",
4927 "trailing statements should be on next line\n" . $herecurr);
4930 # Check for }<nl>else {, these must be at the same
4931 # indent level to be relevant to each other.
4932 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4933 $previndent == $indent) {
4934 if (ERROR("ELSE_AFTER_BRACE",
4935 "else should follow close brace '}'\n" . $hereprev) &&
4936 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4937 fix_delete_line($fixlinenr - 1, $prevrawline);
4938 fix_delete_line($fixlinenr, $rawline);
4939 my $fixedline = $prevrawline;
4940 $fixedline =~ s/}\s*$//;
4941 if ($fixedline !~ /^\+\s*$/) {
4942 fix_insert_line($fixlinenr, $fixedline);
4944 $fixedline = $rawline;
4945 $fixedline =~ s/^(.\s*)else/$1} else/;
4946 fix_insert_line($fixlinenr, $fixedline);
4950 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4951 $previndent == $indent) {
4952 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4954 # Find out what is on the end of the line after the
4956 substr($s, 0, length($c), '');
4959 if ($s =~ /^\s*;/) {
4960 if (ERROR("WHILE_AFTER_BRACE",
4961 "while should follow close brace '}'\n" . $hereprev) &&
4962 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4963 fix_delete_line($fixlinenr - 1, $prevrawline);
4964 fix_delete_line($fixlinenr, $rawline);
4965 my $fixedline = $prevrawline;
4966 my $trailing = $rawline;
4967 $trailing =~ s/^\+//;
4968 $trailing = trim($trailing);
4969 $fixedline =~ s/}\s*$/} $trailing/;
4970 fix_insert_line($fixlinenr, $fixedline);
4975 #Specific variable tests
4976 while ($line =~ m{($Constant|$Lval)}g) {
4979 #gcc binary extension
4980 if ($var =~ /^$Binary$/) {
4981 if (WARN("GCC_BINARY_CONSTANT",
4982 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4984 my $hexval = sprintf("0x%x", oct($var));
4985 $fixed[$fixlinenr] =~
4986 s/\b$var\b/$hexval/;
4991 if ($var !~ /^$Constant$/ &&
4992 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4993 #Ignore Page<foo> variants
4994 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4995 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4996 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4997 #Ignore some three character SI units explicitly, like MiB and KHz
4998 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4999 while ($var =~ m{($Ident)}g) {
5001 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5003 seed_camelcase_includes();
5004 if (!$file && !$camelcase_file_seeded) {
5005 seed_camelcase_file($realfile);
5006 $camelcase_file_seeded = 1;
5009 if (!defined $camelcase{$word}) {
5010 $camelcase{$word} = 1;
5012 "Avoid CamelCase: <$word>\n" . $herecurr);
5018 #no spaces allowed after \ in define
5019 if ($line =~ /\#\s*define.*\\\s+$/) {
5020 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5021 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5023 $fixed[$fixlinenr] =~ s/\s+$//;
5027 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5028 # itself <asm/foo.h> (uses RAW line)
5029 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5031 my $checkfile = "include/linux/$file";
5032 if (-f "$root/$checkfile" &&
5033 $realfile ne $checkfile &&
5034 $1 !~ /$allowed_asm_includes/)
5036 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5037 if ($asminclude > 0) {
5038 if ($realfile =~ m{^arch/}) {
5039 CHK("ARCH_INCLUDE_LINUX",
5040 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5042 WARN("INCLUDE_LINUX",
5043 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5049 # multi-statement macros should be enclosed in a do while loop, grab the
5050 # first statement and ensure its the whole macro if its not enclosed
5051 # in a known good container
5052 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5053 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5056 my ($off, $dstat, $dcond, $rest);
5058 my $has_flow_statement = 0;
5059 my $has_arg_concat = 0;
5060 ($dstat, $dcond, $ln, $cnt, $off) =
5061 ctx_statement_block($linenr, $realcnt, 0);
5063 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5064 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5066 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5067 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5069 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5070 my $define_args = $1;
5071 my $define_stmt = $dstat;
5074 if (defined $define_args && $define_args ne "") {
5075 $define_args = substr($define_args, 1, length($define_args) - 2);
5076 $define_args =~ s/\s*//g;
5077 $define_args =~ s/\\\+?//g;
5078 @def_args = split(",", $define_args);
5082 $dstat =~ s/\\\n.//g;
5083 $dstat =~ s/^\s*//s;
5084 $dstat =~ s/\s*$//s;
5086 # Flatten any parentheses and braces
5087 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5088 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5089 $dstat =~ s/.\[[^\[\]]*\]/1/)
5093 # Flatten any obvious string concatentation.
5094 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5095 $dstat =~ s/$Ident\s*($String)/$1/)
5099 # Make asm volatile uses seem like a generic function
5100 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5102 my $exceptions = qr{
5115 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5118 my $stmt_cnt = statement_rawlines($ctx);
5119 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5122 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5123 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5124 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5125 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5126 $dstat !~ /$exceptions/ &&
5127 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5128 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5129 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5130 $dstat !~ /^for\s*$Constant$/ && # for (...)
5131 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5132 $dstat !~ /^do\s*{/ && # do {...
5133 $dstat !~ /^\(\{/ && # ({...
5134 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5136 if ($dstat =~ /^\s*if\b/) {
5137 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5138 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5139 } elsif ($dstat =~ /;/) {
5140 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5141 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5143 ERROR("COMPLEX_MACRO",
5144 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5149 # Make $define_stmt single line, comment-free, etc
5150 my @stmt_array = split('\n', $define_stmt);
5153 foreach my $l (@stmt_array) {
5158 } elsif ($l =~ /^[\+ ]/) {
5159 $define_stmt .= substr($l, 1);
5162 $define_stmt =~ s/$;//g;
5163 $define_stmt =~ s/\s+/ /g;
5164 $define_stmt = trim($define_stmt);
5166 # check if any macro arguments are reused (ignore '...' and 'type')
5167 foreach my $arg (@def_args) {
5168 next if ($arg =~ /\.\.\./);
5169 next if ($arg =~ /^type$/i);
5170 my $tmp_stmt = $define_stmt;
5171 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5172 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5173 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5174 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5176 CHK("MACRO_ARG_REUSE",
5177 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5179 # check if any macro arguments may have other precedence issues
5180 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5181 ((defined($1) && $1 ne ',') ||
5182 (defined($2) && $2 ne ','))) {
5183 CHK("MACRO_ARG_PRECEDENCE",
5184 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5188 # check for macros with flow control, but without ## concatenation
5189 # ## concatenation is commonly a macro that defines a function so ignore those
5190 if ($has_flow_statement && !$has_arg_concat) {
5191 my $cnt = statement_rawlines($ctx);
5192 my $herectx = get_stat_here($linenr, $cnt, $here);
5194 WARN("MACRO_WITH_FLOW_CONTROL",
5195 "Macros with flow control statements should be avoided\n" . "$herectx");
5198 # check for line continuations outside of #defines, preprocessor #, and asm
5201 if ($prevline !~ /^..*\\$/ &&
5202 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5203 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5204 $line =~ /^\+.*\\$/) {
5205 WARN("LINE_CONTINUATIONS",
5206 "Avoid unnecessary line continuations\n" . $herecurr);
5210 # do {} while (0) macro tests:
5211 # single-statement macros do not need to be enclosed in do while (0) loop,
5212 # macro should not end with a semicolon
5213 if ($perl_version_ok &&
5214 $realfile !~ m@/vmlinux.lds.h$@ &&
5215 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5218 my ($off, $dstat, $dcond, $rest);
5220 ($dstat, $dcond, $ln, $cnt, $off) =
5221 ctx_statement_block($linenr, $realcnt, 0);
5224 $dstat =~ s/\\\n.//g;
5227 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5232 my $cnt = statement_rawlines($ctx);
5233 my $herectx = get_stat_here($linenr, $cnt, $here);
5235 if (($stmts =~ tr/;/;/) == 1 &&
5236 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5237 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5238 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5240 if (defined $semis && $semis ne "") {
5241 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5242 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5244 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5246 my $cnt = statement_rawlines($ctx);
5247 my $herectx = get_stat_here($linenr, $cnt, $here);
5249 WARN("TRAILING_SEMICOLON",
5250 "macros should not use a trailing semicolon\n" . "$herectx");
5254 # check for redundant bracing round if etc
5255 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5256 my ($level, $endln, @chunks) =
5257 ctx_statement_full($linenr, $realcnt, 1);
5258 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5259 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5260 if ($#chunks > 0 && $level == 0) {
5264 my $herectx = $here . "\n";
5265 my $ln = $linenr - 1;
5266 for my $chunk (@chunks) {
5267 my ($cond, $block) = @{$chunk};
5269 # If the condition carries leading newlines, then count those as offsets.
5270 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5271 my $offset = statement_rawlines($whitespace) - 1;
5273 $allowed[$allow] = 0;
5274 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5276 # We have looked at and allowed this specific line.
5277 $suppress_ifbraces{$ln + $offset} = 1;
5279 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5280 $ln += statement_rawlines($block) - 1;
5282 substr($block, 0, length($cond), '');
5284 $seen++ if ($block =~ /^\s*{/);
5286 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5287 if (statement_lines($cond) > 1) {
5288 #print "APW: ALLOWED: cond<$cond>\n";
5289 $allowed[$allow] = 1;
5291 if ($block =~/\b(?:if|for|while)\b/) {
5292 #print "APW: ALLOWED: block<$block>\n";
5293 $allowed[$allow] = 1;
5295 if (statement_block_size($block) > 1) {
5296 #print "APW: ALLOWED: lines block<$block>\n";
5297 $allowed[$allow] = 1;
5302 my $sum_allowed = 0;
5303 foreach (@allowed) {
5306 if ($sum_allowed == 0) {
5308 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5309 } elsif ($sum_allowed != $allow &&
5312 "braces {} should be used on all arms of this statement\n" . $herectx);
5317 if (!defined $suppress_ifbraces{$linenr - 1} &&
5318 $line =~ /\b(if|while|for|else)\b/) {
5321 # Check the pre-context.
5322 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5323 #print "APW: ALLOWED: pre<$1>\n";
5327 my ($level, $endln, @chunks) =
5328 ctx_statement_full($linenr, $realcnt, $-[0]);
5330 # Check the condition.
5331 my ($cond, $block) = @{$chunks[0]};
5332 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5333 if (defined $cond) {
5334 substr($block, 0, length($cond), '');
5336 if (statement_lines($cond) > 1) {
5337 #print "APW: ALLOWED: cond<$cond>\n";
5340 if ($block =~/\b(?:if|for|while)\b/) {
5341 #print "APW: ALLOWED: block<$block>\n";
5344 if (statement_block_size($block) > 1) {
5345 #print "APW: ALLOWED: lines block<$block>\n";
5348 # Check the post-context.
5349 if (defined $chunks[1]) {
5350 my ($cond, $block) = @{$chunks[1]};
5351 if (defined $cond) {
5352 substr($block, 0, length($cond), '');
5354 if ($block =~ /^\s*\{/) {
5355 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5359 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5360 my $cnt = statement_rawlines($block);
5361 my $herectx = get_stat_here($linenr, $cnt, $here);
5364 "braces {} are not necessary for single statement blocks\n" . $herectx);
5368 # check for single line unbalanced braces
5369 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5370 $sline =~ /^.\s*else\s*\{\s*$/) {
5371 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5374 # check for unnecessary blank lines around braces
5375 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5377 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5378 $fix && $prevrawline =~ /^\+/) {
5379 fix_delete_line($fixlinenr - 1, $prevrawline);
5382 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5384 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5386 fix_delete_line($fixlinenr, $rawline);
5390 # no volatiles please
5391 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5392 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5394 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5397 # Check for user-visible strings broken across lines, which breaks the ability
5398 # to grep for the string. Make exceptions when the previous string ends in a
5399 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5400 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5401 if ($line =~ /^\+\s*$String/ &&
5402 $prevline =~ /"\s*$/ &&
5403 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5404 if (WARN("SPLIT_STRING",
5405 "quoted string split across lines\n" . $hereprev) &&
5407 $prevrawline =~ /^\+.*"\s*$/ &&
5408 $last_coalesced_string_linenr != $linenr - 1) {
5409 my $extracted_string = get_quoted_string($line, $rawline);
5410 my $comma_close = "";
5411 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5415 fix_delete_line($fixlinenr - 1, $prevrawline);
5416 fix_delete_line($fixlinenr, $rawline);
5417 my $fixedline = $prevrawline;
5418 $fixedline =~ s/"\s*$//;
5419 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5420 fix_insert_line($fixlinenr - 1, $fixedline);
5421 $fixedline = $rawline;
5422 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5423 if ($fixedline !~ /\+\s*$/) {
5424 fix_insert_line($fixlinenr, $fixedline);
5426 $last_coalesced_string_linenr = $linenr;
5430 # check for missing a space in a string concatenation
5431 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5432 WARN('MISSING_SPACE',
5433 "break quoted strings at a space character\n" . $hereprev);
5436 # check for an embedded function name in a string when the function is known
5437 # This does not work very well for -f --file checking as it depends on patch
5438 # context providing the function name or a single line form for in-file
5439 # function declarations
5440 if ($line =~ /^\+.*$String/ &&
5441 defined($context_function) &&
5442 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5443 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5444 WARN("EMBEDDED_FUNCTION_NAME",
5445 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5448 # check for spaces before a quoted newline
5449 if ($rawline =~ /^.*\".*\s\\n/) {
5450 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5451 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5453 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5458 # concatenated string without spaces between elements
5459 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5460 if (CHK("CONCATENATED_STRING",
5461 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5463 while ($line =~ /($String)/g) {
5464 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5465 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5466 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5471 # uncoalesced string fragments
5472 if ($line =~ /$String\s*"/) {
5473 if (WARN("STRING_FRAGMENTS",
5474 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5476 while ($line =~ /($String)(?=\s*")/g) {
5477 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5478 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5483 # check for non-standard and hex prefixed decimal printf formats
5484 my $show_L = 1; #don't show the same defect twice
5486 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5487 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5488 $string =~ s/%%/__/g;
5490 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5492 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5496 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5498 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5501 # check for 0x<decimal>
5502 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5503 ERROR("PRINTF_0XDECIMAL",
5504 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5508 # check for line continuations in quoted strings with odd counts of "
5509 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5510 WARN("LINE_CONTINUATIONS",
5511 "Avoid line continuations in quoted strings\n" . $herecurr);
5515 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5517 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5521 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5523 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5526 # check for needless "if (<foo>) fn(<foo>)" uses
5527 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5528 my $tested = quotemeta($1);
5529 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5530 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5532 if (WARN('NEEDLESS_IF',
5533 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5536 my $leading_tabs = "";
5537 my $new_leading_tabs = "";
5538 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5543 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5544 $new_leading_tabs = $1;
5545 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5552 fix_delete_line($fixlinenr - 1, $prevrawline);
5553 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5559 # check for unnecessary "Out of Memory" messages
5560 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5561 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5562 (defined $1 || defined $3) &&
5565 my $testline = $lines[$linenr - 3];
5567 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5568 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5570 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)/) {
5572 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5576 # check for logging functions with KERN_<LEVEL>
5577 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5578 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5580 if (WARN("UNNECESSARY_KERN_LEVEL",
5581 "Possible unnecessary $level\n" . $herecurr) &&
5583 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5587 # check for logging continuations
5588 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5589 WARN("LOGGING_CONTINUATION",
5590 "Avoid logging continuation uses where feasible\n" . $herecurr);
5593 # check for mask then right shift without a parentheses
5594 if ($perl_version_ok &&
5595 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5596 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5597 WARN("MASK_THEN_SHIFT",
5598 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5601 # check for pointer comparisons to NULL
5602 if ($perl_version_ok) {
5603 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5606 $equal = "" if ($4 eq "!=");
5607 if (CHK("COMPARISON_TO_NULL",
5608 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5610 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5615 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5616 if ($line =~ /(\b$InitAttribute\b)/) {
5618 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5621 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5622 ERROR("MISPLACED_INIT",
5623 "$attr should be placed after $var\n" . $herecurr)) ||
5624 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5625 WARN("MISPLACED_INIT",
5626 "$attr should be placed after $var\n" . $herecurr))) &&
5628 $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;
5633 # check for $InitAttributeData (ie: __initdata) with const
5634 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5636 $attr =~ /($InitAttributePrefix)(.*)/;
5637 my $attr_prefix = $1;
5639 if (ERROR("INIT_ATTRIBUTE",
5640 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5642 $fixed[$fixlinenr] =~
5643 s/$InitAttributeData/${attr_prefix}initconst/;
5647 # check for $InitAttributeConst (ie: __initconst) without const
5648 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5650 if (ERROR("INIT_ATTRIBUTE",
5651 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5653 my $lead = $fixed[$fixlinenr] =~
5654 /(^\+\s*(?:static\s+))/;
5656 $lead = "$lead " if ($lead !~ /^\+$/);
5657 $lead = "${lead}const ";
5658 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5662 # check for __read_mostly with const non-pointer (should just be const)
5663 if ($line =~ /\b__read_mostly\b/ &&
5664 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5665 if (ERROR("CONST_READ_MOSTLY",
5666 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5668 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5672 # don't use __constant_<foo> functions outside of include/uapi/
5673 if ($realfile !~ m@^include/uapi/@ &&
5674 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5675 my $constant_func = $1;
5676 my $func = $constant_func;
5677 $func =~ s/^__constant_//;
5678 if (WARN("CONSTANT_CONVERSION",
5679 "$constant_func should be $func\n" . $herecurr) &&
5681 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5685 # prefer usleep_range over udelay
5686 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5688 # ignore udelay's < 10, however
5689 if (! ($delay < 10) ) {
5691 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5693 if ($delay > 2000) {
5695 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5699 # warn about unexpectedly long msleep's
5700 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5703 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5707 # check for comparisons of jiffies
5708 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5709 WARN("JIFFIES_COMPARISON",
5710 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5713 # check for comparisons of get_jiffies_64()
5714 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5715 WARN("JIFFIES_COMPARISON",
5716 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5719 # warn about #ifdefs in C files
5720 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5721 # print "#ifdef in C files should be avoided\n";
5722 # print "$herecurr";
5726 # warn about spacing in #ifdefs
5727 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5728 if (ERROR("SPACING",
5729 "exactly one space required after that #$1\n" . $herecurr) &&
5731 $fixed[$fixlinenr] =~
5732 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5737 # check for spinlock_t definitions without a comment.
5738 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5739 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5741 if (!ctx_has_comment($first_line, $linenr)) {
5742 CHK("UNCOMMENTED_DEFINITION",
5743 "$1 definition without comment\n" . $herecurr);
5746 # check for memory barriers without a comment.
5752 read_barrier_depends
5754 my $barrier_stems = qr{
5762 my $all_barriers = qr{
5764 smp_(?:$barrier_stems)|
5765 virt_(?:$barrier_stems)
5768 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5769 if (!ctx_has_comment($first_line, $linenr)) {
5770 WARN("MEMORY_BARRIER",
5771 "memory barrier without comment\n" . $herecurr);
5775 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5777 if ($realfile !~ m@^include/asm-generic/@ &&
5778 $realfile !~ m@/barrier\.h$@ &&
5779 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5780 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5781 WARN("MEMORY_BARRIER",
5782 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5785 # check for waitqueue_active without a comment.
5786 if ($line =~ /\bwaitqueue_active\s*\(/) {
5787 if (!ctx_has_comment($first_line, $linenr)) {
5788 WARN("WAITQUEUE_ACTIVE",
5789 "waitqueue_active without comment\n" . $herecurr);
5793 # check for smp_read_barrier_depends and read_barrier_depends
5794 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5795 WARN("READ_BARRIER_DEPENDS",
5796 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5799 # check of hardware specific defines
5800 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5802 "architecture specific defines should be avoided\n" . $herecurr);
5805 # check that the storage class is not after a type
5806 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5807 WARN("STORAGE_CLASS",
5808 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5810 # Check that the storage class is at the beginning of a declaration
5811 if ($line =~ /\b$Storage\b/ &&
5812 $line !~ /^.\s*$Storage/ &&
5813 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5814 $1 !~ /[\,\)]\s*$/) {
5815 WARN("STORAGE_CLASS",
5816 "storage class should be at the beginning of the declaration\n" . $herecurr);
5819 # check the location of the inline attribute, that it is between
5820 # storage class and type.
5821 if ($line =~ /\b$Type\s+$Inline\b/ ||
5822 $line =~ /\b$Inline\s+$Storage\b/) {
5823 ERROR("INLINE_LOCATION",
5824 "inline keyword should sit between storage class and type\n" . $herecurr);
5827 # Check for __inline__ and __inline, prefer inline
5828 if ($realfile !~ m@\binclude/uapi/@ &&
5829 $line =~ /\b(__inline__|__inline)\b/) {
5831 "plain inline is preferred over $1\n" . $herecurr) &&
5833 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5838 # Check for __attribute__ packed, prefer __packed
5839 if ($realfile !~ m@\binclude/uapi/@ &&
5840 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5841 WARN("PREFER_PACKED",
5842 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5845 # Check for __attribute__ aligned, prefer __aligned
5846 if ($realfile !~ m@\binclude/uapi/@ &&
5847 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5848 WARN("PREFER_ALIGNED",
5849 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5852 # Check for __attribute__ format(printf, prefer __printf
5853 if ($realfile !~ m@\binclude/uapi/@ &&
5854 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5855 if (WARN("PREFER_PRINTF",
5856 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5858 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5863 # Check for __attribute__ format(scanf, prefer __scanf
5864 if ($realfile !~ m@\binclude/uapi/@ &&
5865 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5866 if (WARN("PREFER_SCANF",
5867 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5869 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5873 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5874 if ($perl_version_ok &&
5875 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5876 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5877 $line =~ /\b__weak\b/)) {
5878 ERROR("WEAK_DECLARATION",
5879 "Using weak declarations can have unintended link defects\n" . $herecurr);
5882 # check for c99 types like uint8_t used outside of uapi/ and tools/
5883 if ($realfile !~ m@\binclude/uapi/@ &&
5884 $realfile !~ m@\btools/@ &&
5885 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5887 if ($type =~ /\b($typeC99Typedefs)\b/) {
5889 my $kernel_type = 'u';
5890 $kernel_type = 's' if ($type =~ /^_*[si]/);
5893 if (CHK("PREFER_KERNEL_TYPES",
5894 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5896 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5901 # check for cast of C90 native int or longer types constants
5902 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5905 if (WARN("TYPECAST_INT_CONSTANT",
5906 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5909 my $newconst = $const;
5910 $newconst =~ s/${Int_type}$//;
5911 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5912 if ($cast =~ /\blong\s+long\b/) {
5914 } elsif ($cast =~ /\blong\b/) {
5917 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5921 # check for sizeof(&)
5922 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5923 WARN("SIZEOF_ADDRESS",
5924 "sizeof(& should be avoided\n" . $herecurr);
5927 # check for sizeof without parenthesis
5928 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5929 if (WARN("SIZEOF_PARENTHESIS",
5930 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5932 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5936 # check for struct spinlock declarations
5937 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5938 WARN("USE_SPINLOCK_T",
5939 "struct spinlock should be spinlock_t\n" . $herecurr);
5942 # check for seq_printf uses that could be seq_puts
5943 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5944 my $fmt = get_quoted_string($line, $rawline);
5947 if (WARN("PREFER_SEQ_PUTS",
5948 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5950 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5955 # check for vsprintf extension %p<foo> misuses
5956 if ($perl_version_ok &&
5958 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5959 $1 !~ /^_*volatile_*$/) {
5962 my $lc = $stat =~ tr@\n@@;
5963 $lc = $lc + $linenr;
5964 for (my $count = $linenr; $count <= $lc; $count++) {
5967 my $bad_specifier = "";
5968 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5971 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5974 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5975 $bad_specifier = $specifier;
5978 if ($extension eq "x" && !defined($stat_real)) {
5979 if (!defined($stat_real)) {
5980 $stat_real = get_stat_real($linenr, $lc);
5982 WARN("VSPRINTF_SPECIFIER_PX",
5983 "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");
5986 if ($bad_specifier ne "") {
5987 my $stat_real = get_stat_real($linenr, $lc);
5988 my $ext_type = "Invalid";
5990 if ($bad_specifier =~ /p[Ff]/) {
5991 $ext_type = "Deprecated";
5992 $use = " - use %pS instead";
5993 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5996 WARN("VSPRINTF_POINTER_EXTENSION",
5997 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6002 # Check for misused memsets
6003 if ($perl_version_ok &&
6005 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6011 if ($ms_size =~ /^(0x|)0$/i) {
6013 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6014 } elsif ($ms_size =~ /^(0x|)1$/i) {
6016 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6020 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6021 # if ($perl_version_ok &&
6023 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6024 # if (WARN("PREFER_ETHER_ADDR_COPY",
6025 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6027 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6031 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6032 # if ($perl_version_ok &&
6034 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6035 # WARN("PREFER_ETHER_ADDR_EQUAL",
6036 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6039 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6040 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6041 # if ($perl_version_ok &&
6043 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6047 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6048 # if (WARN("PREFER_ETH_ZERO_ADDR",
6049 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6051 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6053 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6054 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6055 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6057 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6062 # typecasts on min/max could be min_t/max_t
6063 if ($perl_version_ok &&
6065 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6066 if (defined $2 || defined $7) {
6068 my $cast1 = deparenthesize($2);
6070 my $cast2 = deparenthesize($7);
6074 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6075 $cast = "$cast1 or $cast2";
6076 } elsif ($cast1 ne "") {
6082 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6086 # check usleep_range arguments
6087 if ($perl_version_ok &&
6089 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6093 WARN("USLEEP_RANGE",
6094 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6095 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6097 WARN("USLEEP_RANGE",
6098 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6102 # check for naked sscanf
6103 if ($perl_version_ok &&
6105 $line =~ /\bsscanf\b/ &&
6106 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6107 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6108 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6109 my $lc = $stat =~ tr@\n@@;
6110 $lc = $lc + $linenr;
6111 my $stat_real = get_stat_real($linenr, $lc);
6112 WARN("NAKED_SSCANF",
6113 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6116 # check for simple sscanf that should be kstrto<foo>
6117 if ($perl_version_ok &&
6119 $line =~ /\bsscanf\b/) {
6120 my $lc = $stat =~ tr@\n@@;
6121 $lc = $lc + $linenr;
6122 my $stat_real = get_stat_real($linenr, $lc);
6123 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6125 my $count = $format =~ tr@%@%@;
6127 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6128 WARN("SSCANF_TO_KSTRTO",
6129 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6134 # check for new externs in .h files.
6135 if ($realfile =~ /\.h$/ &&
6136 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6137 if (CHK("AVOID_EXTERNS",
6138 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6140 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6144 # check for new externs in .c files.
6145 if ($realfile =~ /\.c$/ && defined $stat &&
6146 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6148 my $function_name = $1;
6149 my $paren_space = $2;
6152 if (defined $cond) {
6153 substr($s, 0, length($cond), '');
6155 if ($s =~ /^\s*;/ &&
6156 $function_name ne 'uninitialized_var')
6158 WARN("AVOID_EXTERNS",
6159 "externs should be avoided in .c files\n" . $herecurr);
6162 if ($paren_space =~ /\n/) {
6163 WARN("FUNCTION_ARGUMENTS",
6164 "arguments for function declarations should follow identifier\n" . $herecurr);
6167 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6168 $stat =~ /^.\s*extern\s+/)
6170 WARN("AVOID_EXTERNS",
6171 "externs should be avoided in .c files\n" . $herecurr);
6174 # check for function declarations that have arguments without identifier names
6175 if (defined $stat &&
6176 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6178 my $args = trim($1);
6179 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6181 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6182 WARN("FUNCTION_ARGUMENTS",
6183 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6188 # check for function definitions
6189 if ($perl_version_ok &&
6191 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6192 $context_function = $1;
6194 # check for multiline function definition with misplaced open brace
6196 my $cnt = statement_rawlines($stat);
6197 my $herectx = $here . "\n";
6198 for (my $n = 0; $n < $cnt; $n++) {
6199 my $rl = raw_line($linenr, $n);
6200 $herectx .= $rl . "\n";
6201 $ok = 1 if ($rl =~ /^[ \+]\{/);
6202 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6203 last if $rl =~ /^[ \+].*\{/;
6207 "open brace '{' following function definitions go on the next line\n" . $herectx);
6211 # checks for new __setup's
6212 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6215 if (!grep(/$name/, @setup_docs)) {
6216 CHK("UNDOCUMENTED_SETUP",
6217 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6221 # check for pointless casting of kmalloc return
6222 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6223 WARN("UNNECESSARY_CASTS",
6224 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6228 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6229 if ($perl_version_ok &&
6230 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6231 CHK("ALLOC_SIZEOF_STRUCT",
6232 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6235 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6236 if ($perl_version_ok &&
6238 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6242 my $newfunc = "kmalloc_array";
6243 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6246 if ($a1 =~ /^sizeof\s*\S/) {
6250 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6251 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6252 my $cnt = statement_rawlines($stat);
6253 my $herectx = get_stat_here($linenr, $cnt, $here);
6255 if (WARN("ALLOC_WITH_MULTIPLY",
6256 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6259 $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;
6264 # check for krealloc arg reuse
6265 if ($perl_version_ok &&
6266 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6268 WARN("KREALLOC_ARG_REUSE",
6269 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6272 # check for alloc argument mismatch
6273 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6274 WARN("ALLOC_ARRAY_ARGS",
6275 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6278 # check for multiple semicolons
6279 if ($line =~ /;\s*;\s*$/) {
6280 if (WARN("ONE_SEMICOLON",
6281 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6283 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6287 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6288 if ($realfile !~ m@^include/uapi/@ &&
6289 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6291 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6292 if (CHK("BIT_MACRO",
6293 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6295 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6299 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6300 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6302 if (WARN("PREFER_IS_ENABLED",
6303 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6305 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6309 # check for case / default statements not preceded by break/fallthrough/switch
6310 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6312 my $has_statement = 0;
6314 my $prevline = $linenr;
6315 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6317 my $rline = $rawlines[$prevline - 1];
6318 my $fline = $lines[$prevline - 1];
6319 last if ($fline =~ /^\@\@/);
6320 next if ($fline =~ /^\-/);
6321 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6322 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6323 next if ($fline =~ /^.[\s$;]*$/);
6326 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6328 if (!$has_break && $has_statement) {
6329 WARN("MISSING_BREAK",
6330 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6334 # check for switch/default statements without a break;
6335 if ($perl_version_ok &&
6337 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6338 my $cnt = statement_rawlines($stat);
6339 my $herectx = get_stat_here($linenr, $cnt, $here);
6341 WARN("DEFAULT_NO_BREAK",
6342 "switch default: should use break\n" . $herectx);
6345 # check for gcc specific __FUNCTION__
6346 if ($line =~ /\b__FUNCTION__\b/) {
6347 if (WARN("USE_FUNC",
6348 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6350 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6354 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6355 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6357 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6360 # check for use of yield()
6361 if ($line =~ /\byield\s*\(\s*\)/) {
6363 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6366 # check for comparisons against true and false
6367 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6375 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6377 my $type = lc($otype);
6378 if ($type =~ /^(?:true|false)$/) {
6379 if (("$test" eq "==" && "$type" eq "true") ||
6380 ("$test" eq "!=" && "$type" eq "false")) {
6384 CHK("BOOL_COMPARISON",
6385 "Using comparison to $otype is error prone\n" . $herecurr);
6387 ## maybe suggesting a correct construct would better
6388 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6393 # check for bool bitfields
6394 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6395 WARN("BOOL_BITFIELD",
6396 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6399 # check for bool use in .h files
6400 if ($realfile =~ /\.h$/ &&
6401 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6403 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6406 # check for semaphores initialized locked
6407 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6408 WARN("CONSIDER_COMPLETION",
6409 "consider using a completion\n" . $herecurr);
6412 # recommend kstrto* over simple_strto* and strict_strto*
6413 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6414 WARN("CONSIDER_KSTRTO",
6415 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6418 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6419 if ($line =~ /^.\s*__initcall\s*\(/) {
6420 WARN("USE_DEVICE_INITCALL",
6421 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6424 # check for various structs that are normally const (ops, kgdb, device_tree)
6425 # and avoid what seem like struct definitions 'struct foo {'
6426 if ($line !~ /\bconst\b/ &&
6427 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6428 WARN("CONST_STRUCT",
6429 "struct $1 should normally be const\n" . $herecurr);
6432 # use of NR_CPUS is usually wrong
6433 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6434 if ($line =~ /\bNR_CPUS\b/ &&
6435 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6436 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6437 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6438 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6439 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6442 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6445 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6446 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6447 ERROR("DEFINE_ARCH_HAS",
6448 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6451 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6452 if ($perl_version_ok &&
6453 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6454 WARN("LIKELY_MISUSE",
6455 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6458 # whine mightly about in_atomic
6459 if ($line =~ /\bin_atomic\s*\(/) {
6460 if ($realfile =~ m@^drivers/@) {
6462 "do not use in_atomic in drivers\n" . $herecurr);
6463 } elsif ($realfile !~ m@^kernel/@) {
6465 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6469 # check for mutex_trylock_recursive usage
6470 if ($line =~ /mutex_trylock_recursive/) {
6472 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6475 # check for lockdep_set_novalidate_class
6476 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6477 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6478 if ($realfile !~ m@^kernel/lockdep@ &&
6479 $realfile !~ m@^include/linux/lockdep@ &&
6480 $realfile !~ m@^drivers/base/core@) {
6482 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6486 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6487 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6488 WARN("EXPORTED_WORLD_WRITABLE",
6489 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6492 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6493 # and whether or not function naming is typical and if
6494 # DEVICE_ATTR permissions uses are unusual too
6495 if ($perl_version_ok &&
6497 $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*\)/) {
6502 my $octal_perms = perms_to_octal($perms);
6503 if ($show =~ /^${var}_show$/ &&
6504 $store =~ /^${var}_store$/ &&
6505 $octal_perms eq "0644") {
6506 if (WARN("DEVICE_ATTR_RW",
6507 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6509 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6511 } elsif ($show =~ /^${var}_show$/ &&
6512 $store =~ /^NULL$/ &&
6513 $octal_perms eq "0444") {
6514 if (WARN("DEVICE_ATTR_RO",
6515 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6517 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6519 } elsif ($show =~ /^NULL$/ &&
6520 $store =~ /^${var}_store$/ &&
6521 $octal_perms eq "0200") {
6522 if (WARN("DEVICE_ATTR_WO",
6523 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6525 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6527 } elsif ($octal_perms eq "0644" ||
6528 $octal_perms eq "0444" ||
6529 $octal_perms eq "0200") {
6530 my $newshow = "$show";
6531 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6532 my $newstore = $store;
6533 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6535 if ($show ne $newshow) {
6536 $rename .= " '$show' to '$newshow'";
6538 if ($store ne $newstore) {
6539 $rename .= " '$store' to '$newstore'";
6541 WARN("DEVICE_ATTR_FUNCTIONS",
6542 "Consider renaming function(s)$rename\n" . $herecurr);
6544 WARN("DEVICE_ATTR_PERMS",
6545 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6549 # Mode permission misuses where it seems decimal should be octal
6550 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6551 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6552 # specific definition of not visible in sysfs.
6553 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6554 # use the default permissions
6555 if ($perl_version_ok &&
6557 $line =~ /$mode_perms_search/) {
6558 foreach my $entry (@mode_permission_funcs) {
6559 my $func = $entry->[0];
6560 my $arg_pos = $entry->[1];
6562 my $lc = $stat =~ tr@\n@@;
6563 $lc = $lc + $linenr;
6564 my $stat_real = get_stat_real($linenr, $lc);
6569 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6571 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6572 if ($stat =~ /$test/) {
6574 $val = $6 if ($skip_args ne "");
6575 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6576 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6577 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6578 ERROR("NON_OCTAL_PERMISSIONS",
6579 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6581 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6582 ERROR("EXPORTED_WORLD_WRITABLE",
6583 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6589 # check for uses of S_<PERMS> that could be octal for readability
6590 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6592 my $octal = perms_to_octal($oval);
6593 if (WARN("SYMBOLIC_PERMS",
6594 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6596 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6600 # validate content of MODULE_LICENSE against list from include/linux/module.h
6601 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6602 my $extracted_string = get_quoted_string($line, $rawline);
6603 my $valid_licenses = qr{
6606 GPL\ and\ additional\ rights|
6612 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6613 WARN("MODULE_LICENSE",
6614 "unknown module license " . $extracted_string . "\n" . $herecurr);
6619 # If we have no input at all, then there is nothing to report on
6620 # so just keep quiet.
6621 if ($#rawlines == -1) {
6625 # In mailback mode only produce a report in the negative, for
6626 # things that appear to be patches.
6627 if ($mailback && ($clean == 1 || !$is_patch)) {
6631 # This is not a patch, and we are are in 'no-patch' mode so
6633 if (!$chk_patch && !$is_patch) {
6637 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6638 ERROR("NOT_UNIFIED_DIFF",
6639 "Does not appear to be a unified-diff format patch\n");
6641 if ($is_patch && $has_commit_log && $chk_signoff) {
6642 if ($signoff == 0) {
6643 ERROR("MISSING_SIGN_OFF",
6644 "Missing Signed-off-by: line(s)\n");
6645 } elsif (!$authorsignoff) {
6646 WARN("NO_AUTHOR_SIGN_OFF",
6647 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6651 print report_dump();
6652 if ($summary && !($clean == 1 && $quiet == 1)) {
6653 print "$filename " if ($summary_file);
6654 print "total: $cnt_error errors, $cnt_warn warnings, " .
6655 (($check)? "$cnt_chk checks, " : "") .
6656 "$cnt_lines lines checked\n";
6660 # If there were any defects found and not already fixing them
6661 if (!$clean and !$fix) {
6664 NOTE: For some of the reported defects, checkpatch may be able to
6665 mechanically convert to the typical style using --fix or --fix-inplace.
6668 # If there were whitespace errors which cleanpatch can fix
6669 # then suggest that.
6670 if ($rpt_cleaners) {
6674 NOTE: Whitespace errors detected.
6675 You may wish to use scripts/cleanpatch or scripts/cleanfile
6680 if ($clean == 0 && $fix &&
6681 ("@rawlines" ne "@fixed" ||
6682 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6683 my $newfile = $filename;
6684 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6688 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6690 open($f, '>', $newfile)
6691 or die "$P: Can't open $newfile for write\n";
6692 foreach my $fixed_line (@fixed) {
6695 if ($linecount > 3) {
6696 $fixed_line =~ s/^\+//;
6697 print $f $fixed_line . "\n";
6700 print $f $fixed_line . "\n";
6708 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6710 Do _NOT_ trust the results written to this file.
6711 Do _NOT_ submit these changes without inspecting them for correctness.
6713 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6714 No warranties, expressed or implied...
6722 print "$vname has no obvious style problems and is ready for submission.\n";
6724 print "$vname has style problems, please review.\n";