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 = 80;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile = "";
64 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
65 # git output parsing needs US English output, so first set backtick child process LANGUAGE
66 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
73 Usage: $P [OPTION]... [FILE]...
78 --no-tree run without a kernel tree
79 --no-signoff do not check for 'Signed-off-by' line
80 --patch treat FILE as patchfile (default)
81 --emacs emacs compile window format
82 --terse one line per report
83 --showfile emit diffed file position, not input file position
84 -g, --git treat FILE as a single commit or git revision range
85 single git commit with:
89 multiple git commits with:
93 git merges are ignored
94 -f, --file treat FILE as regular source file
95 --subjective, --strict enable more subjective tests
96 --list-types list the possible message types
97 --types TYPE(,TYPE2...) show only these comma separated message types
98 --ignore TYPE(,TYPE2...) ignore various comma separated message types
99 --show-types show the specific message type in the output
100 --max-line-length=n set the maximum line length, if exceeded, warn
101 --min-conf-desc-length=n set the min description length, if shorter, warn
102 --tab-size=n set the number of spaces for tab (default 8)
103 --root=PATH PATH to the kernel tree root
104 --no-summary suppress the per-file summary
105 --mailback only produce a report in case of warnings/errors
106 --summary-file include the filename in summary
107 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
108 'values', 'possible', 'type', and 'attr' (default
110 --test-only=WORD report only warnings/errors containing WORD
112 --fix EXPERIMENTAL - may create horrible results
113 If correctable single-line errors exist, create
114 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
115 with potential errors corrected to the preferred
117 --fix-inplace EXPERIMENTAL - may create horrible results
118 Is the same as --fix, but overwrites the input
119 file. It's your fault if there's no backup or git
120 --ignore-perl-version override checking of perl version. expect
122 --codespell Use the codespell dictionary for spelling/typos
123 (default:/usr/share/codespell/dictionary.txt)
124 --codespellfile Use this codespell dictionary
125 --typedefsfile Read additional types from this file
126 --color[=WHEN] Use colors 'always', 'never', or only when output
127 is a terminal ('auto'). Default is 'auto'.
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,
220 'tab-size=i' => \$tabsize,
222 'summary!' => \$summary,
223 'mailback!' => \$mailback,
224 'summary-file!' => \$summary_file,
226 'fix-inplace!' => \$fix_inplace,
227 'ignore-perl-version!' => \$ignore_perl_version,
228 'debug=s' => \%debug,
229 'test-only=s' => \$tst_only,
230 'codespell!' => \$codespell,
231 'codespellfile=s' => \$codespellfile,
232 'typedefsfile=s' => \$typedefsfile,
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 # skip TAB size 1 to avoid additional checks on $tabsize - 1
274 die "Invalid TAB size: $tabsize\n" if ($tabsize < 2);
276 sub hash_save_array_words {
277 my ($hashRef, $arrayRef) = @_;
279 my @array = split(/,/, join(',', @$arrayRef));
280 foreach my $word (@array) {
281 $word =~ s/\s*\n?$//g;
284 $word =~ tr/[a-z]/[A-Z]/;
286 next if ($word =~ m/^\s*#/);
287 next if ($word =~ m/^\s*$/);
293 sub hash_show_words {
294 my ($hashRef, $prefix) = @_;
296 if (keys %$hashRef) {
297 print "\nNOTE: $prefix message types:";
298 foreach my $word (sort keys %$hashRef) {
305 hash_save_array_words(\%ignore_type, \@ignore);
306 hash_save_array_words(\%use_type, \@use);
309 my $dbg_possible = 0;
312 for my $key (keys %debug) {
314 eval "\${dbg_$key} = '$debug{$key}';";
318 my $rpt_cleaners = 0;
327 if (!top_of_kernel_tree($root)) {
328 die "$P: $root: --root does not point at a valid tree\n";
331 if (top_of_kernel_tree('.')) {
333 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
334 top_of_kernel_tree($1)) {
339 if (!defined $root) {
340 print "Must be run from the top-level dir. of a kernel tree\n";
345 my $emitted_corrupt = 0;
348 [A-Za-z_][A-Za-z\d_]*
349 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
351 our $Storage = qr{extern|static|asmlinkage};
365 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
366 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
367 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
368 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
369 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
371 # Notes to $Attribute:
372 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
394 ____cacheline_aligned|
395 ____cacheline_aligned_in_smp|
396 ____cacheline_internodealigned_in_smp|
400 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
401 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
402 our $Lval = qr{$Ident(?:$Member)*};
404 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
405 our $Binary = qr{(?i)0b[01]+$Int_type?};
406 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
407 our $Int = qr{[0-9]+$Int_type?};
408 our $Octal = qr{0[0-7]+$Int_type?};
409 our $String = qr{"[X\t]*"};
410 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
411 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
412 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
413 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
414 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
415 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
416 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
417 our $Arithmetic = qr{\+|-|\*|\/|%};
421 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
424 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
428 our $NonptrTypeMisordered;
429 our $NonptrTypeWithAttr;
433 our $DeclareMisordered;
435 our $NON_ASCII_UTF8 = qr{
436 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
437 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
438 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
439 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
440 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
441 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
442 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
446 [\x09\x0A\x0D\x20-\x7E] # ASCII
450 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
451 our $typeOtherOSTypedefs = qr{(?x:
452 u_(?:char|short|int|long) | # bsd
453 u(?:nchar|short|int|long) # sysv
455 our $typeKernelTypedefs = qr{(?x:
456 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
459 our $typeTypedefs = qr{(?x:
461 $typeOtherOSTypedefs\b|
462 $typeKernelTypedefs\b
465 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
467 our $logFunctions = qr{(?x:
468 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
469 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
471 WARN(?:_RATELIMIT|_ONCE|)|
474 seq_vprintf|seq_printf|seq_puts
477 our $allocFunctions = qr{(?x:
479 (?:kv|k|v)[czm]alloc(?:_node|_array)? |
482 (?:\w+)?alloc_skb(?:_ip_align)? |
483 # dev_alloc_skb/netdev_alloc_skb, et al
487 our $signature_tags = qr{(?xi:
499 our @typeListMisordered = (
500 qr{char\s+(?:un)?signed},
501 qr{int\s+(?:(?:un)?signed\s+)?short\s},
502 qr{int\s+short(?:\s+(?:un)?signed)},
503 qr{short\s+int(?:\s+(?:un)?signed)},
504 qr{(?:un)?signed\s+int\s+short},
505 qr{short\s+(?:un)?signed},
506 qr{long\s+int\s+(?:un)?signed},
507 qr{int\s+long\s+(?:un)?signed},
508 qr{long\s+(?:un)?signed\s+int},
509 qr{int\s+(?:un)?signed\s+long},
510 qr{int\s+(?:un)?signed},
511 qr{int\s+long\s+long\s+(?:un)?signed},
512 qr{long\s+long\s+int\s+(?:un)?signed},
513 qr{long\s+long\s+(?:un)?signed\s+int},
514 qr{long\s+long\s+(?:un)?signed},
515 qr{long\s+(?:un)?signed},
520 qr{(?:(?:un)?signed\s+)?char},
521 qr{(?:(?:un)?signed\s+)?short\s+int},
522 qr{(?:(?:un)?signed\s+)?short},
523 qr{(?:(?:un)?signed\s+)?int},
524 qr{(?:(?:un)?signed\s+)?long\s+int},
525 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
526 qr{(?:(?:un)?signed\s+)?long\s+long},
527 qr{(?:(?:un)?signed\s+)?long},
536 qr{${Ident}_handler},
537 qr{${Ident}_handler_fn},
541 our $C90_int_types = qr{(?x:
542 long\s+long\s+int\s+(?:un)?signed|
543 long\s+long\s+(?:un)?signed\s+int|
544 long\s+long\s+(?:un)?signed|
545 (?:(?:un)?signed\s+)?long\s+long\s+int|
546 (?:(?:un)?signed\s+)?long\s+long|
547 int\s+long\s+long\s+(?:un)?signed|
548 int\s+(?:(?:un)?signed\s+)?long\s+long|
550 long\s+int\s+(?:un)?signed|
551 long\s+(?:un)?signed\s+int|
552 long\s+(?:un)?signed|
553 (?:(?:un)?signed\s+)?long\s+int|
554 (?:(?:un)?signed\s+)?long|
555 int\s+long\s+(?:un)?signed|
556 int\s+(?:(?:un)?signed\s+)?long|
559 (?:(?:un)?signed\s+)?int
562 our @typeListFile = ();
563 our @typeListWithAttr = (
565 qr{struct\s+$InitAttribute\s+$Ident},
566 qr{union\s+$InitAttribute\s+$Ident},
569 our @modifierList = (
572 our @modifierListFile = ();
574 our @mode_permission_funcs = (
576 ["module_param_(?:array|named|string)", 4],
577 ["module_param_array_named", 5],
578 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
579 ["proc_create(?:_data|)", 2],
580 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
581 ["IIO_DEV_ATTR_[A-Z_]+", 1],
582 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
583 ["SENSOR_TEMPLATE(?:_2|)", 3],
587 #Create a search pattern for all these functions to speed up a loop below
588 our $mode_perms_search = "";
589 foreach my $entry (@mode_permission_funcs) {
590 $mode_perms_search .= '|' if ($mode_perms_search ne "");
591 $mode_perms_search .= $entry->[0];
593 $mode_perms_search = "(?:${mode_perms_search})";
595 our %deprecated_apis = (
596 "synchronize_rcu_bh" => "synchronize_rcu",
597 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
598 "call_rcu_bh" => "call_rcu",
599 "rcu_barrier_bh" => "rcu_barrier",
600 "synchronize_sched" => "synchronize_rcu",
601 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
602 "call_rcu_sched" => "call_rcu",
603 "rcu_barrier_sched" => "rcu_barrier",
604 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
605 "cond_synchronize_sched" => "cond_synchronize_rcu",
608 #Create a search pattern for all these strings to speed up a loop below
609 our $deprecated_apis_search = "";
610 foreach my $entry (keys %deprecated_apis) {
611 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
612 $deprecated_apis_search .= $entry;
614 $deprecated_apis_search = "(?:${deprecated_apis_search})";
616 our $mode_perms_world_writable = qr{
624 our %mode_permission_string_types = (
643 #Create a search pattern for all these strings to speed up a loop below
644 our $mode_perms_string_search = "";
645 foreach my $entry (keys %mode_permission_string_types) {
646 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
647 $mode_perms_string_search .= $entry;
649 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
650 our $multi_mode_perms_string_search = qr{
651 ${single_mode_perms_string_search}
652 (?:\s*\|\s*${single_mode_perms_string_search})*
658 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
665 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
666 $curpos = pos($string);
669 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
671 $to |= $mode_permission_string_types{$match};
672 $val .= '\s*\|\s*' if ($val ne "");
676 $oval =~ s/^\s*\|\s*//;
677 $oval =~ s/\s*\|\s*$//;
678 return sprintf("%04o", $to);
681 our $allowed_asm_includes = qr{(?x:
687 # memory.h: ARM has a custom one
689 # Load common spelling mistakes and build regular expression list.
693 if (open(my $spelling, '<', $spelling_file)) {
694 while (<$spelling>) {
697 $line =~ s/\s*\n?$//g;
700 next if ($line =~ m/^\s*#/);
701 next if ($line =~ m/^\s*$/);
703 my ($suspect, $fix) = split(/\|\|/, $line);
705 $spelling_fix{$suspect} = $fix;
709 warn "No typos will be found - file '$spelling_file': $!\n";
713 if (open(my $spelling, '<', $codespellfile)) {
714 while (<$spelling>) {
717 $line =~ s/\s*\n?$//g;
720 next if ($line =~ m/^\s*#/);
721 next if ($line =~ m/^\s*$/);
722 next if ($line =~ m/, disabled/i);
726 my ($suspect, $fix) = split(/->/, $line);
728 $spelling_fix{$suspect} = $fix;
732 warn "No codespell typos will be found - file '$codespellfile': $!\n";
736 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
739 my ($wordsRef, $file) = @_;
741 if (open(my $words, '<', $file)) {
745 $line =~ s/\s*\n?$//g;
748 next if ($line =~ m/^\s*#/);
749 next if ($line =~ m/^\s*$/);
751 print("$file: '$line' invalid - ignored\n");
755 $$wordsRef .= '|' if ($$wordsRef ne "");
765 my $const_structs = "";
766 read_words(\$const_structs, $conststructsfile)
767 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
769 my $typeOtherTypedefs = "";
770 if (length($typedefsfile)) {
771 read_words(\$typeOtherTypedefs, $typedefsfile)
772 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
774 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
777 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
778 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
779 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
780 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
781 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
787 (?:$Modifier\s+|const\s+)*
789 (?:typeof|__typeof__)\s*\([^\)]*\)|
793 (?:\s+$Modifier|\s+const)*
795 $NonptrTypeMisordered = qr{
796 (?:$Modifier\s+|const\s+)*
800 (?:\s+$Modifier|\s+const)*
802 $NonptrTypeWithAttr = qr{
803 (?:$Modifier\s+|const\s+)*
805 (?:typeof|__typeof__)\s*\([^\)]*\)|
809 (?:\s+$Modifier|\s+const)*
813 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
814 (?:\s+$Inline|\s+$Modifier)*
816 $TypeMisordered = qr{
817 $NonptrTypeMisordered
818 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
819 (?:\s+$Inline|\s+$Modifier)*
821 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
822 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
826 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
828 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
829 # requires at least perl version v5.10.0
830 # Any use must be runtime checked with $^V
832 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
833 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
834 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
836 our $declaration_macros = qr{(?x:
837 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
838 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
839 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
840 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
845 return "" if (!defined($string));
847 while ($string =~ /^\s*\(.*\)\s*$/) {
848 $string =~ s@^\s*\(\s*@@;
849 $string =~ s@\s*\)\s*$@@;
852 $string =~ s@\s+@ @g;
857 sub seed_camelcase_file {
860 return if (!(-f $file));
864 open(my $include_file, '<', "$file")
865 or warn "$P: Can't read '$file' $!\n";
866 my $text = <$include_file>;
867 close($include_file);
869 my @lines = split('\n', $text);
871 foreach my $line (@lines) {
872 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
873 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
875 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
877 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
883 our %maintained_status = ();
885 sub is_maintained_obsolete {
888 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
890 if (!exists($maintained_status{$filename})) {
891 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
894 return $maintained_status{$filename} =~ /obsolete/i;
897 sub is_SPDX_License_valid {
900 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
902 my $root_path = abs_path($root);
903 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
904 return 0 if ($status ne "");
908 my $camelcase_seeded = 0;
909 sub seed_camelcase_includes {
910 return if ($camelcase_seeded);
913 my $camelcase_cache = "";
914 my @include_files = ();
916 $camelcase_seeded = 1;
919 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
920 chomp $git_last_include_commit;
921 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
923 my $last_mod_date = 0;
924 $files = `find $root/include -name "*.h"`;
925 @include_files = split('\n', $files);
926 foreach my $file (@include_files) {
927 my $date = POSIX::strftime("%Y%m%d%H%M",
928 localtime((stat $file)[9]));
929 $last_mod_date = $date if ($last_mod_date < $date);
931 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
934 if ($camelcase_cache ne "" && -f $camelcase_cache) {
935 open(my $camelcase_file, '<', "$camelcase_cache")
936 or warn "$P: Can't read '$camelcase_cache' $!\n";
937 while (<$camelcase_file>) {
941 close($camelcase_file);
947 $files = `${git_command} ls-files "include/*.h"`;
948 @include_files = split('\n', $files);
951 foreach my $file (@include_files) {
952 seed_camelcase_file($file);
955 if ($camelcase_cache ne "") {
956 unlink glob ".checkpatch-camelcase.*";
957 open(my $camelcase_file, '>', "$camelcase_cache")
958 or warn "$P: Can't write '$camelcase_cache' $!\n";
959 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
960 print $camelcase_file ("$_\n");
962 close($camelcase_file);
966 sub git_commit_info {
967 my ($commit, $id, $desc) = @_;
969 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
971 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
972 $output =~ s/^\s*//gm;
973 my @lines = split("\n", $output);
975 return ($id, $desc) if ($#lines < 0);
977 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
978 # Maybe one day convert this block of bash into something that returns
979 # all matching commit ids, but it's very slow...
981 # echo "checking commits $1..."
982 # git rev-list --remotes | grep -i "^$1" |
983 # while read line ; do
984 # git log --format='%H %s' -1 $line |
985 # echo "commit $(cut -c 1-12,41-)"
987 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
990 $id = substr($lines[0], 0, 12);
991 $desc = substr($lines[0], 41);
997 $chk_signoff = 0 if ($file);
1002 my @fixed_inserted = ();
1003 my @fixed_deleted = ();
1006 # If input is git commits, extract all commits from the commit expressions.
1007 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1008 die "$P: No git repository found\n" if ($git && !-e ".git");
1012 foreach my $commit_expr (@ARGV) {
1014 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1015 $git_range = "-$2 $1";
1016 } elsif ($commit_expr =~ m/\.\./) {
1017 $git_range = "$commit_expr";
1019 $git_range = "-1 $commit_expr";
1021 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1022 foreach my $line (split(/\n/, $lines)) {
1023 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1024 next if (!defined($1) || !defined($2));
1027 unshift(@commits, $sha1);
1028 $git_commits{$sha1} = $subject;
1031 die "$P: no git commits after extraction!\n" if (@commits == 0);
1036 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1037 for my $filename (@ARGV) {
1040 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1041 die "$P: $filename: git format-patch failed - $!\n";
1043 open($FILE, '-|', "diff -u /dev/null $filename") ||
1044 die "$P: $filename: diff failed - $!\n";
1045 } elsif ($filename eq '-') {
1046 open($FILE, '<&STDIN');
1048 open($FILE, '<', "$filename") ||
1049 die "$P: $filename: open failed - $!\n";
1051 if ($filename eq '-') {
1052 $vname = 'Your patch';
1054 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1060 push(@rawlines, $_);
1064 if ($#ARGV > 0 && $quiet == 0) {
1065 print '-' x length($vname) . "\n";
1067 print '-' x length($vname) . "\n";
1070 if (!process($filename)) {
1076 @fixed_inserted = ();
1077 @fixed_deleted = ();
1079 @modifierListFile = ();
1085 hash_show_words(\%use_type, "Used");
1086 hash_show_words(\%ignore_type, "Ignored");
1088 if (!$perl_version_ok) {
1091 NOTE: perl $^V is not modern enough to detect all possible issues.
1092 An upgrade to at least perl $minimum_perl_version is suggested.
1098 NOTE: If any of the errors are false positives, please report
1099 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1106 sub top_of_kernel_tree {
1110 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1111 "README", "Documentation", "arch", "include", "drivers",
1112 "fs", "init", "ipc", "kernel", "lib", "scripts",
1115 foreach my $check (@tree_check) {
1116 if (! -e $root . '/' . $check) {
1124 my ($formatted_email) = @_;
1127 my $name_comment = "";
1131 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1134 $comment = $3 if defined $3;
1135 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1137 $comment = $2 if defined $2;
1138 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1140 $comment = $2 if defined $2;
1141 $formatted_email =~ s/\Q$address\E.*$//;
1142 $name = $formatted_email;
1143 $name = trim($name);
1144 $name =~ s/^\"|\"$//g;
1145 # If there's a name left after stripping spaces and
1146 # leading quotes, and the address doesn't have both
1147 # leading and trailing angle brackets, the address
1149 # "joe smith joe@smith.com" bad
1150 # "joe smith <joe@smith.com" bad
1151 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1158 $name = trim($name);
1159 $name =~ s/^\"|\"$//g;
1160 $name =~ s/(\s*\([^\)]+\))\s*//;
1162 $name_comment = trim($1);
1164 $address = trim($address);
1165 $address =~ s/^\<|\>$//g;
1167 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1168 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1169 $name = "\"$name\"";
1172 return ($name, $name_comment, $address, $comment);
1176 my ($name, $address) = @_;
1178 my $formatted_email;
1180 $name = trim($name);
1181 $name =~ s/^\"|\"$//g;
1182 $address = trim($address);
1184 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1185 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1186 $name = "\"$name\"";
1189 if ("$name" eq "") {
1190 $formatted_email = "$address";
1192 $formatted_email = "$name <$address>";
1195 return $formatted_email;
1198 sub reformat_email {
1201 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1202 return format_email($email_name, $email_address);
1205 sub same_email_addresses {
1206 my ($email1, $email2) = @_;
1208 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1209 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1211 return $email1_name eq $email2_name &&
1212 $email1_address eq $email2_address;
1218 foreach my $path (split(/:/, $ENV{PATH})) {
1219 if (-e "$path/$bin") {
1220 return "$path/$bin";
1230 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1231 if (-e "$path/$conf") {
1232 return "$path/$conf";
1244 for my $c (split(//, $str)) {
1248 for (; ($n % $tabsize) != 0; $n++) {
1260 (my $res = shift) =~ tr/\t/ /c;
1267 # Drop the diff line leader and expand tabs
1269 $line = expand_tabs($line);
1271 # Pick the indent from the front of the line.
1272 my ($white) = ($line =~ /^(\s*)/);
1274 return (length($line), length($white));
1277 my $sanitise_quote = '';
1279 sub sanitise_line_reset {
1280 my ($in_comment) = @_;
1283 $sanitise_quote = '*/';
1285 $sanitise_quote = '';
1298 # Always copy over the diff marker.
1299 $res = substr($line, 0, 1);
1301 for ($off = 1; $off < length($line); $off++) {
1302 $c = substr($line, $off, 1);
1304 # Comments we are whacking completely including the begin
1305 # and end, all to $;.
1306 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1307 $sanitise_quote = '*/';
1309 substr($res, $off, 2, "$;$;");
1313 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1314 $sanitise_quote = '';
1315 substr($res, $off, 2, "$;$;");
1319 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1320 $sanitise_quote = '//';
1322 substr($res, $off, 2, $sanitise_quote);
1327 # A \ in a string means ignore the next character.
1328 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1330 substr($res, $off, 2, 'XX');
1335 if ($c eq "'" || $c eq '"') {
1336 if ($sanitise_quote eq '') {
1337 $sanitise_quote = $c;
1339 substr($res, $off, 1, $c);
1341 } elsif ($sanitise_quote eq $c) {
1342 $sanitise_quote = '';
1346 #print "c<$c> SQ<$sanitise_quote>\n";
1347 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1348 substr($res, $off, 1, $;);
1349 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1350 substr($res, $off, 1, $;);
1351 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1352 substr($res, $off, 1, 'X');
1354 substr($res, $off, 1, $c);
1358 if ($sanitise_quote eq '//') {
1359 $sanitise_quote = '';
1362 # The pathname on a #include may be surrounded by '<' and '>'.
1363 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1364 my $clean = 'X' x length($1);
1365 $res =~ s@\<.*\>@<$clean>@;
1367 # The whole of a #error is a string.
1368 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1369 my $clean = 'X' x length($1);
1370 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1373 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1375 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1381 sub get_quoted_string {
1382 my ($line, $rawline) = @_;
1384 return "" if (!defined($line) || !defined($rawline));
1385 return "" if ($line !~ m/($String)/g);
1386 return substr($rawline, $-[0], $+[0] - $-[0]);
1389 sub ctx_statement_block {
1390 my ($linenr, $remain, $off) = @_;
1391 my $line = $linenr - 1;
1394 my $coff = $off - 1;
1408 @stack = (['', 0]) if ($#stack == -1);
1410 #warn "CSB: blk<$blk> remain<$remain>\n";
1411 # If we are about to drop off the end, pull in more
1414 for (; $remain > 0; $line++) {
1415 last if (!defined $lines[$line]);
1416 next if ($lines[$line] =~ /^-/);
1419 $blk .= $lines[$line] . "\n";
1420 $len = length($blk);
1424 # Bail if there is no further context.
1425 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1429 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1435 $c = substr($blk, $off, 1);
1436 $remainder = substr($blk, $off);
1438 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1440 # Handle nested #if/#else.
1441 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1442 push(@stack, [ $type, $level ]);
1443 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1444 ($type, $level) = @{$stack[$#stack - 1]};
1445 } elsif ($remainder =~ /^#\s*endif\b/) {
1446 ($type, $level) = @{pop(@stack)};
1449 # Statement ends at the ';' or a close '}' at the
1451 if ($level == 0 && $c eq ';') {
1455 # An else is really a conditional as long as its not else if
1456 if ($level == 0 && $coff_set == 0 &&
1457 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1458 $remainder =~ /^(else)(?:\s|{)/ &&
1459 $remainder !~ /^else\s+if\b/) {
1460 $coff = $off + length($1) - 1;
1462 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1463 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1466 if (($type eq '' || $type eq '(') && $c eq '(') {
1470 if ($type eq '(' && $c eq ')') {
1472 $type = ($level != 0)? '(' : '';
1474 if ($level == 0 && $coff < $soff) {
1477 #warn "CSB: mark coff<$coff>\n";
1480 if (($type eq '' || $type eq '{') && $c eq '{') {
1484 if ($type eq '{' && $c eq '}') {
1486 $type = ($level != 0)? '{' : '';
1489 if (substr($blk, $off + 1, 1) eq ';') {
1495 # Preprocessor commands end at the newline unless escaped.
1496 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1504 # We are truly at the end, so shuffle to the next line.
1511 my $statement = substr($blk, $soff, $off - $soff + 1);
1512 my $condition = substr($blk, $soff, $coff - $soff + 1);
1514 #warn "STATEMENT<$statement>\n";
1515 #warn "CONDITION<$condition>\n";
1517 #print "coff<$coff> soff<$off> loff<$loff>\n";
1519 return ($statement, $condition,
1520 $line, $remain + 1, $off - $loff + 1, $level);
1523 sub statement_lines {
1526 # Strip the diff line prefixes and rip blank lines at start and end.
1527 $stmt =~ s/(^|\n)./$1/g;
1531 my @stmt_lines = ($stmt =~ /\n/g);
1533 return $#stmt_lines + 2;
1536 sub statement_rawlines {
1539 my @stmt_lines = ($stmt =~ /\n/g);
1541 return $#stmt_lines + 2;
1544 sub statement_block_size {
1547 $stmt =~ s/(^|\n)./$1/g;
1553 my @stmt_lines = ($stmt =~ /\n/g);
1554 my @stmt_statements = ($stmt =~ /;/g);
1556 my $stmt_lines = $#stmt_lines + 2;
1557 my $stmt_statements = $#stmt_statements + 1;
1559 if ($stmt_lines > $stmt_statements) {
1562 return $stmt_statements;
1566 sub ctx_statement_full {
1567 my ($linenr, $remain, $off) = @_;
1568 my ($statement, $condition, $level);
1572 # Grab the first conditional/block pair.
1573 ($statement, $condition, $linenr, $remain, $off, $level) =
1574 ctx_statement_block($linenr, $remain, $off);
1575 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1576 push(@chunks, [ $condition, $statement ]);
1577 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1578 return ($level, $linenr, @chunks);
1581 # Pull in the following conditional/block pairs and see if they
1582 # could continue the statement.
1584 ($statement, $condition, $linenr, $remain, $off, $level) =
1585 ctx_statement_block($linenr, $remain, $off);
1586 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1587 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1589 push(@chunks, [ $condition, $statement ]);
1592 return ($level, $linenr, @chunks);
1596 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1598 my $start = $linenr - 1;
1605 my @stack = ($level);
1606 for ($line = $start; $remain > 0; $line++) {
1607 next if ($rawlines[$line] =~ /^-/);
1610 $blk .= $rawlines[$line];
1612 # Handle nested #if/#else.
1613 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1614 push(@stack, $level);
1615 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1616 $level = $stack[$#stack - 1];
1617 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1618 $level = pop(@stack);
1621 foreach my $c (split(//, $lines[$line])) {
1622 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1628 if ($c eq $close && $level > 0) {
1630 last if ($level == 0);
1631 } elsif ($c eq $open) {
1636 if (!$outer || $level <= 1) {
1637 push(@res, $rawlines[$line]);
1640 last if ($level == 0);
1643 return ($level, @res);
1645 sub ctx_block_outer {
1646 my ($linenr, $remain) = @_;
1648 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1652 my ($linenr, $remain) = @_;
1654 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1658 my ($linenr, $remain, $off) = @_;
1660 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1663 sub ctx_block_level {
1664 my ($linenr, $remain) = @_;
1666 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1668 sub ctx_statement_level {
1669 my ($linenr, $remain, $off) = @_;
1671 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1674 sub ctx_locate_comment {
1675 my ($first_line, $end_line) = @_;
1677 # Catch a comment on the end of the line itself.
1678 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1679 return $current_comment if (defined $current_comment);
1681 # Look through the context and try and figure out if there is a
1684 $current_comment = '';
1685 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1686 my $line = $rawlines[$linenr - 1];
1688 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1691 if ($line =~ m@/\*@) {
1694 if (!$in_comment && $current_comment ne '') {
1695 $current_comment = '';
1697 $current_comment .= $line . "\n" if ($in_comment);
1698 if ($line =~ m@\*/@) {
1703 chomp($current_comment);
1704 return($current_comment);
1706 sub ctx_has_comment {
1707 my ($first_line, $end_line) = @_;
1708 my $cmt = ctx_locate_comment($first_line, $end_line);
1710 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1711 ##print "CMMT: $cmt\n";
1713 return ($cmt ne '');
1717 my ($linenr, $cnt) = @_;
1719 my $offset = $linenr - 1;
1724 $line = $rawlines[$offset++];
1725 next if (defined($line) && $line =~ /^-/);
1733 my ($linenr, $lc) = @_;
1735 my $stat_real = raw_line($linenr, 0);
1736 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1737 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1744 my ($linenr, $cnt, $here) = @_;
1746 my $herectx = $here . "\n";
1747 for (my $n = 0; $n < $cnt; $n++) {
1748 $herectx .= raw_line($linenr, $n) . "\n";
1759 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1762 $coded = sprintf("^%c", unpack('C', $2) + 64);
1771 my $av_preprocessor = 0;
1776 sub annotate_reset {
1777 $av_preprocessor = 0;
1779 @av_paren_type = ('E');
1780 $av_pend_colon = 'O';
1783 sub annotate_values {
1784 my ($stream, $type) = @_;
1787 my $var = '_' x length($stream);
1790 print "$stream\n" if ($dbg_values > 1);
1792 while (length($cur)) {
1793 @av_paren_type = ('E') if ($#av_paren_type < 0);
1794 print " <" . join('', @av_paren_type) .
1795 "> <$type> <$av_pending>" if ($dbg_values > 1);
1796 if ($cur =~ /^(\s+)/o) {
1797 print "WS($1)\n" if ($dbg_values > 1);
1798 if ($1 =~ /\n/ && $av_preprocessor) {
1799 $type = pop(@av_paren_type);
1800 $av_preprocessor = 0;
1803 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1804 print "CAST($1)\n" if ($dbg_values > 1);
1805 push(@av_paren_type, $type);
1808 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1809 print "DECLARE($1)\n" if ($dbg_values > 1);
1812 } elsif ($cur =~ /^($Modifier)\s*/) {
1813 print "MODIFIER($1)\n" if ($dbg_values > 1);
1816 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1817 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1818 $av_preprocessor = 1;
1819 push(@av_paren_type, $type);
1825 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1826 print "UNDEF($1)\n" if ($dbg_values > 1);
1827 $av_preprocessor = 1;
1828 push(@av_paren_type, $type);
1830 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1831 print "PRE_START($1)\n" if ($dbg_values > 1);
1832 $av_preprocessor = 1;
1834 push(@av_paren_type, $type);
1835 push(@av_paren_type, $type);
1838 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1839 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1840 $av_preprocessor = 1;
1842 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1846 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1847 print "PRE_END($1)\n" if ($dbg_values > 1);
1849 $av_preprocessor = 1;
1851 # Assume all arms of the conditional end as this
1852 # one does, and continue as if the #endif was not here.
1853 pop(@av_paren_type);
1854 push(@av_paren_type, $type);
1857 } elsif ($cur =~ /^(\\\n)/o) {
1858 print "PRECONT($1)\n" if ($dbg_values > 1);
1860 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1861 print "ATTR($1)\n" if ($dbg_values > 1);
1862 $av_pending = $type;
1865 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1866 print "SIZEOF($1)\n" if ($dbg_values > 1);
1872 } elsif ($cur =~ /^(if|while|for)\b/o) {
1873 print "COND($1)\n" if ($dbg_values > 1);
1877 } elsif ($cur =~/^(case)/o) {
1878 print "CASE($1)\n" if ($dbg_values > 1);
1879 $av_pend_colon = 'C';
1882 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1883 print "KEYWORD($1)\n" if ($dbg_values > 1);
1886 } elsif ($cur =~ /^(\()/o) {
1887 print "PAREN('$1')\n" if ($dbg_values > 1);
1888 push(@av_paren_type, $av_pending);
1892 } elsif ($cur =~ /^(\))/o) {
1893 my $new_type = pop(@av_paren_type);
1894 if ($new_type ne '_') {
1896 print "PAREN('$1') -> $type\n"
1897 if ($dbg_values > 1);
1899 print "PAREN('$1')\n" if ($dbg_values > 1);
1902 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1903 print "FUNC($1)\n" if ($dbg_values > 1);
1907 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1908 if (defined $2 && $type eq 'C' || $type eq 'T') {
1909 $av_pend_colon = 'B';
1910 } elsif ($type eq 'E') {
1911 $av_pend_colon = 'L';
1913 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1916 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1917 print "IDENT($1)\n" if ($dbg_values > 1);
1920 } elsif ($cur =~ /^($Assignment)/o) {
1921 print "ASSIGN($1)\n" if ($dbg_values > 1);
1924 } elsif ($cur =~/^(;|{|})/) {
1925 print "END($1)\n" if ($dbg_values > 1);
1927 $av_pend_colon = 'O';
1929 } elsif ($cur =~/^(,)/) {
1930 print "COMMA($1)\n" if ($dbg_values > 1);
1933 } elsif ($cur =~ /^(\?)/o) {
1934 print "QUESTION($1)\n" if ($dbg_values > 1);
1937 } elsif ($cur =~ /^(:)/o) {
1938 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1940 substr($var, length($res), 1, $av_pend_colon);
1941 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1946 $av_pend_colon = 'O';
1948 } elsif ($cur =~ /^(\[)/o) {
1949 print "CLOSE($1)\n" if ($dbg_values > 1);
1952 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1955 print "OPV($1)\n" if ($dbg_values > 1);
1962 substr($var, length($res), 1, $variant);
1965 } elsif ($cur =~ /^($Operators)/o) {
1966 print "OP($1)\n" if ($dbg_values > 1);
1967 if ($1 ne '++' && $1 ne '--') {
1971 } elsif ($cur =~ /(^.)/o) {
1972 print "C($1)\n" if ($dbg_values > 1);
1975 $cur = substr($cur, length($1));
1976 $res .= $type x length($1);
1980 return ($res, $var);
1984 my ($possible, $line) = @_;
1985 my $notPermitted = qr{(?:
2002 ^(?:typedef|struct|enum)\b
2004 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2005 if ($possible !~ $notPermitted) {
2006 # Check for modifiers.
2007 $possible =~ s/\s*$Storage\s*//g;
2008 $possible =~ s/\s*$Sparse\s*//g;
2009 if ($possible =~ /^\s*$/) {
2011 } elsif ($possible =~ /\s/) {
2012 $possible =~ s/\s*$Type\s*//g;
2013 for my $modifier (split(' ', $possible)) {
2014 if ($modifier !~ $notPermitted) {
2015 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2016 push(@modifierListFile, $modifier);
2021 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2022 push(@typeListFile, $possible);
2026 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2035 $type =~ tr/[a-z]/[A-Z]/;
2037 return defined $use_type{$type} if (scalar keys %use_type > 0);
2039 return !defined $ignore_type{$type};
2043 my ($level, $type, $msg) = @_;
2045 if (!show_type($type) ||
2046 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2051 if ($level eq 'ERROR') {
2053 } elsif ($level eq 'WARNING') {
2059 $output .= $prefix . $level . ':';
2061 $output .= BLUE if ($color);
2062 $output .= "$type:";
2064 $output .= RESET if ($color);
2065 $output .= ' ' . $msg . "\n";
2068 my @lines = split("\n", $output, -1);
2069 splice(@lines, 1, 1);
2070 $output = join("\n", @lines);
2072 $output = (split('\n', $output))[0] . "\n" if ($terse);
2074 push(our @report, $output);
2083 sub fixup_current_range {
2084 my ($lineRef, $offset, $length) = @_;
2086 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2089 my $no = $o + $offset;
2090 my $nl = $l + $length;
2091 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2095 sub fix_inserted_deleted_lines {
2096 my ($linesRef, $insertedRef, $deletedRef) = @_;
2098 my $range_last_linenr = 0;
2099 my $delta_offset = 0;
2104 my $next_insert = 0;
2105 my $next_delete = 0;
2109 my $inserted = @{$insertedRef}[$next_insert++];
2110 my $deleted = @{$deletedRef}[$next_delete++];
2112 foreach my $old_line (@{$linesRef}) {
2114 my $line = $old_line; #don't modify the array
2115 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2117 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2118 $range_last_linenr = $new_linenr;
2119 fixup_current_range(\$line, $delta_offset, 0);
2122 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2123 $deleted = @{$deletedRef}[$next_delete++];
2125 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2128 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2129 push(@lines, ${$inserted}{'LINE'});
2130 $inserted = @{$insertedRef}[$next_insert++];
2132 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2136 push(@lines, $line);
2146 sub fix_insert_line {
2147 my ($linenr, $line) = @_;
2153 push(@fixed_inserted, $inserted);
2156 sub fix_delete_line {
2157 my ($linenr, $line) = @_;
2164 push(@fixed_deleted, $deleted);
2168 my ($type, $msg) = @_;
2170 if (report("ERROR", $type, $msg)) {
2178 my ($type, $msg) = @_;
2180 if (report("WARNING", $type, $msg)) {
2188 my ($type, $msg) = @_;
2190 if ($check && report("CHECK", $type, $msg)) {
2198 sub check_absolute_file {
2199 my ($absolute, $herecurr) = @_;
2200 my $file = $absolute;
2202 ##print "absolute<$absolute>\n";
2204 # See if any suffix of this path is a path within the tree.
2205 while ($file =~ s@^[^/]*/@@) {
2206 if (-f "$root/$file") {
2207 ##print "file<$file>\n";
2215 # It is, so see if the prefix is acceptable.
2216 my $prefix = $absolute;
2217 substr($prefix, -length($file)) = '';
2219 ##print "prefix<$prefix>\n";
2220 if ($prefix ne ".../") {
2221 WARN("USE_RELATIVE_PATH",
2222 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2229 $string =~ s/^\s+|\s+$//g;
2237 $string =~ s/^\s+//;
2245 $string =~ s/\s+$//;
2250 sub string_find_replace {
2251 my ($string, $find, $replace) = @_;
2253 $string =~ s/$find/$replace/g;
2261 my $source_indent = $tabsize;
2262 my $max_spaces_before_tab = $source_indent - 1;
2263 my $spaces_to_tab = " " x $source_indent;
2265 #convert leading spaces to tabs
2266 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2267 #Remove spaces before a tab
2268 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2273 sub pos_last_openparen {
2278 my $opens = $line =~ tr/\(/\(/;
2279 my $closes = $line =~ tr/\)/\)/;
2281 my $last_openparen = 0;
2283 if (($opens == 0) || ($closes >= $opens)) {
2287 my $len = length($line);
2289 for ($pos = 0; $pos < $len; $pos++) {
2290 my $string = substr($line, $pos);
2291 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2292 $pos += length($1) - 1;
2293 } elsif (substr($line, $pos, 1) eq '(') {
2294 $last_openparen = $pos;
2295 } elsif (index($string, '(') == -1) {
2300 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2303 sub get_raw_comment {
2304 my ($line, $rawline) = @_;
2307 for my $i (0 .. (length($line) - 1)) {
2308 if (substr($line, $i, 1) eq "$;") {
2309 $comment .= substr($rawline, $i, 1);
2317 my $filename = shift;
2323 my $stashrawline="";
2333 my $authorsignoff = 0;
2335 my $is_binding_patch = -1;
2336 my $in_header_lines = $file ? 0 : 1;
2337 my $in_commit_log = 0; #Scanning lines before patch
2338 my $has_patch_separator = 0; #Found a --- line
2339 my $has_commit_log = 0; #Encountered lines before patch
2340 my $commit_log_lines = 0; #Number of commit log lines
2341 my $commit_log_possible_stack_dump = 0;
2342 my $commit_log_long_line = 0;
2343 my $commit_log_has_diff = 0;
2344 my $reported_maintainer_file = 0;
2345 my $non_utf8_charset = 0;
2347 my $last_blank_line = 0;
2348 my $last_coalesced_string_linenr = -1;
2356 # Trace the real file/line as we go.
2361 my $context_function; #undef'd unless there's a known function
2363 my $comment_edge = 0;
2367 my $prev_values = 'E';
2370 my %suppress_ifbraces;
2371 my %suppress_whiletrailers;
2372 my %suppress_export;
2373 my $suppress_statement = 0;
2375 my %signatures = ();
2377 # Pre-scan the patch sanitizing the lines.
2378 # Pre-scan the patch looking for any __setup documentation.
2380 my @setup_docs = ();
2383 my $camelcase_file_seeded = 0;
2385 my $checklicenseline = 1;
2387 sanitise_line_reset();
2389 foreach my $rawline (@rawlines) {
2393 push(@fixed, $rawline) if ($fix);
2395 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2397 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2402 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2411 # Guestimate if this is a continuing comment. Run
2412 # the context looking for a comment "edge". If this
2413 # edge is a close comment then we must be in a comment
2417 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2418 next if (defined $rawlines[$ln - 1] &&
2419 $rawlines[$ln - 1] =~ /^-/);
2421 #print "RAW<$rawlines[$ln - 1]>\n";
2422 last if (!defined $rawlines[$ln - 1]);
2423 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2424 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2429 if (defined $edge && $edge eq '*/') {
2433 # Guestimate if this is a continuing comment. If this
2434 # is the start of a diff block and this line starts
2435 # ' *' then it is very likely a comment.
2436 if (!defined $edge &&
2437 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2442 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2443 sanitise_line_reset($in_comment);
2445 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2446 # Standardise the strings and chars within the input to
2447 # simplify matching -- only bother with positive lines.
2448 $line = sanitise_line($rawline);
2450 push(@lines, $line);
2453 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2458 #print "==>$rawline\n";
2459 #print "-->$line\n";
2461 if ($setup_docs && $line =~ /^\+/) {
2462 push(@setup_docs, $line);
2471 foreach my $line (@lines) {
2474 my $sline = $line; #copy of $line
2475 $sline =~ s/$;/ /g; #with comments as spaces
2477 my $rawline = $rawlines[$linenr - 1];
2478 my $raw_comment = get_raw_comment($line, $rawline);
2480 # check if it's a mode change, rename or start of a patch
2481 if (!$in_commit_log &&
2482 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2483 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2484 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2488 #extract the line range in the file after the patch is applied
2489 if (!$in_commit_log &&
2490 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2493 $first_line = $linenr + 1;
2503 %suppress_ifbraces = ();
2504 %suppress_whiletrailers = ();
2505 %suppress_export = ();
2506 $suppress_statement = 0;
2507 if ($context =~ /\b(\w+)\s*\(/) {
2508 $context_function = $1;
2510 undef $context_function;
2514 # track the line number as we move through the hunk, note that
2515 # new versions of GNU diff omit the leading space on completely
2516 # blank context lines so we need to count that too.
2517 } elsif ($line =~ /^( |\+|$)/) {
2519 $realcnt-- if ($realcnt != 0);
2521 # Measure the line length and indent.
2522 ($length, $indent) = line_stats($rawline);
2524 # Track the previous line.
2525 ($prevline, $stashline) = ($stashline, $line);
2526 ($previndent, $stashindent) = ($stashindent, $indent);
2527 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2529 #warn "line<$line>\n";
2531 } elsif ($realcnt == 1) {
2535 my $hunk_line = ($realcnt != 0);
2537 $here = "#$linenr: " if (!$file);
2538 $here = "#$realline: " if ($file);
2541 # extract the filename as it passes
2542 if ($line =~ /^diff --git.*?(\S+)$/) {
2544 $realfile =~ s@^([^/]*)/@@ if (!$file);
2547 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2549 $realfile =~ s@^([^/]*)/@@ if (!$file);
2553 if (!$file && $tree && $p1_prefix ne '' &&
2554 -e "$root/$p1_prefix") {
2555 WARN("PATCH_PREFIX",
2556 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2559 if ($realfile =~ m@^include/asm/@) {
2560 ERROR("MODIFIED_INCLUDE_ASM",
2561 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2566 #make up the handle for any error we report on this line
2568 $prefix = "$realfile:$realline: "
2571 $prefix = "$filename:$realline: ";
2573 $prefix = "$filename:$linenr: ";
2578 if (is_maintained_obsolete($realfile)) {
2580 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2582 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2585 $check = $check_orig;
2587 $checklicenseline = 1;
2589 if ($realfile !~ /^MAINTAINERS/) {
2590 my $last_binding_patch = $is_binding_patch;
2592 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2594 if (($last_binding_patch != -1) &&
2595 ($last_binding_patch ^ $is_binding_patch)) {
2596 WARN("DT_SPLIT_BINDING_PATCH",
2597 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2604 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2606 my $hereline = "$here\n$rawline\n";
2607 my $herecurr = "$here\n$rawline\n";
2608 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2610 $cnt_lines++ if ($realcnt != 0);
2612 # Verify the existence of a commit log if appropriate
2613 # 2 is used because a $signature is counted in $commit_log_lines
2614 if ($in_commit_log) {
2615 if ($line !~ /^\s*$/) {
2616 $commit_log_lines++; #could be a $signature
2618 } elsif ($has_commit_log && $commit_log_lines < 2) {
2619 WARN("COMMIT_MESSAGE",
2620 "Missing commit description - Add an appropriate one\n");
2621 $commit_log_lines = 2; #warn only once
2624 # Check if the commit log has what seems like a diff which can confuse patch
2625 if ($in_commit_log && !$commit_log_has_diff &&
2626 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2627 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2628 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2629 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2630 ERROR("DIFF_IN_COMMIT_MSG",
2631 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2632 $commit_log_has_diff = 1;
2635 # Check for incorrect file permissions
2636 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2637 my $permhere = $here . "FILE: $realfile\n";
2638 if ($realfile !~ m@scripts/@ &&
2639 $realfile !~ /\.(py|pl|awk|sh)$/) {
2640 ERROR("EXECUTE_PERMISSIONS",
2641 "do not set execute permissions for source files\n" . $permhere);
2645 # Check the patch for a From:
2646 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2648 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2650 $author = reformat_email($author);
2653 # Check the patch for a signoff:
2654 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2657 if ($author ne '') {
2658 if (same_email_addresses($1, $author)) {
2664 # Check for patch separator
2665 if ($line =~ /^---$/) {
2666 $has_patch_separator = 1;
2670 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2671 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2672 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2673 $reported_maintainer_file = 1;
2676 # Check signature styles
2677 if (!$in_header_lines &&
2678 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2679 my $space_before = $1;
2681 my $space_after = $3;
2683 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2685 if ($sign_off !~ /$signature_tags/) {
2686 WARN("BAD_SIGN_OFF",
2687 "Non-standard signature: $sign_off\n" . $herecurr);
2689 if (defined $space_before && $space_before ne "") {
2690 if (WARN("BAD_SIGN_OFF",
2691 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2693 $fixed[$fixlinenr] =
2694 "$ucfirst_sign_off $email";
2697 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2698 if (WARN("BAD_SIGN_OFF",
2699 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2701 $fixed[$fixlinenr] =
2702 "$ucfirst_sign_off $email";
2706 if (!defined $space_after || $space_after ne " ") {
2707 if (WARN("BAD_SIGN_OFF",
2708 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2710 $fixed[$fixlinenr] =
2711 "$ucfirst_sign_off $email";
2715 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2716 my $suggested_email = format_email(($email_name, $email_address));
2717 if ($suggested_email eq "") {
2718 ERROR("BAD_SIGN_OFF",
2719 "Unrecognized email address: '$email'\n" . $herecurr);
2721 my $dequoted = $suggested_email;
2722 $dequoted =~ s/^"//;
2723 $dequoted =~ s/" </ </;
2724 # Don't force email to have quotes
2725 # Allow just an angle bracketed address
2726 if (!same_email_addresses($email, $suggested_email)) {
2727 WARN("BAD_SIGN_OFF",
2728 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2732 # Check for duplicate signatures
2733 my $sig_nospace = $line;
2734 $sig_nospace =~ s/\s//g;
2735 $sig_nospace = lc($sig_nospace);
2736 if (defined $signatures{$sig_nospace}) {
2737 WARN("BAD_SIGN_OFF",
2738 "Duplicate signature\n" . $herecurr);
2740 $signatures{$sig_nospace} = 1;
2743 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2744 if ($sign_off =~ /^co-developed-by:$/i) {
2745 if ($email eq $author) {
2746 WARN("BAD_SIGN_OFF",
2747 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2749 if (!defined $lines[$linenr]) {
2750 WARN("BAD_SIGN_OFF",
2751 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2752 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2753 WARN("BAD_SIGN_OFF",
2754 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2755 } elsif ($1 ne $email) {
2756 WARN("BAD_SIGN_OFF",
2757 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2762 # Check email subject for common tools that don't need to be mentioned
2763 if ($in_header_lines &&
2764 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2765 WARN("EMAIL_SUBJECT",
2766 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2769 # Check for Gerrit Change-Ids not in any patch context
2770 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2771 ERROR("GERRIT_CHANGE_ID",
2772 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr);
2775 # Check if the commit log is in a possible stack dump
2776 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2777 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2778 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2780 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2781 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2782 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2783 # stack dump address styles
2784 $commit_log_possible_stack_dump = 1;
2787 # Check for line lengths > 75 in commit log, warn once
2788 if ($in_commit_log && !$commit_log_long_line &&
2789 length($line) > 75 &&
2790 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2791 # file delta changes
2792 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2794 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2795 # A Fixes: or Link: line
2796 $commit_log_possible_stack_dump)) {
2797 WARN("COMMIT_LOG_LONG_LINE",
2798 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2799 $commit_log_long_line = 1;
2802 # Reset possible stack dump if a blank line is found
2803 if ($in_commit_log && $commit_log_possible_stack_dump &&
2805 $commit_log_possible_stack_dump = 0;
2808 # Check for git id commit length and improperly formed commit descriptions
2809 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2810 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
2811 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2812 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2813 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2814 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2815 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2816 my $init_char = "c";
2817 my $orig_commit = "";
2824 my $id = '0123456789ab';
2825 my $orig_desc = "commit description";
2826 my $description = "";
2828 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2830 $orig_commit = lc($2);
2831 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2832 $orig_commit = lc($1);
2835 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2836 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2837 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2838 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2839 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2842 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2843 defined $rawlines[$linenr] &&
2844 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2847 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2848 defined $rawlines[$linenr] &&
2849 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2850 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2852 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2853 $orig_desc .= " " . $1;
2857 ($id, $description) = git_commit_info($orig_commit,
2861 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2862 ERROR("GIT_COMMIT_ID",
2863 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2867 # Check for added, moved or deleted files
2868 if (!$reported_maintainer_file && !$in_commit_log &&
2869 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2870 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2871 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2872 (defined($1) || defined($2))))) {
2874 $reported_maintainer_file = 1;
2875 WARN("FILE_PATH_CHANGES",
2876 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2879 # Check for adding new DT bindings not in schema format
2880 if (!$in_commit_log &&
2881 ($line =~ /^new file mode\s*\d+\s*$/) &&
2882 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
2883 WARN("DT_SCHEMA_BINDING_PATCH",
2884 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
2887 # Check for wrappage within a valid hunk of the file
2888 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2889 ERROR("CORRUPTED_PATCH",
2890 "patch seems to be corrupt (line wrapped?)\n" .
2891 $herecurr) if (!$emitted_corrupt++);
2894 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2895 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2896 $rawline !~ m/^$UTF8*$/) {
2897 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2899 my $blank = copy_spacing($rawline);
2900 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2901 my $hereptr = "$hereline$ptr\n";
2904 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2907 # Check if it's the start of a commit log
2908 # (not a header line and we haven't seen the patch filename)
2909 if ($in_header_lines && $realfile =~ /^$/ &&
2910 !($rawline =~ /^\s+(?:\S|$)/ ||
2911 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2912 $in_header_lines = 0;
2914 $has_commit_log = 1;
2917 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2918 # declined it, i.e defined some charset where it is missing.
2919 if ($in_header_lines &&
2920 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2922 $non_utf8_charset = 1;
2925 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2926 $rawline =~ /$NON_ASCII_UTF8/) {
2927 WARN("UTF8_BEFORE_PATCH",
2928 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2931 # Check for absolute kernel paths in commit message
2932 if ($tree && $in_commit_log) {
2933 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2936 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2937 check_absolute_file($1, $herecurr)) {
2940 check_absolute_file($file, $herecurr);
2945 # Check for various typo / spelling mistakes
2946 if (defined($misspellings) &&
2947 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2948 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2950 my $typo_fix = $spelling_fix{lc($typo)};
2951 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2952 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2953 my $msg_level = \&WARN;
2954 $msg_level = \&CHK if ($file);
2955 if (&{$msg_level}("TYPO_SPELLING",
2956 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2958 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2963 # check for invalid commit id
2964 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
2967 ($id, $description) = git_commit_info($2, undef, undef);
2968 if (!defined($id)) {
2969 WARN("UNKNOWN_COMMIT_ID",
2970 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
2974 # ignore non-hunk lines and lines being removed
2975 next if (!$hunk_line || $line =~ /^-/);
2977 #trailing whitespace
2978 if ($line =~ /^\+.*\015/) {
2979 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2980 if (ERROR("DOS_LINE_ENDINGS",
2981 "DOS line endings\n" . $herevet) &&
2983 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2985 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2986 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2987 if (ERROR("TRAILING_WHITESPACE",
2988 "trailing whitespace\n" . $herevet) &&
2990 $fixed[$fixlinenr] =~ s/\s+$//;
2996 # Check for FSF mailing addresses.
2997 if ($rawline =~ /\bwrite to the Free/i ||
2998 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2999 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3000 $rawline =~ /\b51\s+Franklin\s+St/i) {
3001 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3002 my $msg_level = \&ERROR;
3003 $msg_level = \&CHK if ($file);
3004 &{$msg_level}("FSF_MAILING_ADDRESS",
3005 "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)
3008 # check for Kconfig help text having a real description
3009 # Only applies when adding the entry originally, after that we do not have
3010 # sufficient context to determine whether it is indeed long enough.
3011 if ($realfile =~ /Kconfig/ &&
3012 # 'choice' is usually the last thing on the line (though
3013 # Kconfig supports named choices), so use a word boundary
3014 # (\b) rather than a whitespace character (\s)
3015 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3018 my $ln = $linenr + 1;
3022 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3023 $f = $lines[$ln - 1];
3024 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3025 $is_end = $lines[$ln - 1] =~ /^\+/;
3027 next if ($f =~ /^-/);
3028 last if (!$file && $f =~ /^\@\@/);
3030 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3032 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
3033 if ($lines[$ln - 1] =~ "---help---") {
3034 WARN("CONFIG_DESCRIPTION",
3035 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
3043 next if ($f =~ /^$/);
3045 # This only checks context lines in the patch
3046 # and so hopefully shouldn't trigger false
3047 # positives, even though some of these are
3048 # common words in help texts
3049 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3050 if|endif|menu|endmenu|source)\b/x) {
3056 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3057 WARN("CONFIG_DESCRIPTION",
3058 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3060 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3063 # check for MAINTAINERS entries that don't have the right form
3064 if ($realfile =~ /^MAINTAINERS$/ &&
3065 $rawline =~ /^\+[A-Z]:/ &&
3066 $rawline !~ /^\+[A-Z]:\t\S/) {
3067 if (WARN("MAINTAINERS_STYLE",
3068 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3070 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3074 # discourage the use of boolean for type definition attributes of Kconfig options
3075 if ($realfile =~ /Kconfig/ &&
3076 $line =~ /^\+\s*\bboolean\b/) {
3077 WARN("CONFIG_TYPE_BOOLEAN",
3078 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3081 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3082 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3085 'EXTRA_AFLAGS' => 'asflags-y',
3086 'EXTRA_CFLAGS' => 'ccflags-y',
3087 'EXTRA_CPPFLAGS' => 'cppflags-y',
3088 'EXTRA_LDFLAGS' => 'ldflags-y',
3091 WARN("DEPRECATED_VARIABLE",
3092 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3095 # check for DT compatible documentation
3096 if (defined $root &&
3097 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3098 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3100 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3102 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3103 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3105 foreach my $compat (@compats) {
3106 my $compat2 = $compat;
3107 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3108 my $compat3 = $compat;
3109 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3110 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3112 WARN("UNDOCUMENTED_DT_STRING",
3113 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3116 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3118 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3120 WARN("UNDOCUMENTED_DT_STRING",
3121 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3126 # check for using SPDX license tag at beginning of files
3127 if ($realline == $checklicenseline) {
3128 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3129 $checklicenseline = 2;
3130 } elsif ($rawline =~ /^\+/) {
3132 if ($realfile =~ /\.(h|s|S)$/) {
3134 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3136 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3138 } elsif ($realfile =~ /\.rst$/) {
3142 # check SPDX comment style for .[chsS] files
3143 if ($realfile =~ /\.[chsS]$/ &&
3144 $rawline =~ /SPDX-License-Identifier:/ &&
3145 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3146 WARN("SPDX_LICENSE_TAG",
3147 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3150 if ($comment !~ /^$/ &&
3151 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3152 WARN("SPDX_LICENSE_TAG",
3153 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3154 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3155 my $spdx_license = $1;
3156 if (!is_SPDX_License_valid($spdx_license)) {
3157 WARN("SPDX_LICENSE_TAG",
3158 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3160 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3161 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3162 my $msg_level = \&WARN;
3163 $msg_level = \&CHK if ($file);
3164 if (&{$msg_level}("SPDX_LICENSE_TAG",
3166 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3168 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3175 # check we are in a valid source file if not then ignore this hunk
3176 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3178 # check for using SPDX-License-Identifier on the wrong line number
3179 if ($realline != $checklicenseline &&
3180 $rawline =~ /\bSPDX-License-Identifier:/ &&
3181 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3182 WARN("SPDX_LICENSE_TAG",
3183 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3186 # line length limit (with some exclusions)
3188 # There are a few types of lines that may extend beyond $max_line_length:
3189 # logging functions like pr_info that end in a string
3190 # lines with a single string
3191 # #defines that are a single string
3192 # lines with an RFC3986 like URL
3194 # There are 3 different line length message types:
3195 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3196 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3197 # LONG_LINE all other lines longer than $max_line_length
3199 # if LONG_LINE is ignored, the other 2 types are also ignored
3202 if ($line =~ /^\+/ && $length > $max_line_length) {
3203 my $msg_type = "LONG_LINE";
3205 # Check the allowed long line types first
3207 # logging functions that end in a string that starts
3208 # before $max_line_length
3209 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3210 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3213 # lines with only strings (w/ possible termination)
3214 # #defines with only strings
3215 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3216 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3219 # More special cases
3220 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3221 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3224 # URL ($rawline is used in case the URL is in a comment)
3225 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3228 # Otherwise set the alternate message types
3230 # a comment starts before $max_line_length
3231 } elsif ($line =~ /($;[\s$;]*)$/ &&
3232 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3233 $msg_type = "LONG_LINE_COMMENT"
3235 # a quoted string starts before $max_line_length
3236 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3237 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3238 $msg_type = "LONG_LINE_STRING"
3241 if ($msg_type ne "" &&
3242 (show_type("LONG_LINE") || show_type($msg_type))) {
3244 "line over $max_line_length characters\n" . $herecurr);
3248 # check for adding lines without a newline.
3249 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3250 WARN("MISSING_EOF_NEWLINE",
3251 "adding a line without newline at end of file\n" . $herecurr);
3254 # check we are in a valid source file C or perl if not then ignore this hunk
3255 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3257 # at the beginning of a line any tabs must come first and anything
3258 # more than $tabsize must use tabs.
3259 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3260 $rawline =~ /^\+\s* \s*/) {
3261 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3263 if (ERROR("CODE_INDENT",
3264 "code indent should use tabs where possible\n" . $herevet) &&
3266 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3270 # check for space before tabs.
3271 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3272 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3273 if (WARN("SPACE_BEFORE_TAB",
3274 "please, no space before tabs\n" . $herevet) &&
3276 while ($fixed[$fixlinenr] =~
3277 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3278 while ($fixed[$fixlinenr] =~
3279 s/(^\+.*) +\t/$1\t/) {}
3283 # check for assignments on the start of a line
3284 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3285 CHK("ASSIGNMENT_CONTINUATIONS",
3286 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3289 # check for && or || at the start of a line
3290 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3291 CHK("LOGICAL_CONTINUATIONS",
3292 "Logical continuations should be on the previous line\n" . $hereprev);
3295 # check indentation starts on a tab stop
3296 if ($perl_version_ok &&
3297 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3298 my $indent = length($1);
3299 if ($indent % $tabsize) {
3301 "Statements should start on a tabstop\n" . $herecurr) &&
3303 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3308 # check multi-line statement indentation matches previous line
3309 if ($perl_version_ok &&
3310 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3311 $prevline =~ /^\+(\t*)(.*)$/;
3315 my $pos = pos_last_openparen($rest);
3317 $line =~ /^(\+| )([ \t]*)/;
3320 my $goodtabindent = $oldindent .
3321 "\t" x ($pos / $tabsize) .
3322 " " x ($pos % $tabsize);
3323 my $goodspaceindent = $oldindent . " " x $pos;
3325 if ($newindent ne $goodtabindent &&
3326 $newindent ne $goodspaceindent) {
3328 if (CHK("PARENTHESIS_ALIGNMENT",
3329 "Alignment should match open parenthesis\n" . $hereprev) &&
3330 $fix && $line =~ /^\+/) {
3331 $fixed[$fixlinenr] =~
3332 s/^\+[ \t]*/\+$goodtabindent/;
3338 # check for space after cast like "(int) foo" or "(struct foo) bar"
3339 # avoid checking a few false positives:
3340 # "sizeof(<type>)" or "__alignof__(<type>)"
3341 # function pointer declarations like "(*foo)(int) = bar;"
3342 # structure definitions like "(struct foo) { 0 };"
3343 # multiline macros that define functions
3344 # known attributes or the __attribute__ keyword
3345 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3346 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3348 "No space is necessary after a cast\n" . $herecurr) &&
3350 $fixed[$fixlinenr] =~
3351 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3355 # Block comment styles
3356 # Networking with an initial /*
3357 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3358 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3359 $rawline =~ /^\+[ \t]*\*/ &&
3361 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3362 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3365 # Block comments use * on subsequent lines
3366 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3367 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3368 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3369 $rawline =~ /^\+/ && #line is new
3370 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3371 WARN("BLOCK_COMMENT_STYLE",
3372 "Block comments use * on subsequent lines\n" . $hereprev);
3375 # Block comments use */ on trailing lines
3376 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3377 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3378 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3379 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3380 WARN("BLOCK_COMMENT_STYLE",
3381 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3384 # Block comment * alignment
3385 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3386 $line =~ /^\+[ \t]*$;/ && #leading comment
3387 $rawline =~ /^\+[ \t]*\*/ && #leading *
3388 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3389 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3390 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3392 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3394 $oldindent = expand_tabs($1);
3396 $prevrawline =~ m@^\+(.*/?)\*@;
3397 $oldindent = expand_tabs($1);
3399 $rawline =~ m@^\+([ \t]*)\*@;
3401 $newindent = expand_tabs($newindent);
3402 if (length($oldindent) ne length($newindent)) {
3403 WARN("BLOCK_COMMENT_STYLE",
3404 "Block comments should align the * on each line\n" . $hereprev);
3408 # check for missing blank lines after struct/union declarations
3409 # with exceptions for various attributes and macros
3410 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3412 !($line =~ /^\+\s*$/ ||
3413 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3414 $line =~ /^\+\s*MODULE_/i ||
3415 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3416 $line =~ /^\+[a-z_]*init/ ||
3417 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3418 $line =~ /^\+\s*DECLARE/ ||
3419 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3420 $line =~ /^\+\s*__setup/)) {
3421 if (CHK("LINE_SPACING",
3422 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3424 fix_insert_line($fixlinenr, "\+");
3428 # check for multiple consecutive blank lines
3429 if ($prevline =~ /^[\+ ]\s*$/ &&
3430 $line =~ /^\+\s*$/ &&
3431 $last_blank_line != ($linenr - 1)) {
3432 if (CHK("LINE_SPACING",
3433 "Please don't use multiple blank lines\n" . $hereprev) &&
3435 fix_delete_line($fixlinenr, $rawline);
3438 $last_blank_line = $linenr;
3441 # check for missing blank lines after declarations
3442 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3443 # actual declarations
3444 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3445 # function pointer declarations
3446 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3447 # foo bar; where foo is some local typedef or #define
3448 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3449 # known declaration macros
3450 $prevline =~ /^\+\s+$declaration_macros/) &&
3451 # for "else if" which can look like "$Ident $Ident"
3452 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3453 # other possible extensions of declaration lines
3454 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3455 # not starting a section or a macro "\" extended line
3456 $prevline =~ /(?:\{\s*|\\)$/) &&
3457 # looks like a declaration
3458 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3459 # function pointer declarations
3460 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3461 # foo bar; where foo is some local typedef or #define
3462 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3463 # known declaration macros
3464 $sline =~ /^\+\s+$declaration_macros/ ||
3465 # start of struct or union or enum
3466 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3467 # start or end of block or continuation of declaration
3468 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3469 # bitfield continuation
3470 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3471 # other possible extensions of declaration lines
3472 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3473 # indentation of previous and current line are the same
3474 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3475 if (WARN("LINE_SPACING",
3476 "Missing a blank line after declarations\n" . $hereprev) &&
3478 fix_insert_line($fixlinenr, "\+");
3482 # check for spaces at the beginning of a line.
3484 # 1) within comments
3485 # 2) indented preprocessor commands
3487 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3488 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3489 if (WARN("LEADING_SPACE",
3490 "please, no spaces at the start of a line\n" . $herevet) &&
3492 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3496 # check we are in a valid C source file if not then ignore this hunk
3497 next if ($realfile !~ /\.(h|c)$/);
3499 # check for unusual line ending [ or (
3500 if ($line =~ /^\+.*([\[\(])\s*$/) {
3501 CHK("OPEN_ENDED_LINE",
3502 "Lines should not end with a '$1'\n" . $herecurr);
3505 # check if this appears to be the start function declaration, save the name
3506 if ($sline =~ /^\+\{\s*$/ &&
3507 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3508 $context_function = $1;
3511 # check if this appears to be the end of function declaration
3512 if ($sline =~ /^\+\}\s*$/) {
3513 undef $context_function;
3516 # check indentation of any line with a bare else
3517 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3518 # if the previous line is a break or return and is indented 1 tab more...
3519 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3520 my $tabs = length($1) + 1;
3521 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3522 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3523 defined $lines[$linenr] &&
3524 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3525 WARN("UNNECESSARY_ELSE",
3526 "else is not generally useful after a break or return\n" . $hereprev);
3530 # check indentation of a line with a break;
3531 # if the previous line is a goto or return and is indented the same # of tabs
3532 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3534 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3535 WARN("UNNECESSARY_BREAK",
3536 "break is not useful after a goto or return\n" . $hereprev);
3540 # check for RCS/CVS revision markers
3541 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3543 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3546 # check for old HOTPLUG __dev<foo> section markings
3547 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3548 WARN("HOTPLUG_SECTION",
3549 "Using $1 is unnecessary\n" . $herecurr);
3552 # Check for potential 'bare' types
3553 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3555 #print "LINE<$line>\n";
3556 if ($linenr > $suppress_statement &&
3557 $realcnt && $sline =~ /.\s*\S/) {
3558 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3559 ctx_statement_block($linenr, $realcnt, 0);
3560 $stat =~ s/\n./\n /g;
3561 $cond =~ s/\n./\n /g;
3563 #print "linenr<$linenr> <$stat>\n";
3564 # If this statement has no statement boundaries within
3565 # it there is no point in retrying a statement scan
3566 # until we hit end of it.
3567 my $frag = $stat; $frag =~ s/;+\s*$//;
3568 if ($frag !~ /(?:{|;)/) {
3569 #print "skip<$line_nr_next>\n";
3570 $suppress_statement = $line_nr_next;
3573 # Find the real next line.
3574 $realline_next = $line_nr_next;
3575 if (defined $realline_next &&
3576 (!defined $lines[$realline_next - 1] ||
3577 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3584 # Ignore goto labels.
3585 if ($s =~ /$Ident:\*$/s) {
3587 # Ignore functions being called
3588 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3590 } elsif ($s =~ /^.\s*else\b/s) {
3592 # declarations always start with types
3593 } 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) {
3596 possible($type, "A:" . $s);
3598 # definitions in global scope can only start with types
3599 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3600 possible($1, "B:" . $s);
3603 # any (foo ... *) is a pointer cast, and foo is a type
3604 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3605 possible($1, "C:" . $s);
3608 # Check for any sort of function declaration.
3609 # int foo(something bar, other baz);
3610 # void (*store_gdt)(x86_descr_ptr *);
3611 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3612 my ($name_len) = length($1);
3615 substr($ctx, 0, $name_len + 1, '');
3616 $ctx =~ s/\)[^\)]*$//;
3618 for my $arg (split(/\s*,\s*/, $ctx)) {
3619 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3621 possible($1, "D:" . $s);
3629 # Checks which may be anchored in the context.
3632 # Check for switch () and associated case and default
3633 # statements should be at the same indent.
3634 if ($line=~/\bswitch\s*\(.*\)/) {
3637 my @ctx = ctx_block_outer($linenr, $realcnt);
3639 for my $ctx (@ctx) {
3640 my ($clen, $cindent) = line_stats($ctx);
3641 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3642 $indent != $cindent) {
3643 $err .= "$sep$ctx\n";
3650 ERROR("SWITCH_CASE_INDENT_LEVEL",
3651 "switch and case should be at the same indent\n$hereline$err");
3655 # if/while/etc brace do not go on next line, unless defining a do while loop,
3656 # or if that brace on the next line is for something else
3657 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3658 my $pre_ctx = "$1$2";
3660 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3662 if ($line =~ /^\+\t{6,}/) {
3663 WARN("DEEP_INDENTATION",
3664 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3667 my $ctx_cnt = $realcnt - $#ctx - 1;
3668 my $ctx = join("\n", @ctx);
3670 my $ctx_ln = $linenr;
3671 my $ctx_skip = $realcnt;
3673 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3674 defined $lines[$ctx_ln - 1] &&
3675 $lines[$ctx_ln - 1] =~ /^-/)) {
3676 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3677 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3681 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3682 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3684 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3686 "that open brace { should be on the previous line\n" .
3687 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3689 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3690 $ctx =~ /\)\s*\;\s*$/ &&
3691 defined $lines[$ctx_ln - 1])
3693 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3694 if ($nindent > $indent) {
3695 WARN("TRAILING_SEMICOLON",
3696 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3697 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3702 # Check relative indent for conditionals and blocks.
3703 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3704 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3705 ctx_statement_block($linenr, $realcnt, 0)
3706 if (!defined $stat);
3707 my ($s, $c) = ($stat, $cond);
3709 substr($s, 0, length($c), '');
3711 # remove inline comments
3715 # Find out how long the conditional actually is.
3716 my @newlines = ($c =~ /\n/gs);
3717 my $cond_lines = 1 + $#newlines;
3719 # Make sure we remove the line prefixes as we have
3720 # none on the first line, and are going to readd them
3723 while ($s =~ /\n\s+\\\n/) {
3724 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3727 # We want to check the first line inside the block
3728 # starting at the end of the conditional, so remove:
3729 # 1) any blank line termination
3730 # 2) any opening brace { on end of the line
3732 my $continuation = 0;
3734 $s =~ s/^.*\bdo\b//;
3736 if ($s =~ s/^\s*\\//) {
3739 if ($s =~ s/^\s*?\n//) {
3744 # Also ignore a loop construct at the end of a
3745 # preprocessor statement.
3746 if (($prevline =~ /^.\s*#\s*define\s/ ||
3747 $prevline =~ /\\\s*$/) && $continuation == 0) {
3753 while ($cond_ptr != $cond_lines) {
3754 $cond_ptr = $cond_lines;
3756 # If we see an #else/#elif then the code
3758 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3763 # 1) blank lines, they should be at 0,
3764 # 2) preprocessor lines, and
3766 if ($continuation ||
3768 $s =~ /^\s*#\s*?/ ||
3769 $s =~ /^\s*$Ident\s*:/) {
3770 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3771 if ($s =~ s/^.*?\n//) {
3777 my (undef, $sindent) = line_stats("+" . $s);
3778 my $stat_real = raw_line($linenr, $cond_lines);
3780 # Check if either of these lines are modified, else
3781 # this is not this patch's fault.
3782 if (!defined($stat_real) ||
3783 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3786 if (defined($stat_real) && $cond_lines > 1) {
3787 $stat_real = "[...]\n$stat_real";
3790 #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";
3792 if ($check && $s ne '' &&
3793 (($sindent % $tabsize) != 0 ||
3794 ($sindent < $indent) ||
3795 ($sindent == $indent &&
3796 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3797 ($sindent > $indent + $tabsize))) {
3798 WARN("SUSPECT_CODE_INDENT",
3799 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3803 # Track the 'values' across context and added lines.
3804 my $opline = $line; $opline =~ s/^./ /;
3805 my ($curr_values, $curr_vars) =
3806 annotate_values($opline . "\n", $prev_values);
3807 $curr_values = $prev_values . $curr_values;
3809 my $outline = $opline; $outline =~ s/\t/ /g;
3810 print "$linenr > .$outline\n";
3811 print "$linenr > $curr_values\n";
3812 print "$linenr > $curr_vars\n";
3814 $prev_values = substr($curr_values, -1);
3816 #ignore lines not being added
3817 next if ($line =~ /^[^\+]/);
3819 # check for dereferences that span multiple lines
3820 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3821 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3822 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3824 $line =~ /^.\s*($Lval)/;
3827 WARN("MULTILINE_DEREFERENCE",
3828 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3831 # check for declarations of signed or unsigned without int
3832 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3835 $var = "" if (!defined $var);
3836 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3840 $pointer = "" if (!defined $pointer);
3842 if (WARN("UNSPECIFIED_INT",
3843 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3845 my $decl = trim($sign) . " int ";
3846 my $comp_pointer = $pointer;
3847 $comp_pointer =~ s/\s//g;
3848 $decl .= $comp_pointer;
3849 $decl = rtrim($decl) if ($var eq "");
3850 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3855 # TEST: allow direct testing of the type matcher.
3857 if ($line =~ /^.\s*$Declare\s*$/) {
3859 "TEST: is type\n" . $herecurr);
3860 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3861 ERROR("TEST_NOT_TYPE",
3862 "TEST: is not type ($1 is)\n". $herecurr);
3866 # TEST: allow direct testing of the attribute matcher.
3868 if ($line =~ /^.\s*$Modifier\s*$/) {
3870 "TEST: is attr\n" . $herecurr);
3871 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3872 ERROR("TEST_NOT_ATTR",
3873 "TEST: is not attr ($1 is)\n". $herecurr);
3878 # check for initialisation to aggregates open brace on the next line
3879 if ($line =~ /^.\s*{/ &&
3880 $prevline =~ /(?:^|[^=])=\s*$/) {
3881 if (ERROR("OPEN_BRACE",
3882 "that open brace { should be on the previous line\n" . $hereprev) &&
3883 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3884 fix_delete_line($fixlinenr - 1, $prevrawline);
3885 fix_delete_line($fixlinenr, $rawline);
3886 my $fixedline = $prevrawline;
3887 $fixedline =~ s/\s*=\s*$/ = {/;
3888 fix_insert_line($fixlinenr, $fixedline);
3890 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3891 fix_insert_line($fixlinenr, $fixedline);
3896 # Checks which are anchored on the added line.
3899 # check for malformed paths in #include statements (uses RAW line)
3900 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3902 if ($path =~ m{//}) {
3903 ERROR("MALFORMED_INCLUDE",
3904 "malformed #include filename\n" . $herecurr);
3906 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3907 ERROR("UAPI_INCLUDE",
3908 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3912 # no C99 // comments
3913 if ($line =~ m{//}) {
3914 if (ERROR("C99_COMMENTS",
3915 "do not use C99 // comments\n" . $herecurr) &&
3917 my $line = $fixed[$fixlinenr];
3918 if ($line =~ /\/\/(.*)$/) {
3919 my $comment = trim($1);
3920 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3924 # Remove C99 comments.
3926 $opline =~ s@//.*@@;
3928 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3929 # the whole statement.
3930 #print "APW <$lines[$realline_next - 1]>\n";
3931 if (defined $realline_next &&
3932 exists $lines[$realline_next - 1] &&
3933 !defined $suppress_export{$realline_next} &&
3934 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3935 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3936 # Handle definitions which produce identifiers with
3939 # EXPORT_SYMBOL(something_foo);
3941 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3942 $name =~ /^${Ident}_$2/) {
3943 #print "FOO C name<$name>\n";
3944 $suppress_export{$realline_next} = 1;
3946 } elsif ($stat !~ /(?:
3948 ^.DEFINE_$Ident\(\Q$name\E\)|
3949 ^.DECLARE_$Ident\(\Q$name\E\)|
3950 ^.LIST_HEAD\(\Q$name\E\)|
3951 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3952 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3954 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3955 $suppress_export{$realline_next} = 2;
3957 $suppress_export{$realline_next} = 1;
3960 if (!defined $suppress_export{$linenr} &&
3961 $prevline =~ /^.\s*$/ &&
3962 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3963 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3964 #print "FOO B <$lines[$linenr - 1]>\n";
3965 $suppress_export{$linenr} = 2;
3967 if (defined $suppress_export{$linenr} &&
3968 $suppress_export{$linenr} == 2) {
3969 WARN("EXPORT_SYMBOL",
3970 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3973 # check for global initialisers.
3974 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3975 if (ERROR("GLOBAL_INITIALISERS",
3976 "do not initialise globals to $1\n" . $herecurr) &&
3978 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3981 # check for static initialisers.
3982 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3983 if (ERROR("INITIALISED_STATIC",
3984 "do not initialise statics to $1\n" .
3987 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3991 # check for misordered declarations of char/short/int/long with signed/unsigned
3992 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3994 WARN("MISORDERED_TYPE",
3995 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3998 # check for unnecessary <signed> int declarations of short/long/long long
3999 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4000 my $type = trim($1);
4001 next if ($type !~ /\bint\b/);
4002 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4003 my $new_type = $type;
4004 $new_type =~ s/\b\s*int\s*\b/ /;
4005 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4006 $new_type =~ s/^const\s+//;
4007 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4008 $new_type = "const $new_type" if ($type =~ /^const\b/);
4009 $new_type =~ s/\s+/ /g;
4010 $new_type = trim($new_type);
4011 if (WARN("UNNECESSARY_INT",
4012 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4014 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4018 # check for static const char * arrays.
4019 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4020 WARN("STATIC_CONST_CHAR_ARRAY",
4021 "static const char * array should probably be static const char * const\n" .
4025 # check for initialized const char arrays that should be static const
4026 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4027 if (WARN("STATIC_CONST_CHAR_ARRAY",
4028 "const array should probably be static const\n" . $herecurr) &&
4030 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4034 # check for static char foo[] = "bar" declarations.
4035 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4036 WARN("STATIC_CONST_CHAR_ARRAY",
4037 "static char array declaration should probably be static const char\n" .
4041 # check for const <foo> const where <foo> is not a pointer or array type
4042 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4044 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4046 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4047 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4049 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4053 # check for non-global char *foo[] = {"bar", ...} declarations.
4054 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4055 WARN("STATIC_CONST_CHAR_ARRAY",
4056 "char * array declaration might be better as static const\n" .
4060 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4061 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4063 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4065 if (WARN("ARRAY_SIZE",
4066 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4068 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4073 # check for function declarations without arguments like "int foo()"
4074 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4075 if (ERROR("FUNCTION_WITHOUT_ARGS",
4076 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4078 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4082 # check for new typedefs, only function parameters and sparse annotations
4084 if ($line =~ /\btypedef\s/ &&
4085 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4086 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4087 $line !~ /\b$typeTypedefs\b/ &&
4088 $line !~ /\b__bitwise\b/) {
4089 WARN("NEW_TYPEDEFS",
4090 "do not add new typedefs\n" . $herecurr);
4093 # * goes on variable not on type
4095 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4097 my ($ident, $from, $to) = ($1, $2, $2);
4099 # Should start with a space.
4100 $to =~ s/^(\S)/ $1/;
4101 # Should not end with a space.
4103 # '*'s should not have spaces between.
4104 while ($to =~ s/\*\s+\*/\*\*/) {
4107 ## print "1: from<$from> to<$to> ident<$ident>\n";
4109 if (ERROR("POINTER_LOCATION",
4110 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4112 my $sub_from = $ident;
4113 my $sub_to = $ident;
4114 $sub_to =~ s/\Q$from\E/$to/;
4115 $fixed[$fixlinenr] =~
4116 s@\Q$sub_from\E@$sub_to@;
4120 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4122 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4124 # Should start with a space.
4125 $to =~ s/^(\S)/ $1/;
4126 # Should not end with a space.
4128 # '*'s should not have spaces between.
4129 while ($to =~ s/\*\s+\*/\*\*/) {
4131 # Modifiers should have spaces.
4132 $to =~ s/(\b$Modifier$)/$1 /;
4134 ## print "2: from<$from> to<$to> ident<$ident>\n";
4135 if ($from ne $to && $ident !~ /^$Modifier$/) {
4136 if (ERROR("POINTER_LOCATION",
4137 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4140 my $sub_from = $match;
4141 my $sub_to = $match;
4142 $sub_to =~ s/\Q$from\E/$to/;
4143 $fixed[$fixlinenr] =~
4144 s@\Q$sub_from\E@$sub_to@;
4149 # avoid BUG() or BUG_ON()
4150 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4151 my $msg_level = \&WARN;
4152 $msg_level = \&CHK if ($file);
4153 &{$msg_level}("AVOID_BUG",
4154 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4157 # avoid LINUX_VERSION_CODE
4158 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4159 WARN("LINUX_VERSION_CODE",
4160 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4163 # check for uses of printk_ratelimit
4164 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4165 WARN("PRINTK_RATELIMITED",
4166 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4169 # printk should use KERN_* levels
4170 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4171 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4172 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4175 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4177 my $level = lc($orig);
4178 $level = "warn" if ($level eq "warning");
4179 my $level2 = $level;
4180 $level2 = "dbg" if ($level eq "debug");
4181 WARN("PREFER_PR_LEVEL",
4182 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4185 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4187 my $level = lc($orig);
4188 $level = "warn" if ($level eq "warning");
4189 $level = "dbg" if ($level eq "debug");
4190 WARN("PREFER_DEV_LEVEL",
4191 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4194 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4195 # number of false positives, but assembly files are not checked, so at
4196 # least the arch entry code will not trigger this warning.
4197 if ($line =~ /\bENOSYS\b/) {
4199 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4202 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4203 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4204 # Similarly to ENOSYS warning a small number of false positives is expected.
4205 if (!$file && $line =~ /\bENOTSUPP\b/) {
4206 if (WARN("ENOTSUPP",
4207 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4209 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4213 # function brace can't be on same line, except for #defines of do while,
4214 # or if closed on same line
4215 if ($perl_version_ok &&
4216 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4217 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4219 if (ERROR("OPEN_BRACE",
4220 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4222 fix_delete_line($fixlinenr, $rawline);
4223 my $fixed_line = $rawline;
4224 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4227 fix_insert_line($fixlinenr, ltrim($line1));
4228 fix_insert_line($fixlinenr, "\+{");
4229 if ($line2 !~ /^\s*$/) {
4230 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4235 # open braces for enum, union and struct go on the same line.
4236 if ($line =~ /^.\s*{/ &&
4237 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4238 if (ERROR("OPEN_BRACE",
4239 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4240 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4241 fix_delete_line($fixlinenr - 1, $prevrawline);
4242 fix_delete_line($fixlinenr, $rawline);
4243 my $fixedline = rtrim($prevrawline) . " {";
4244 fix_insert_line($fixlinenr, $fixedline);
4245 $fixedline = $rawline;
4246 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4247 if ($fixedline !~ /^\+\s*$/) {
4248 fix_insert_line($fixlinenr, $fixedline);
4253 # missing space after union, struct or enum definition
4254 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4256 "missing space after $1 definition\n" . $herecurr) &&
4258 $fixed[$fixlinenr] =~
4259 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4263 # Function pointer declarations
4264 # check spacing between type, funcptr, and args
4265 # canonical declaration is "type (*funcptr)(args...)"
4266 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4268 my $pre_pointer_space = $2;
4269 my $post_pointer_space = $3;
4271 my $post_funcname_space = $5;
4272 my $pre_args_space = $6;
4274 # the $Declare variable will capture all spaces after the type
4275 # so check it for a missing trailing missing space but pointer return types
4276 # don't need a space so don't warn for those.
4277 my $post_declare_space = "";
4278 if ($declare =~ /(\s+)$/) {
4279 $post_declare_space = $1;
4280 $declare = rtrim($declare);
4282 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4284 "missing space after return type\n" . $herecurr);
4285 $post_declare_space = " ";
4288 # unnecessary space "type (*funcptr)(args...)"
4289 # This test is not currently implemented because these declarations are
4291 # int foo(int bar, ...)
4292 # and this is form shouldn't/doesn't generate a checkpatch warning.
4294 # elsif ($declare =~ /\s{2,}$/) {
4296 # "Multiple spaces after return type\n" . $herecurr);
4299 # unnecessary space "type ( *funcptr)(args...)"
4300 if (defined $pre_pointer_space &&
4301 $pre_pointer_space =~ /^\s/) {
4303 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4306 # unnecessary space "type (* funcptr)(args...)"
4307 if (defined $post_pointer_space &&
4308 $post_pointer_space =~ /^\s/) {
4310 "Unnecessary space before function pointer name\n" . $herecurr);
4313 # unnecessary space "type (*funcptr )(args...)"
4314 if (defined $post_funcname_space &&
4315 $post_funcname_space =~ /^\s/) {
4317 "Unnecessary space after function pointer name\n" . $herecurr);
4320 # unnecessary space "type (*funcptr) (args...)"
4321 if (defined $pre_args_space &&
4322 $pre_args_space =~ /^\s/) {
4324 "Unnecessary space before function pointer arguments\n" . $herecurr);
4327 if (show_type("SPACING") && $fix) {
4328 $fixed[$fixlinenr] =~
4329 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4333 # check for spacing round square brackets; allowed:
4334 # 1. with a type on the left -- int [] a;
4335 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4336 # 3. inside a curly brace -- = { [0...10] = 5 }
4337 while ($line =~ /(.*?\s)\[/g) {
4338 my ($where, $prefix) = ($-[1], $1);
4339 if ($prefix !~ /$Type\s+$/ &&
4340 ($where != 0 || $prefix !~ /^.\s+$/) &&
4341 $prefix !~ /[{,:]\s+$/) {
4342 if (ERROR("BRACKET_SPACE",
4343 "space prohibited before open square bracket '['\n" . $herecurr) &&
4345 $fixed[$fixlinenr] =~
4346 s/^(\+.*?)\s+\[/$1\[/;
4351 # check for spaces between functions and their parentheses.
4352 while ($line =~ /($Ident)\s+\(/g) {
4354 my $ctx_before = substr($line, 0, $-[1]);
4355 my $ctx = "$ctx_before$name";
4357 # Ignore those directives where spaces _are_ permitted.
4359 if|for|while|switch|return|case|
4360 volatile|__volatile__|
4361 __attribute__|format|__extension__|
4364 # cpp #define statements have non-optional spaces, ie
4365 # if there is a space between the name and the open
4366 # parenthesis it is simply not a parameter group.
4367 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4369 # cpp #elif statement condition may start with a (
4370 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4372 # If this whole things ends with a type its most
4373 # likely a typedef for a function.
4374 } elsif ($ctx =~ /$Type$/) {
4378 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4380 $fixed[$fixlinenr] =~
4381 s/\b$name\s+\(/$name\(/;
4386 # Check operator spacing.
4387 if (!($line=~/\#\s*include/)) {
4388 my $fixed_line = "";
4392 <<=|>>=|<=|>=|==|!=|
4393 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4394 =>|->|<<|>>|<|>|=|!|~|
4395 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4398 my @elements = split(/($ops|;)/, $opline);
4400 ## print("element count: <" . $#elements . ">\n");
4401 ## foreach my $el (@elements) {
4402 ## print("el: <$el>\n");
4405 my @fix_elements = ();
4408 foreach my $el (@elements) {
4409 push(@fix_elements, substr($rawline, $off, length($el)));
4410 $off += length($el);
4415 my $blank = copy_spacing($opline);
4416 my $last_after = -1;
4418 for (my $n = 0; $n < $#elements; $n += 2) {
4420 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4422 ## print("n: <$n> good: <$good>\n");
4424 $off += length($elements[$n]);
4426 # Pick up the preceding and succeeding characters.
4427 my $ca = substr($opline, 0, $off);
4429 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4430 $cc = substr($opline, $off + length($elements[$n + 1]));
4432 my $cb = "$ca$;$cc";
4435 $a = 'V' if ($elements[$n] ne '');
4436 $a = 'W' if ($elements[$n] =~ /\s$/);
4437 $a = 'C' if ($elements[$n] =~ /$;$/);
4438 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4439 $a = 'O' if ($elements[$n] eq '');
4440 $a = 'E' if ($ca =~ /^\s*$/);
4442 my $op = $elements[$n + 1];
4445 if (defined $elements[$n + 2]) {
4446 $c = 'V' if ($elements[$n + 2] ne '');
4447 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4448 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4449 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4450 $c = 'O' if ($elements[$n + 2] eq '');
4451 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4456 my $ctx = "${a}x${c}";
4458 my $at = "(ctx:$ctx)";
4460 my $ptr = substr($blank, 0, $off) . "^";
4461 my $hereptr = "$hereline$ptr\n";
4463 # Pull out the value of this operator.
4464 my $op_type = substr($curr_values, $off + 1, 1);
4466 # Get the full operator variant.
4467 my $opv = $op . substr($curr_vars, $off, 1);
4469 # Ignore operators passed as parameters.
4470 if ($op_type ne 'V' &&
4471 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4474 # } elsif ($op =~ /^$;+$/) {
4476 # ; should have either the end of line or a space or \ after it
4477 } elsif ($op eq ';') {
4478 if ($ctx !~ /.x[WEBC]/ &&
4479 $cc !~ /^\\/ && $cc !~ /^;/) {
4480 if (ERROR("SPACING",
4481 "space required after that '$op' $at\n" . $hereptr)) {
4482 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4488 } elsif ($op eq '//') {
4490 # : when part of a bitfield
4491 } elsif ($opv eq ':B') {
4492 # skip the bitfield test for now
4496 } elsif ($op eq '->') {
4497 if ($ctx =~ /Wx.|.xW/) {
4498 if (ERROR("SPACING",
4499 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4500 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4501 if (defined $fix_elements[$n + 2]) {
4502 $fix_elements[$n + 2] =~ s/^\s+//;
4508 # , must not have a space before and must have a space on the right.
4509 } elsif ($op eq ',') {
4510 my $rtrim_before = 0;
4511 my $space_after = 0;
4512 if ($ctx =~ /Wx./) {
4513 if (ERROR("SPACING",
4514 "space prohibited before that '$op' $at\n" . $hereptr)) {
4519 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4520 if (ERROR("SPACING",
4521 "space required after that '$op' $at\n" . $hereptr)) {
4527 if ($rtrim_before || $space_after) {
4528 if ($rtrim_before) {
4529 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4531 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4538 # '*' as part of a type definition -- reported already.
4539 } elsif ($opv eq '*_') {
4540 #warn "'*' is part of type\n";
4542 # unary operators should have a space before and
4543 # none after. May be left adjacent to another
4544 # unary operator, or a cast
4545 } elsif ($op eq '!' || $op eq '~' ||
4546 $opv eq '*U' || $opv eq '-U' ||
4547 $opv eq '&U' || $opv eq '&&U') {
4548 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4549 if (ERROR("SPACING",
4550 "space required before that '$op' $at\n" . $hereptr)) {
4551 if ($n != $last_after + 2) {
4552 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4557 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4558 # A unary '*' may be const
4560 } elsif ($ctx =~ /.xW/) {
4561 if (ERROR("SPACING",
4562 "space prohibited after that '$op' $at\n" . $hereptr)) {
4563 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4564 if (defined $fix_elements[$n + 2]) {
4565 $fix_elements[$n + 2] =~ s/^\s+//;
4571 # unary ++ and unary -- are allowed no space on one side.
4572 } elsif ($op eq '++' or $op eq '--') {
4573 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4574 if (ERROR("SPACING",
4575 "space required one side of that '$op' $at\n" . $hereptr)) {
4576 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4580 if ($ctx =~ /Wx[BE]/ ||
4581 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4582 if (ERROR("SPACING",
4583 "space prohibited before that '$op' $at\n" . $hereptr)) {
4584 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4588 if ($ctx =~ /ExW/) {
4589 if (ERROR("SPACING",
4590 "space prohibited after that '$op' $at\n" . $hereptr)) {
4591 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4592 if (defined $fix_elements[$n + 2]) {
4593 $fix_elements[$n + 2] =~ s/^\s+//;
4599 # << and >> may either have or not have spaces both sides
4600 } elsif ($op eq '<<' or $op eq '>>' or
4601 $op eq '&' or $op eq '^' or $op eq '|' or
4602 $op eq '+' or $op eq '-' or
4603 $op eq '*' or $op eq '/' or
4607 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4609 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4610 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4611 $fix_elements[$n + 2] =~ s/^\s+//;
4614 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4616 "space preferred before that '$op' $at\n" . $hereptr)) {
4617 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4621 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4622 if (ERROR("SPACING",
4623 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4624 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4625 if (defined $fix_elements[$n + 2]) {
4626 $fix_elements[$n + 2] =~ s/^\s+//;
4632 # A colon needs no spaces before when it is
4633 # terminating a case value or a label.
4634 } elsif ($opv eq ':C' || $opv eq ':L') {
4635 if ($ctx =~ /Wx./) {
4636 if (ERROR("SPACING",
4637 "space prohibited before that '$op' $at\n" . $hereptr)) {
4638 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4643 # All the others need spaces both sides.
4644 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4647 # Ignore email addresses <foo@bar>
4649 $cc =~ /^\S+\@\S+>/) ||
4651 $ca =~ /<\S+\@\S+$/))
4656 # for asm volatile statements
4657 # ignore a colon with another
4658 # colon immediately before or after
4660 ($ca =~ /:$/ || $cc =~ /^:/)) {
4664 # messages are ERROR, but ?: are CHK
4666 my $msg_level = \&ERROR;
4667 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4669 if (&{$msg_level}("SPACING",
4670 "spaces required around that '$op' $at\n" . $hereptr)) {
4671 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4672 if (defined $fix_elements[$n + 2]) {
4673 $fix_elements[$n + 2] =~ s/^\s+//;
4679 $off += length($elements[$n + 1]);
4681 ## print("n: <$n> GOOD: <$good>\n");
4683 $fixed_line = $fixed_line . $good;
4686 if (($#elements % 2) == 0) {
4687 $fixed_line = $fixed_line . $fix_elements[$#elements];
4690 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4691 $fixed[$fixlinenr] = $fixed_line;
4697 # check for whitespace before a non-naked semicolon
4698 if ($line =~ /^\+.*\S\s+;\s*$/) {
4700 "space prohibited before semicolon\n" . $herecurr) &&
4702 1 while $fixed[$fixlinenr] =~
4703 s/^(\+.*\S)\s+;/$1;/;
4707 # check for multiple assignments
4708 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4709 CHK("MULTIPLE_ASSIGNMENTS",
4710 "multiple assignments should be avoided\n" . $herecurr);
4713 ## # check for multiple declarations, allowing for a function declaration
4715 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4716 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4718 ## # Remove any bracketed sections to ensure we do not
4719 ## # falsly report the parameters of functions.
4721 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4723 ## if ($ln =~ /,/) {
4724 ## WARN("MULTIPLE_DECLARATION",
4725 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4729 #need space before brace following if, while, etc
4730 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4731 $line =~ /\b(?:else|do)\{/) {
4732 if (ERROR("SPACING",
4733 "space required before the open brace '{'\n" . $herecurr) &&
4735 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4739 ## # check for blank lines before declarations
4740 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4741 ## $prevrawline =~ /^.\s*$/) {
4743 ## "No blank lines before declarations\n" . $hereprev);
4747 # closing brace should have a space following it when it has anything
4749 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4750 if (ERROR("SPACING",
4751 "space required after that close brace '}'\n" . $herecurr) &&
4753 $fixed[$fixlinenr] =~
4754 s/}((?!(?:,|;|\)))\S)/} $1/;
4758 # check spacing on square brackets
4759 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4760 if (ERROR("SPACING",
4761 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4763 $fixed[$fixlinenr] =~
4767 if ($line =~ /\s\]/) {
4768 if (ERROR("SPACING",
4769 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4771 $fixed[$fixlinenr] =~
4776 # check spacing on parentheses
4777 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4778 $line !~ /for\s*\(\s+;/) {
4779 if (ERROR("SPACING",
4780 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4782 $fixed[$fixlinenr] =~
4786 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4787 $line !~ /for\s*\(.*;\s+\)/ &&
4788 $line !~ /:\s+\)/) {
4789 if (ERROR("SPACING",
4790 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4792 $fixed[$fixlinenr] =~
4797 # check unnecessary parentheses around addressof/dereference single $Lvals
4798 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4800 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4802 if (CHK("UNNECESSARY_PARENTHESES",
4803 "Unnecessary parentheses around $var\n" . $herecurr) &&
4805 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4809 # check for unnecessary parentheses around function pointer uses
4810 # ie: (foo->bar)(); should be foo->bar();
4811 # but not "if (foo->bar) (" to avoid some false positives
4812 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4814 if (CHK("UNNECESSARY_PARENTHESES",
4815 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4817 my $var2 = deparenthesize($var);
4819 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4823 # check for unnecessary parentheses around comparisons in if uses
4824 # when !drivers/staging or command-line uses --strict
4825 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4826 $perl_version_ok && defined($stat) &&
4827 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4829 my $test = substr($2, 1, -1);
4831 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4833 # avoid parentheses around potential macro args
4834 next if ($match =~ /^\s*\w+\s*$/);
4835 if (!defined($herectx)) {
4836 $herectx = $here . "\n";
4837 my $cnt = statement_rawlines($if_stat);
4838 for (my $n = 0; $n < $cnt; $n++) {
4839 my $rl = raw_line($linenr, $n);
4840 $herectx .= $rl . "\n";
4841 last if $rl =~ /^[ \+].*\{/;
4844 CHK("UNNECESSARY_PARENTHESES",
4845 "Unnecessary parentheses around '$match'\n" . $herectx);
4849 #goto labels aren't indented, allow a single space however
4850 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4851 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4852 if (WARN("INDENTED_LABEL",
4853 "labels should not be indented\n" . $herecurr) &&
4855 $fixed[$fixlinenr] =~
4860 # return is not a function
4861 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4863 if ($perl_version_ok &&
4864 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4866 $value = deparenthesize($value);
4867 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4868 ERROR("RETURN_PARENTHESES",
4869 "return is not a function, parentheses are not required\n" . $herecurr);
4871 } elsif ($spacing !~ /\s+/) {
4873 "space required before the open parenthesis '('\n" . $herecurr);
4877 # unnecessary return in a void function
4878 # at end-of-function, with the previous line a single leading tab, then return;
4879 # and the line before that not a goto label target like "out:"
4880 if ($sline =~ /^[ \+]}\s*$/ &&
4881 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4883 $lines[$linenr - 3] =~ /^[ +]/ &&
4884 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4886 "void function return statements are not generally useful\n" . $hereprev);
4889 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4890 if ($perl_version_ok &&
4891 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4892 my $openparens = $1;
4893 my $count = $openparens =~ tr@\(@\(@;
4895 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4896 my $comp = $4; #Not $1 because of $LvalOrFunc
4897 $msg = " - maybe == should be = ?" if ($comp eq "==");
4898 WARN("UNNECESSARY_PARENTHESES",
4899 "Unnecessary parentheses$msg\n" . $herecurr);
4903 # comparisons with a constant or upper case identifier on the left
4904 # avoid cases like "foo + BAR < baz"
4905 # only fix matches surrounded by parentheses to avoid incorrect
4906 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4907 if ($perl_version_ok &&
4908 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4913 my $newcomp = $comp;
4914 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4915 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4916 WARN("CONSTANT_COMPARISON",
4917 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4921 } elsif ($comp eq "<=") {
4923 } elsif ($comp eq ">") {
4925 } elsif ($comp eq ">=") {
4928 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4932 # Return of what appears to be an errno should normally be negative
4933 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4935 if ($name ne 'EOF' && $name ne 'ERROR') {
4936 WARN("USE_NEGATIVE_ERRNO",
4937 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4941 # Need a space before open parenthesis after if, while etc
4942 if ($line =~ /\b(if|while|for|switch)\(/) {
4943 if (ERROR("SPACING",
4944 "space required before the open parenthesis '('\n" . $herecurr) &&
4946 $fixed[$fixlinenr] =~
4947 s/\b(if|while|for|switch)\(/$1 \(/;
4951 # Check for illegal assignment in if conditional -- and check for trailing
4952 # statements after the conditional.
4953 if ($line =~ /do\s*(?!{)/) {
4954 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4955 ctx_statement_block($linenr, $realcnt, 0)
4956 if (!defined $stat);
4957 my ($stat_next) = ctx_statement_block($line_nr_next,
4958 $remain_next, $off_next);
4959 $stat_next =~ s/\n./\n /g;
4960 ##print "stat<$stat> stat_next<$stat_next>\n";
4962 if ($stat_next =~ /^\s*while\b/) {
4963 # If the statement carries leading newlines,
4964 # then count those as offsets.
4966 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4968 statement_rawlines($whitespace) - 1;
4970 $suppress_whiletrailers{$line_nr_next +
4974 if (!defined $suppress_whiletrailers{$linenr} &&
4975 defined($stat) && defined($cond) &&
4976 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4977 my ($s, $c) = ($stat, $cond);
4979 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4980 ERROR("ASSIGN_IN_IF",
4981 "do not use assignment in if condition\n" . $herecurr);
4984 # Find out what is on the end of the line after the
4986 substr($s, 0, length($c), '');
4988 $s =~ s/$;//g; # Remove any comments
4989 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4990 $c !~ /}\s*while\s*/)
4992 # Find out how long the conditional actually is.
4993 my @newlines = ($c =~ /\n/gs);
4994 my $cond_lines = 1 + $#newlines;
4997 $stat_real = raw_line($linenr, $cond_lines)
4998 . "\n" if ($cond_lines);
4999 if (defined($stat_real) && $cond_lines > 1) {
5000 $stat_real = "[...]\n$stat_real";
5003 ERROR("TRAILING_STATEMENTS",
5004 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5008 # Check for bitwise tests written as boolean
5020 WARN("HEXADECIMAL_BOOLEAN_TEST",
5021 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5024 # if and else should not have general statements after it
5025 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5027 $s =~ s/$;//g; # Remove any comments
5028 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5029 ERROR("TRAILING_STATEMENTS",
5030 "trailing statements should be on next line\n" . $herecurr);
5033 # if should not continue a brace
5034 if ($line =~ /}\s*if\b/) {
5035 ERROR("TRAILING_STATEMENTS",
5036 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5039 # case and default should not have general statements after them
5040 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5042 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5046 ERROR("TRAILING_STATEMENTS",
5047 "trailing statements should be on next line\n" . $herecurr);
5050 # Check for }<nl>else {, these must be at the same
5051 # indent level to be relevant to each other.
5052 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5053 $previndent == $indent) {
5054 if (ERROR("ELSE_AFTER_BRACE",
5055 "else should follow close brace '}'\n" . $hereprev) &&
5056 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5057 fix_delete_line($fixlinenr - 1, $prevrawline);
5058 fix_delete_line($fixlinenr, $rawline);
5059 my $fixedline = $prevrawline;
5060 $fixedline =~ s/}\s*$//;
5061 if ($fixedline !~ /^\+\s*$/) {
5062 fix_insert_line($fixlinenr, $fixedline);
5064 $fixedline = $rawline;
5065 $fixedline =~ s/^(.\s*)else/$1} else/;
5066 fix_insert_line($fixlinenr, $fixedline);
5070 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5071 $previndent == $indent) {
5072 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5074 # Find out what is on the end of the line after the
5076 substr($s, 0, length($c), '');
5079 if ($s =~ /^\s*;/) {
5080 if (ERROR("WHILE_AFTER_BRACE",
5081 "while should follow close brace '}'\n" . $hereprev) &&
5082 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5083 fix_delete_line($fixlinenr - 1, $prevrawline);
5084 fix_delete_line($fixlinenr, $rawline);
5085 my $fixedline = $prevrawline;
5086 my $trailing = $rawline;
5087 $trailing =~ s/^\+//;
5088 $trailing = trim($trailing);
5089 $fixedline =~ s/}\s*$/} $trailing/;
5090 fix_insert_line($fixlinenr, $fixedline);
5095 #Specific variable tests
5096 while ($line =~ m{($Constant|$Lval)}g) {
5100 if ($var !~ /^$Constant$/ &&
5101 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5102 #Ignore Page<foo> variants
5103 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5104 #Ignore SI style variants like nS, mV and dB
5105 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5106 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5107 #Ignore some three character SI units explicitly, like MiB and KHz
5108 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5109 while ($var =~ m{($Ident)}g) {
5111 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5113 seed_camelcase_includes();
5114 if (!$file && !$camelcase_file_seeded) {
5115 seed_camelcase_file($realfile);
5116 $camelcase_file_seeded = 1;
5119 if (!defined $camelcase{$word}) {
5120 $camelcase{$word} = 1;
5122 "Avoid CamelCase: <$word>\n" . $herecurr);
5128 #no spaces allowed after \ in define
5129 if ($line =~ /\#\s*define.*\\\s+$/) {
5130 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5131 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5133 $fixed[$fixlinenr] =~ s/\s+$//;
5137 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5138 # itself <asm/foo.h> (uses RAW line)
5139 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5141 my $checkfile = "include/linux/$file";
5142 if (-f "$root/$checkfile" &&
5143 $realfile ne $checkfile &&
5144 $1 !~ /$allowed_asm_includes/)
5146 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5147 if ($asminclude > 0) {
5148 if ($realfile =~ m{^arch/}) {
5149 CHK("ARCH_INCLUDE_LINUX",
5150 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5152 WARN("INCLUDE_LINUX",
5153 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5159 # multi-statement macros should be enclosed in a do while loop, grab the
5160 # first statement and ensure its the whole macro if its not enclosed
5161 # in a known good container
5162 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5163 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5166 my ($off, $dstat, $dcond, $rest);
5168 my $has_flow_statement = 0;
5169 my $has_arg_concat = 0;
5170 ($dstat, $dcond, $ln, $cnt, $off) =
5171 ctx_statement_block($linenr, $realcnt, 0);
5173 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5174 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5176 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5177 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5179 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5180 my $define_args = $1;
5181 my $define_stmt = $dstat;
5184 if (defined $define_args && $define_args ne "") {
5185 $define_args = substr($define_args, 1, length($define_args) - 2);
5186 $define_args =~ s/\s*//g;
5187 $define_args =~ s/\\\+?//g;
5188 @def_args = split(",", $define_args);
5192 $dstat =~ s/\\\n.//g;
5193 $dstat =~ s/^\s*//s;
5194 $dstat =~ s/\s*$//s;
5196 # Flatten any parentheses and braces
5197 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5198 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5199 $dstat =~ s/.\[[^\[\]]*\]/1/)
5203 # Flatten any obvious string concatenation.
5204 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5205 $dstat =~ s/$Ident\s*($String)/$1/)
5209 # Make asm volatile uses seem like a generic function
5210 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5212 my $exceptions = qr{
5225 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5228 my $stmt_cnt = statement_rawlines($ctx);
5229 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5232 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5233 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5234 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5235 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5236 $dstat !~ /$exceptions/ &&
5237 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5238 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5239 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5240 $dstat !~ /^for\s*$Constant$/ && # for (...)
5241 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5242 $dstat !~ /^do\s*{/ && # do {...
5243 $dstat !~ /^\(\{/ && # ({...
5244 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5246 if ($dstat =~ /^\s*if\b/) {
5247 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5248 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5249 } elsif ($dstat =~ /;/) {
5250 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5251 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5253 ERROR("COMPLEX_MACRO",
5254 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5259 # Make $define_stmt single line, comment-free, etc
5260 my @stmt_array = split('\n', $define_stmt);
5263 foreach my $l (@stmt_array) {
5268 } elsif ($l =~ /^[\+ ]/) {
5269 $define_stmt .= substr($l, 1);
5272 $define_stmt =~ s/$;//g;
5273 $define_stmt =~ s/\s+/ /g;
5274 $define_stmt = trim($define_stmt);
5276 # check if any macro arguments are reused (ignore '...' and 'type')
5277 foreach my $arg (@def_args) {
5278 next if ($arg =~ /\.\.\./);
5279 next if ($arg =~ /^type$/i);
5280 my $tmp_stmt = $define_stmt;
5281 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5282 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5283 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5284 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5286 CHK("MACRO_ARG_REUSE",
5287 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5289 # check if any macro arguments may have other precedence issues
5290 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5291 ((defined($1) && $1 ne ',') ||
5292 (defined($2) && $2 ne ','))) {
5293 CHK("MACRO_ARG_PRECEDENCE",
5294 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5298 # check for macros with flow control, but without ## concatenation
5299 # ## concatenation is commonly a macro that defines a function so ignore those
5300 if ($has_flow_statement && !$has_arg_concat) {
5301 my $cnt = statement_rawlines($ctx);
5302 my $herectx = get_stat_here($linenr, $cnt, $here);
5304 WARN("MACRO_WITH_FLOW_CONTROL",
5305 "Macros with flow control statements should be avoided\n" . "$herectx");
5308 # check for line continuations outside of #defines, preprocessor #, and asm
5311 if ($prevline !~ /^..*\\$/ &&
5312 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5313 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5314 $line =~ /^\+.*\\$/) {
5315 WARN("LINE_CONTINUATIONS",
5316 "Avoid unnecessary line continuations\n" . $herecurr);
5320 # do {} while (0) macro tests:
5321 # single-statement macros do not need to be enclosed in do while (0) loop,
5322 # macro should not end with a semicolon
5323 if ($perl_version_ok &&
5324 $realfile !~ m@/vmlinux.lds.h$@ &&
5325 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5328 my ($off, $dstat, $dcond, $rest);
5330 ($dstat, $dcond, $ln, $cnt, $off) =
5331 ctx_statement_block($linenr, $realcnt, 0);
5334 $dstat =~ s/\\\n.//g;
5337 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5342 my $cnt = statement_rawlines($ctx);
5343 my $herectx = get_stat_here($linenr, $cnt, $here);
5345 if (($stmts =~ tr/;/;/) == 1 &&
5346 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5347 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5348 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5350 if (defined $semis && $semis ne "") {
5351 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5352 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5354 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5356 my $cnt = statement_rawlines($ctx);
5357 my $herectx = get_stat_here($linenr, $cnt, $here);
5359 WARN("TRAILING_SEMICOLON",
5360 "macros should not use a trailing semicolon\n" . "$herectx");
5364 # check for redundant bracing round if etc
5365 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5366 my ($level, $endln, @chunks) =
5367 ctx_statement_full($linenr, $realcnt, 1);
5368 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5369 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5370 if ($#chunks > 0 && $level == 0) {
5374 my $herectx = $here . "\n";
5375 my $ln = $linenr - 1;
5376 for my $chunk (@chunks) {
5377 my ($cond, $block) = @{$chunk};
5379 # If the condition carries leading newlines, then count those as offsets.
5380 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5381 my $offset = statement_rawlines($whitespace) - 1;
5383 $allowed[$allow] = 0;
5384 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5386 # We have looked at and allowed this specific line.
5387 $suppress_ifbraces{$ln + $offset} = 1;
5389 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5390 $ln += statement_rawlines($block) - 1;
5392 substr($block, 0, length($cond), '');
5394 $seen++ if ($block =~ /^\s*{/);
5396 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5397 if (statement_lines($cond) > 1) {
5398 #print "APW: ALLOWED: cond<$cond>\n";
5399 $allowed[$allow] = 1;
5401 if ($block =~/\b(?:if|for|while)\b/) {
5402 #print "APW: ALLOWED: block<$block>\n";
5403 $allowed[$allow] = 1;
5405 if (statement_block_size($block) > 1) {
5406 #print "APW: ALLOWED: lines block<$block>\n";
5407 $allowed[$allow] = 1;
5412 my $sum_allowed = 0;
5413 foreach (@allowed) {
5416 if ($sum_allowed == 0) {
5418 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5419 } elsif ($sum_allowed != $allow &&
5422 "braces {} should be used on all arms of this statement\n" . $herectx);
5427 if (!defined $suppress_ifbraces{$linenr - 1} &&
5428 $line =~ /\b(if|while|for|else)\b/) {
5431 # Check the pre-context.
5432 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5433 #print "APW: ALLOWED: pre<$1>\n";
5437 my ($level, $endln, @chunks) =
5438 ctx_statement_full($linenr, $realcnt, $-[0]);
5440 # Check the condition.
5441 my ($cond, $block) = @{$chunks[0]};
5442 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5443 if (defined $cond) {
5444 substr($block, 0, length($cond), '');
5446 if (statement_lines($cond) > 1) {
5447 #print "APW: ALLOWED: cond<$cond>\n";
5450 if ($block =~/\b(?:if|for|while)\b/) {
5451 #print "APW: ALLOWED: block<$block>\n";
5454 if (statement_block_size($block) > 1) {
5455 #print "APW: ALLOWED: lines block<$block>\n";
5458 # Check the post-context.
5459 if (defined $chunks[1]) {
5460 my ($cond, $block) = @{$chunks[1]};
5461 if (defined $cond) {
5462 substr($block, 0, length($cond), '');
5464 if ($block =~ /^\s*\{/) {
5465 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5469 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5470 my $cnt = statement_rawlines($block);
5471 my $herectx = get_stat_here($linenr, $cnt, $here);
5474 "braces {} are not necessary for single statement blocks\n" . $herectx);
5478 # check for single line unbalanced braces
5479 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5480 $sline =~ /^.\s*else\s*\{\s*$/) {
5481 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5484 # check for unnecessary blank lines around braces
5485 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5487 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5488 $fix && $prevrawline =~ /^\+/) {
5489 fix_delete_line($fixlinenr - 1, $prevrawline);
5492 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5494 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5496 fix_delete_line($fixlinenr, $rawline);
5500 # no volatiles please
5501 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5502 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5504 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5507 # Check for user-visible strings broken across lines, which breaks the ability
5508 # to grep for the string. Make exceptions when the previous string ends in a
5509 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5510 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5511 if ($line =~ /^\+\s*$String/ &&
5512 $prevline =~ /"\s*$/ &&
5513 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5514 if (WARN("SPLIT_STRING",
5515 "quoted string split across lines\n" . $hereprev) &&
5517 $prevrawline =~ /^\+.*"\s*$/ &&
5518 $last_coalesced_string_linenr != $linenr - 1) {
5519 my $extracted_string = get_quoted_string($line, $rawline);
5520 my $comma_close = "";
5521 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5525 fix_delete_line($fixlinenr - 1, $prevrawline);
5526 fix_delete_line($fixlinenr, $rawline);
5527 my $fixedline = $prevrawline;
5528 $fixedline =~ s/"\s*$//;
5529 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5530 fix_insert_line($fixlinenr - 1, $fixedline);
5531 $fixedline = $rawline;
5532 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5533 if ($fixedline !~ /\+\s*$/) {
5534 fix_insert_line($fixlinenr, $fixedline);
5536 $last_coalesced_string_linenr = $linenr;
5540 # check for missing a space in a string concatenation
5541 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5542 WARN('MISSING_SPACE',
5543 "break quoted strings at a space character\n" . $hereprev);
5546 # check for an embedded function name in a string when the function is known
5547 # This does not work very well for -f --file checking as it depends on patch
5548 # context providing the function name or a single line form for in-file
5549 # function declarations
5550 if ($line =~ /^\+.*$String/ &&
5551 defined($context_function) &&
5552 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5553 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5554 WARN("EMBEDDED_FUNCTION_NAME",
5555 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5558 # check for spaces before a quoted newline
5559 if ($rawline =~ /^.*\".*\s\\n/) {
5560 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5561 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5563 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5568 # concatenated string without spaces between elements
5569 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5570 if (CHK("CONCATENATED_STRING",
5571 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5573 while ($line =~ /($String)/g) {
5574 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5575 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5576 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5581 # uncoalesced string fragments
5582 if ($line =~ /$String\s*"/) {
5583 if (WARN("STRING_FRAGMENTS",
5584 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5586 while ($line =~ /($String)(?=\s*")/g) {
5587 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5588 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5593 # check for non-standard and hex prefixed decimal printf formats
5594 my $show_L = 1; #don't show the same defect twice
5596 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5597 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5598 $string =~ s/%%/__/g;
5600 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5602 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5606 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5608 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5611 # check for 0x<decimal>
5612 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5613 ERROR("PRINTF_0XDECIMAL",
5614 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5618 # check for line continuations in quoted strings with odd counts of "
5619 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5620 WARN("LINE_CONTINUATIONS",
5621 "Avoid line continuations in quoted strings\n" . $herecurr);
5625 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5627 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5631 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5633 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5636 # check for needless "if (<foo>) fn(<foo>)" uses
5637 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5638 my $tested = quotemeta($1);
5639 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5640 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5642 if (WARN('NEEDLESS_IF',
5643 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5646 my $leading_tabs = "";
5647 my $new_leading_tabs = "";
5648 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5653 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5654 $new_leading_tabs = $1;
5655 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5662 fix_delete_line($fixlinenr - 1, $prevrawline);
5663 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5669 # check for unnecessary "Out of Memory" messages
5670 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5671 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5672 (defined $1 || defined $3) &&
5675 my $testline = $lines[$linenr - 3];
5677 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5678 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5680 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5681 $s !~ /\b__GFP_NOWARN\b/ ) {
5683 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5687 # check for logging functions with KERN_<LEVEL>
5688 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5689 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5691 if (WARN("UNNECESSARY_KERN_LEVEL",
5692 "Possible unnecessary $level\n" . $herecurr) &&
5694 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5698 # check for logging continuations
5699 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5700 WARN("LOGGING_CONTINUATION",
5701 "Avoid logging continuation uses where feasible\n" . $herecurr);
5704 # check for mask then right shift without a parentheses
5705 if ($perl_version_ok &&
5706 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5707 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5708 WARN("MASK_THEN_SHIFT",
5709 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5712 # check for pointer comparisons to NULL
5713 if ($perl_version_ok) {
5714 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5717 $equal = "" if ($4 eq "!=");
5718 if (CHK("COMPARISON_TO_NULL",
5719 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5721 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5726 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5727 if ($line =~ /(\b$InitAttribute\b)/) {
5729 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5732 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5733 ERROR("MISPLACED_INIT",
5734 "$attr should be placed after $var\n" . $herecurr)) ||
5735 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5736 WARN("MISPLACED_INIT",
5737 "$attr should be placed after $var\n" . $herecurr))) &&
5739 $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;
5744 # check for $InitAttributeData (ie: __initdata) with const
5745 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5747 $attr =~ /($InitAttributePrefix)(.*)/;
5748 my $attr_prefix = $1;
5750 if (ERROR("INIT_ATTRIBUTE",
5751 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5753 $fixed[$fixlinenr] =~
5754 s/$InitAttributeData/${attr_prefix}initconst/;
5758 # check for $InitAttributeConst (ie: __initconst) without const
5759 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5761 if (ERROR("INIT_ATTRIBUTE",
5762 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5764 my $lead = $fixed[$fixlinenr] =~
5765 /(^\+\s*(?:static\s+))/;
5767 $lead = "$lead " if ($lead !~ /^\+$/);
5768 $lead = "${lead}const ";
5769 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5773 # check for __read_mostly with const non-pointer (should just be const)
5774 if ($line =~ /\b__read_mostly\b/ &&
5775 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5776 if (ERROR("CONST_READ_MOSTLY",
5777 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5779 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5783 # don't use __constant_<foo> functions outside of include/uapi/
5784 if ($realfile !~ m@^include/uapi/@ &&
5785 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5786 my $constant_func = $1;
5787 my $func = $constant_func;
5788 $func =~ s/^__constant_//;
5789 if (WARN("CONSTANT_CONVERSION",
5790 "$constant_func should be $func\n" . $herecurr) &&
5792 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5796 # prefer usleep_range over udelay
5797 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5799 # ignore udelay's < 10, however
5800 if (! ($delay < 10) ) {
5802 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5804 if ($delay > 2000) {
5806 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5810 # warn about unexpectedly long msleep's
5811 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5814 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5818 # check for comparisons of jiffies
5819 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5820 WARN("JIFFIES_COMPARISON",
5821 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5824 # check for comparisons of get_jiffies_64()
5825 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5826 WARN("JIFFIES_COMPARISON",
5827 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5830 # warn about #ifdefs in C files
5831 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5832 # print "#ifdef in C files should be avoided\n";
5833 # print "$herecurr";
5837 # warn about spacing in #ifdefs
5838 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5839 if (ERROR("SPACING",
5840 "exactly one space required after that #$1\n" . $herecurr) &&
5842 $fixed[$fixlinenr] =~
5843 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5848 # check for spinlock_t definitions without a comment.
5849 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5850 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5852 if (!ctx_has_comment($first_line, $linenr)) {
5853 CHK("UNCOMMENTED_DEFINITION",
5854 "$1 definition without comment\n" . $herecurr);
5857 # check for memory barriers without a comment.
5863 read_barrier_depends
5865 my $barrier_stems = qr{
5873 my $all_barriers = qr{
5875 smp_(?:$barrier_stems)|
5876 virt_(?:$barrier_stems)
5879 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5880 if (!ctx_has_comment($first_line, $linenr)) {
5881 WARN("MEMORY_BARRIER",
5882 "memory barrier without comment\n" . $herecurr);
5886 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5888 if ($realfile !~ m@^include/asm-generic/@ &&
5889 $realfile !~ m@/barrier\.h$@ &&
5890 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5891 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5892 WARN("MEMORY_BARRIER",
5893 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5896 # check for waitqueue_active without a comment.
5897 if ($line =~ /\bwaitqueue_active\s*\(/) {
5898 if (!ctx_has_comment($first_line, $linenr)) {
5899 WARN("WAITQUEUE_ACTIVE",
5900 "waitqueue_active without comment\n" . $herecurr);
5904 # check for smp_read_barrier_depends and read_barrier_depends
5905 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5906 WARN("READ_BARRIER_DEPENDS",
5907 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5910 # check of hardware specific defines
5911 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5913 "architecture specific defines should be avoided\n" . $herecurr);
5916 # check that the storage class is not after a type
5917 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5918 WARN("STORAGE_CLASS",
5919 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5921 # Check that the storage class is at the beginning of a declaration
5922 if ($line =~ /\b$Storage\b/ &&
5923 $line !~ /^.\s*$Storage/ &&
5924 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5925 $1 !~ /[\,\)]\s*$/) {
5926 WARN("STORAGE_CLASS",
5927 "storage class should be at the beginning of the declaration\n" . $herecurr);
5930 # check the location of the inline attribute, that it is between
5931 # storage class and type.
5932 if ($line =~ /\b$Type\s+$Inline\b/ ||
5933 $line =~ /\b$Inline\s+$Storage\b/) {
5934 ERROR("INLINE_LOCATION",
5935 "inline keyword should sit between storage class and type\n" . $herecurr);
5938 # Check for __inline__ and __inline, prefer inline
5939 if ($realfile !~ m@\binclude/uapi/@ &&
5940 $line =~ /\b(__inline__|__inline)\b/) {
5942 "plain inline is preferred over $1\n" . $herecurr) &&
5944 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5949 # Check for __attribute__ packed, prefer __packed
5950 if ($realfile !~ m@\binclude/uapi/@ &&
5951 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5952 WARN("PREFER_PACKED",
5953 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5956 # Check for __attribute__ aligned, prefer __aligned
5957 if ($realfile !~ m@\binclude/uapi/@ &&
5958 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5959 WARN("PREFER_ALIGNED",
5960 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5963 # Check for __attribute__ section, prefer __section
5964 if ($realfile !~ m@\binclude/uapi/@ &&
5965 $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
5966 my $old = substr($rawline, $-[1], $+[1] - $-[1]);
5967 my $new = substr($old, 1, -1);
5968 if (WARN("PREFER_SECTION",
5969 "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
5971 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
5975 # Check for __attribute__ format(printf, prefer __printf
5976 if ($realfile !~ m@\binclude/uapi/@ &&
5977 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5978 if (WARN("PREFER_PRINTF",
5979 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5981 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5986 # Check for __attribute__ format(scanf, prefer __scanf
5987 if ($realfile !~ m@\binclude/uapi/@ &&
5988 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5989 if (WARN("PREFER_SCANF",
5990 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5992 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5996 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5997 if ($perl_version_ok &&
5998 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5999 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6000 $line =~ /\b__weak\b/)) {
6001 ERROR("WEAK_DECLARATION",
6002 "Using weak declarations can have unintended link defects\n" . $herecurr);
6005 # check for c99 types like uint8_t used outside of uapi/ and tools/
6006 if ($realfile !~ m@\binclude/uapi/@ &&
6007 $realfile !~ m@\btools/@ &&
6008 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6010 if ($type =~ /\b($typeC99Typedefs)\b/) {
6012 my $kernel_type = 'u';
6013 $kernel_type = 's' if ($type =~ /^_*[si]/);
6016 if (CHK("PREFER_KERNEL_TYPES",
6017 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6019 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6024 # check for cast of C90 native int or longer types constants
6025 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6028 if (WARN("TYPECAST_INT_CONSTANT",
6029 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6032 my $newconst = $const;
6033 $newconst =~ s/${Int_type}$//;
6034 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6035 if ($cast =~ /\blong\s+long\b/) {
6037 } elsif ($cast =~ /\blong\b/) {
6040 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6044 # check for sizeof(&)
6045 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6046 WARN("SIZEOF_ADDRESS",
6047 "sizeof(& should be avoided\n" . $herecurr);
6050 # check for sizeof without parenthesis
6051 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6052 if (WARN("SIZEOF_PARENTHESIS",
6053 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6055 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6059 # check for struct spinlock declarations
6060 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6061 WARN("USE_SPINLOCK_T",
6062 "struct spinlock should be spinlock_t\n" . $herecurr);
6065 # check for seq_printf uses that could be seq_puts
6066 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6067 my $fmt = get_quoted_string($line, $rawline);
6070 if (WARN("PREFER_SEQ_PUTS",
6071 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6073 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6078 # check for vsprintf extension %p<foo> misuses
6079 if ($perl_version_ok &&
6081 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6082 $1 !~ /^_*volatile_*$/) {
6085 my $lc = $stat =~ tr@\n@@;
6086 $lc = $lc + $linenr;
6087 for (my $count = $linenr; $count <= $lc; $count++) {
6091 my $bad_specifier = "";
6092 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6095 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6099 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6100 ($extension eq "f" &&
6101 defined $qualifier && $qualifier !~ /^w/)) {
6102 $bad_specifier = $specifier;
6105 if ($extension eq "x" && !defined($stat_real)) {
6106 if (!defined($stat_real)) {
6107 $stat_real = get_stat_real($linenr, $lc);
6109 WARN("VSPRINTF_SPECIFIER_PX",
6110 "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");
6113 if ($bad_specifier ne "") {
6114 my $stat_real = get_stat_real($linenr, $lc);
6115 my $ext_type = "Invalid";
6117 if ($bad_specifier =~ /p[Ff]/) {
6118 $use = " - use %pS instead";
6119 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6122 WARN("VSPRINTF_POINTER_EXTENSION",
6123 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6128 # Check for misused memsets
6129 if ($perl_version_ok &&
6131 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6137 if ($ms_size =~ /^(0x|)0$/i) {
6139 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6140 } elsif ($ms_size =~ /^(0x|)1$/i) {
6142 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6146 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6147 # if ($perl_version_ok &&
6149 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6150 # if (WARN("PREFER_ETHER_ADDR_COPY",
6151 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6153 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6157 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6158 # if ($perl_version_ok &&
6160 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6161 # WARN("PREFER_ETHER_ADDR_EQUAL",
6162 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6165 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6166 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6167 # if ($perl_version_ok &&
6169 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6173 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6174 # if (WARN("PREFER_ETH_ZERO_ADDR",
6175 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6177 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6179 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6180 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6181 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6183 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6188 # typecasts on min/max could be min_t/max_t
6189 if ($perl_version_ok &&
6191 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6192 if (defined $2 || defined $7) {
6194 my $cast1 = deparenthesize($2);
6196 my $cast2 = deparenthesize($7);
6200 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6201 $cast = "$cast1 or $cast2";
6202 } elsif ($cast1 ne "") {
6208 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6212 # check usleep_range arguments
6213 if ($perl_version_ok &&
6215 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6219 WARN("USLEEP_RANGE",
6220 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6221 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6223 WARN("USLEEP_RANGE",
6224 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6228 # check for naked sscanf
6229 if ($perl_version_ok &&
6231 $line =~ /\bsscanf\b/ &&
6232 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6233 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6234 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6235 my $lc = $stat =~ tr@\n@@;
6236 $lc = $lc + $linenr;
6237 my $stat_real = get_stat_real($linenr, $lc);
6238 WARN("NAKED_SSCANF",
6239 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6242 # check for simple sscanf that should be kstrto<foo>
6243 if ($perl_version_ok &&
6245 $line =~ /\bsscanf\b/) {
6246 my $lc = $stat =~ tr@\n@@;
6247 $lc = $lc + $linenr;
6248 my $stat_real = get_stat_real($linenr, $lc);
6249 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6251 my $count = $format =~ tr@%@%@;
6253 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6254 WARN("SSCANF_TO_KSTRTO",
6255 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6260 # check for new externs in .h files.
6261 if ($realfile =~ /\.h$/ &&
6262 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6263 if (CHK("AVOID_EXTERNS",
6264 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6266 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6270 # check for new externs in .c files.
6271 if ($realfile =~ /\.c$/ && defined $stat &&
6272 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6274 my $function_name = $1;
6275 my $paren_space = $2;
6278 if (defined $cond) {
6279 substr($s, 0, length($cond), '');
6281 if ($s =~ /^\s*;/ &&
6282 $function_name ne 'uninitialized_var')
6284 WARN("AVOID_EXTERNS",
6285 "externs should be avoided in .c files\n" . $herecurr);
6288 if ($paren_space =~ /\n/) {
6289 WARN("FUNCTION_ARGUMENTS",
6290 "arguments for function declarations should follow identifier\n" . $herecurr);
6293 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6294 $stat =~ /^.\s*extern\s+/)
6296 WARN("AVOID_EXTERNS",
6297 "externs should be avoided in .c files\n" . $herecurr);
6300 # check for function declarations that have arguments without identifier names
6301 # while avoiding uninitialized_var(x)
6302 if (defined $stat &&
6303 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:($Ident)|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6305 (defined($1) && $1 ne "uninitialized_var")) &&
6307 my $args = trim($2);
6308 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6310 if ($arg =~ /^$Type$/ &&
6311 $arg !~ /enum\s+$Ident$/) {
6312 WARN("FUNCTION_ARGUMENTS",
6313 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6318 # check for function definitions
6319 if ($perl_version_ok &&
6321 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6322 $context_function = $1;
6324 # check for multiline function definition with misplaced open brace
6326 my $cnt = statement_rawlines($stat);
6327 my $herectx = $here . "\n";
6328 for (my $n = 0; $n < $cnt; $n++) {
6329 my $rl = raw_line($linenr, $n);
6330 $herectx .= $rl . "\n";
6331 $ok = 1 if ($rl =~ /^[ \+]\{/);
6332 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6333 last if $rl =~ /^[ \+].*\{/;
6337 "open brace '{' following function definitions go on the next line\n" . $herectx);
6341 # checks for new __setup's
6342 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6345 if (!grep(/$name/, @setup_docs)) {
6346 CHK("UNDOCUMENTED_SETUP",
6347 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6351 # check for pointless casting of alloc functions
6352 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6353 WARN("UNNECESSARY_CASTS",
6354 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6358 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6359 if ($perl_version_ok &&
6360 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6361 CHK("ALLOC_SIZEOF_STRUCT",
6362 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6365 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6366 if ($perl_version_ok &&
6368 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6372 my $newfunc = "kmalloc_array";
6373 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6376 if ($a1 =~ /^sizeof\s*\S/) {
6380 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6381 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6382 my $cnt = statement_rawlines($stat);
6383 my $herectx = get_stat_here($linenr, $cnt, $here);
6385 if (WARN("ALLOC_WITH_MULTIPLY",
6386 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6389 $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;
6394 # check for krealloc arg reuse
6395 if ($perl_version_ok &&
6396 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6398 WARN("KREALLOC_ARG_REUSE",
6399 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6402 # check for alloc argument mismatch
6403 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6404 WARN("ALLOC_ARRAY_ARGS",
6405 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6408 # check for multiple semicolons
6409 if ($line =~ /;\s*;\s*$/) {
6410 if (WARN("ONE_SEMICOLON",
6411 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6413 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6417 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6418 if ($realfile !~ m@^include/uapi/@ &&
6419 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6421 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6422 if (CHK("BIT_MACRO",
6423 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6425 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6429 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6430 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6432 if (WARN("PREFER_IS_ENABLED",
6433 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6435 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6439 # check for case / default statements not preceded by break/fallthrough/switch
6440 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6442 my $has_statement = 0;
6444 my $prevline = $linenr;
6445 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6447 my $rline = $rawlines[$prevline - 1];
6448 my $fline = $lines[$prevline - 1];
6449 last if ($fline =~ /^\@\@/);
6450 next if ($fline =~ /^\-/);
6451 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6452 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6453 next if ($fline =~ /^.[\s$;]*$/);
6456 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6458 if (!$has_break && $has_statement) {
6459 WARN("MISSING_BREAK",
6460 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6464 # check for /* fallthrough */ like comment, prefer fallthrough;
6465 my @fallthroughs = (
6468 'lint -fallthrough[ \t]*',
6469 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6470 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6471 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6472 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6474 if ($raw_comment ne '') {
6475 foreach my $ft (@fallthroughs) {
6476 if ($raw_comment =~ /$ft/) {
6477 my $msg_level = \&WARN;
6478 $msg_level = \&CHK if ($file);
6479 &{$msg_level}("PREFER_FALLTHROUGH",
6480 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6486 # check for switch/default statements without a break;
6487 if ($perl_version_ok &&
6489 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6490 my $cnt = statement_rawlines($stat);
6491 my $herectx = get_stat_here($linenr, $cnt, $here);
6493 WARN("DEFAULT_NO_BREAK",
6494 "switch default: should use break\n" . $herectx);
6497 # check for gcc specific __FUNCTION__
6498 if ($line =~ /\b__FUNCTION__\b/) {
6499 if (WARN("USE_FUNC",
6500 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6502 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6506 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6507 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6509 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6512 # check for use of yield()
6513 if ($line =~ /\byield\s*\(\s*\)/) {
6515 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6518 # check for comparisons against true and false
6519 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6527 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6529 my $type = lc($otype);
6530 if ($type =~ /^(?:true|false)$/) {
6531 if (("$test" eq "==" && "$type" eq "true") ||
6532 ("$test" eq "!=" && "$type" eq "false")) {
6536 CHK("BOOL_COMPARISON",
6537 "Using comparison to $otype is error prone\n" . $herecurr);
6539 ## maybe suggesting a correct construct would better
6540 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6545 # check for semaphores initialized locked
6546 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6547 WARN("CONSIDER_COMPLETION",
6548 "consider using a completion\n" . $herecurr);
6551 # recommend kstrto* over simple_strto* and strict_strto*
6552 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6553 WARN("CONSIDER_KSTRTO",
6554 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6557 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6558 if ($line =~ /^.\s*__initcall\s*\(/) {
6559 WARN("USE_DEVICE_INITCALL",
6560 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6563 # check for spin_is_locked(), suggest lockdep instead
6564 if ($line =~ /\bspin_is_locked\(/) {
6566 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6569 # check for deprecated apis
6570 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6571 my $deprecated_api = $1;
6572 my $new_api = $deprecated_apis{$deprecated_api};
6573 WARN("DEPRECATED_API",
6574 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6577 # check for various structs that are normally const (ops, kgdb, device_tree)
6578 # and avoid what seem like struct definitions 'struct foo {'
6579 if ($line !~ /\bconst\b/ &&
6580 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6581 WARN("CONST_STRUCT",
6582 "struct $1 should normally be const\n" . $herecurr);
6585 # use of NR_CPUS is usually wrong
6586 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6587 if ($line =~ /\bNR_CPUS\b/ &&
6588 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6589 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6590 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6591 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6592 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6595 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6598 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6599 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6600 ERROR("DEFINE_ARCH_HAS",
6601 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6604 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6605 if ($perl_version_ok &&
6606 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6607 WARN("LIKELY_MISUSE",
6608 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6611 # nested likely/unlikely calls
6612 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6613 WARN("LIKELY_MISUSE",
6614 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6617 # whine mightly about in_atomic
6618 if ($line =~ /\bin_atomic\s*\(/) {
6619 if ($realfile =~ m@^drivers/@) {
6621 "do not use in_atomic in drivers\n" . $herecurr);
6622 } elsif ($realfile !~ m@^kernel/@) {
6624 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6628 # check for mutex_trylock_recursive usage
6629 if ($line =~ /mutex_trylock_recursive/) {
6631 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6634 # check for lockdep_set_novalidate_class
6635 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6636 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6637 if ($realfile !~ m@^kernel/lockdep@ &&
6638 $realfile !~ m@^include/linux/lockdep@ &&
6639 $realfile !~ m@^drivers/base/core@) {
6641 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6645 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6646 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6647 WARN("EXPORTED_WORLD_WRITABLE",
6648 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6651 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6652 # and whether or not function naming is typical and if
6653 # DEVICE_ATTR permissions uses are unusual too
6654 if ($perl_version_ok &&
6656 $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*\)/) {
6661 my $octal_perms = perms_to_octal($perms);
6662 if ($show =~ /^${var}_show$/ &&
6663 $store =~ /^${var}_store$/ &&
6664 $octal_perms eq "0644") {
6665 if (WARN("DEVICE_ATTR_RW",
6666 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6668 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6670 } elsif ($show =~ /^${var}_show$/ &&
6671 $store =~ /^NULL$/ &&
6672 $octal_perms eq "0444") {
6673 if (WARN("DEVICE_ATTR_RO",
6674 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6676 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6678 } elsif ($show =~ /^NULL$/ &&
6679 $store =~ /^${var}_store$/ &&
6680 $octal_perms eq "0200") {
6681 if (WARN("DEVICE_ATTR_WO",
6682 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6684 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6686 } elsif ($octal_perms eq "0644" ||
6687 $octal_perms eq "0444" ||
6688 $octal_perms eq "0200") {
6689 my $newshow = "$show";
6690 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6691 my $newstore = $store;
6692 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6694 if ($show ne $newshow) {
6695 $rename .= " '$show' to '$newshow'";
6697 if ($store ne $newstore) {
6698 $rename .= " '$store' to '$newstore'";
6700 WARN("DEVICE_ATTR_FUNCTIONS",
6701 "Consider renaming function(s)$rename\n" . $herecurr);
6703 WARN("DEVICE_ATTR_PERMS",
6704 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6708 # Mode permission misuses where it seems decimal should be octal
6709 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6710 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6711 # specific definition of not visible in sysfs.
6712 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6713 # use the default permissions
6714 if ($perl_version_ok &&
6716 $line =~ /$mode_perms_search/) {
6717 foreach my $entry (@mode_permission_funcs) {
6718 my $func = $entry->[0];
6719 my $arg_pos = $entry->[1];
6721 my $lc = $stat =~ tr@\n@@;
6722 $lc = $lc + $linenr;
6723 my $stat_real = get_stat_real($linenr, $lc);
6728 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6730 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6731 if ($stat =~ /$test/) {
6733 $val = $6 if ($skip_args ne "");
6734 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6735 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6736 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6737 ERROR("NON_OCTAL_PERMISSIONS",
6738 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6740 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6741 ERROR("EXPORTED_WORLD_WRITABLE",
6742 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6748 # check for uses of S_<PERMS> that could be octal for readability
6749 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6751 my $octal = perms_to_octal($oval);
6752 if (WARN("SYMBOLIC_PERMS",
6753 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6755 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6759 # validate content of MODULE_LICENSE against list from include/linux/module.h
6760 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6761 my $extracted_string = get_quoted_string($line, $rawline);
6762 my $valid_licenses = qr{
6765 GPL\ and\ additional\ rights|
6771 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6772 WARN("MODULE_LICENSE",
6773 "unknown module license " . $extracted_string . "\n" . $herecurr);
6777 # check for sysctl duplicate constants
6778 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6779 WARN("DUPLICATED_SYSCTL_CONST",
6780 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6784 # If we have no input at all, then there is nothing to report on
6785 # so just keep quiet.
6786 if ($#rawlines == -1) {
6790 # In mailback mode only produce a report in the negative, for
6791 # things that appear to be patches.
6792 if ($mailback && ($clean == 1 || !$is_patch)) {
6796 # This is not a patch, and we are are in 'no-patch' mode so
6798 if (!$chk_patch && !$is_patch) {
6802 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6803 ERROR("NOT_UNIFIED_DIFF",
6804 "Does not appear to be a unified-diff format patch\n");
6806 if ($is_patch && $has_commit_log && $chk_signoff) {
6807 if ($signoff == 0) {
6808 ERROR("MISSING_SIGN_OFF",
6809 "Missing Signed-off-by: line(s)\n");
6810 } elsif (!$authorsignoff) {
6811 WARN("NO_AUTHOR_SIGN_OFF",
6812 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6816 print report_dump();
6817 if ($summary && !($clean == 1 && $quiet == 1)) {
6818 print "$filename " if ($summary_file);
6819 print "total: $cnt_error errors, $cnt_warn warnings, " .
6820 (($check)? "$cnt_chk checks, " : "") .
6821 "$cnt_lines lines checked\n";
6825 # If there were any defects found and not already fixing them
6826 if (!$clean and !$fix) {
6829 NOTE: For some of the reported defects, checkpatch may be able to
6830 mechanically convert to the typical style using --fix or --fix-inplace.
6833 # If there were whitespace errors which cleanpatch can fix
6834 # then suggest that.
6835 if ($rpt_cleaners) {
6839 NOTE: Whitespace errors detected.
6840 You may wish to use scripts/cleanpatch or scripts/cleanfile
6845 if ($clean == 0 && $fix &&
6846 ("@rawlines" ne "@fixed" ||
6847 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6848 my $newfile = $filename;
6849 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6853 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6855 open($f, '>', $newfile)
6856 or die "$P: Can't open $newfile for write\n";
6857 foreach my $fixed_line (@fixed) {
6860 if ($linecount > 3) {
6861 $fixed_line =~ s/^\+//;
6862 print $f $fixed_line . "\n";
6865 print $f $fixed_line . "\n";
6873 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6875 Do _NOT_ trust the results written to this file.
6876 Do _NOT_ submit these changes without inspecting them for correctness.
6878 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6879 No warranties, expressed or implied...
6887 print "$vname has no obvious style problems and is ready for submission.\n";
6889 print "$vname has style problems, please review.\n";