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;
70 Usage: $P [OPTION]... [FILE]...
75 --no-tree run without a kernel tree
76 --no-signoff do not check for 'Signed-off-by' line
77 --patch treat FILE as patchfile (default)
78 --emacs emacs compile window format
79 --terse one line per report
80 --showfile emit diffed file position, not input file position
81 -g, --git treat FILE as a single commit or git revision range
82 single git commit with:
86 multiple git commits with:
90 git merges are ignored
91 -f, --file treat FILE as regular source file
92 --subjective, --strict enable more subjective tests
93 --list-types list the possible message types
94 --types TYPE(,TYPE2...) show only these comma separated message types
95 --ignore TYPE(,TYPE2...) ignore various comma separated message types
96 --show-types show the specific message type in the output
97 --max-line-length=n set the maximum line length, if exceeded, warn
98 --min-conf-desc-length=n set the min description length, if shorter, warn
99 --root=PATH PATH to the kernel tree root
100 --no-summary suppress the per-file summary
101 --mailback only produce a report in case of warnings/errors
102 --summary-file include the filename in summary
103 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
104 'values', 'possible', 'type', and 'attr' (default
106 --test-only=WORD report only warnings/errors containing WORD
108 --fix EXPERIMENTAL - may create horrible results
109 If correctable single-line errors exist, create
110 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
111 with potential errors corrected to the preferred
113 --fix-inplace EXPERIMENTAL - may create horrible results
114 Is the same as --fix, but overwrites the input
115 file. It's your fault if there's no backup or git
116 --ignore-perl-version override checking of perl version. expect
118 --codespell Use the codespell dictionary for spelling/typos
119 (default:/usr/share/codespell/dictionary.txt)
120 --codespellfile Use this codespell dictionary
121 --typedefsfile Read additional types from this file
122 --color[=WHEN] Use colors 'always', 'never', or only when output
123 is a terminal ('auto'). Default is 'auto'.
124 -h, --help, --version display this help and exit
126 When FILE is - read standard input.
134 return grep { !$seen{$_}++ } @_;
144 open(my $script, '<', abs_path($P)) or
145 die "$P: Can't read '$P' $!\n";
147 my $text = <$script>;
151 # Also catch when type or level is passed through a variable
152 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
155 @types = sort(uniq(@types));
156 print("#\tMessage type\n\n");
157 foreach my $type (@types) {
158 print(++$count . "\t" . $type . "\n");
164 my $conf = which_conf($configuration_file);
167 open(my $conffile, '<', "$conf")
168 or warn "$P: Can't find a readable $configuration_file file $!\n";
170 while (<$conffile>) {
173 $line =~ s/\s*\n?$//g;
177 next if ($line =~ m/^\s*#/);
178 next if ($line =~ m/^\s*$/);
180 my @words = split(" ", $line);
181 foreach my $word (@words) {
182 last if ($word =~ m/^#/);
183 push (@conf_args, $word);
187 unshift(@ARGV, @conf_args) if @conf_args;
190 # Perl's Getopt::Long allows options to take optional arguments after a space.
191 # Prevent --color by itself from consuming other arguments
193 if ($_ eq "--color" || $_ eq "-color") {
194 $_ = "--color=$color";
199 'q|quiet+' => \$quiet,
201 'signoff!' => \$chk_signoff,
202 'patch!' => \$chk_patch,
205 'showfile!' => \$showfile,
208 'subjective!' => \$check,
209 'strict!' => \$check,
210 'ignore=s' => \@ignore,
212 'show-types!' => \$show_types,
213 'list-types!' => \$list_types,
214 'max-line-length=i' => \$max_line_length,
215 'min-conf-desc-length=i' => \$min_conf_desc_length,
217 'summary!' => \$summary,
218 'mailback!' => \$mailback,
219 'summary-file!' => \$summary_file,
221 'fix-inplace!' => \$fix_inplace,
222 'ignore-perl-version!' => \$ignore_perl_version,
223 'debug=s' => \%debug,
224 'test-only=s' => \$tst_only,
225 'codespell!' => \$codespell,
226 'codespellfile=s' => \$codespellfile,
227 'typedefsfile=s' => \$typedefsfile,
228 'color=s' => \$color,
229 'no-color' => \$color, #keep old behaviors of -nocolor
230 'nocolor' => \$color, #keep old behaviors of -nocolor
237 list_types(0) if ($list_types);
239 $fix = 1 if ($fix_inplace);
240 $check_orig = $check;
244 my $perl_version_ok = 1;
245 if ($^V && $^V lt $minimum_perl_version) {
246 $perl_version_ok = 0;
247 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
248 exit(1) if (!$ignore_perl_version);
251 #if no filenames are given, push '-' to read patch from stdin
256 if ($color =~ /^[01]$/) {
258 } elsif ($color =~ /^always$/i) {
260 } elsif ($color =~ /^never$/i) {
262 } elsif ($color =~ /^auto$/i) {
263 $color = (-t STDOUT);
265 die "Invalid color mode: $color\n";
268 sub hash_save_array_words {
269 my ($hashRef, $arrayRef) = @_;
271 my @array = split(/,/, join(',', @$arrayRef));
272 foreach my $word (@array) {
273 $word =~ s/\s*\n?$//g;
276 $word =~ tr/[a-z]/[A-Z]/;
278 next if ($word =~ m/^\s*#/);
279 next if ($word =~ m/^\s*$/);
285 sub hash_show_words {
286 my ($hashRef, $prefix) = @_;
288 if (keys %$hashRef) {
289 print "\nNOTE: $prefix message types:";
290 foreach my $word (sort keys %$hashRef) {
297 hash_save_array_words(\%ignore_type, \@ignore);
298 hash_save_array_words(\%use_type, \@use);
301 my $dbg_possible = 0;
304 for my $key (keys %debug) {
306 eval "\${dbg_$key} = '$debug{$key}';";
310 my $rpt_cleaners = 0;
319 if (!top_of_kernel_tree($root)) {
320 die "$P: $root: --root does not point at a valid tree\n";
323 if (top_of_kernel_tree('.')) {
325 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
326 top_of_kernel_tree($1)) {
331 if (!defined $root) {
332 print "Must be run from the top-level dir. of a kernel tree\n";
337 my $emitted_corrupt = 0;
340 [A-Za-z_][A-Za-z\d_]*
341 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
343 our $Storage = qr{extern|static|asmlinkage};
357 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
358 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
359 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
360 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
361 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
363 # Notes to $Attribute:
364 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
386 ____cacheline_aligned|
387 ____cacheline_aligned_in_smp|
388 ____cacheline_internodealigned_in_smp|
392 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
393 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
394 our $Lval = qr{$Ident(?:$Member)*};
396 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
397 our $Binary = qr{(?i)0b[01]+$Int_type?};
398 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
399 our $Int = qr{[0-9]+$Int_type?};
400 our $Octal = qr{0[0-7]+$Int_type?};
401 our $String = qr{"[X\t]*"};
402 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
403 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
404 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
405 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
406 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
407 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
408 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
409 our $Arithmetic = qr{\+|-|\*|\/|%};
413 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
416 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
420 our $NonptrTypeMisordered;
421 our $NonptrTypeWithAttr;
425 our $DeclareMisordered;
427 our $NON_ASCII_UTF8 = qr{
428 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
429 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
430 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
431 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
432 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
433 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
434 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
438 [\x09\x0A\x0D\x20-\x7E] # ASCII
442 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
443 our $typeOtherOSTypedefs = qr{(?x:
444 u_(?:char|short|int|long) | # bsd
445 u(?:nchar|short|int|long) # sysv
447 our $typeKernelTypedefs = qr{(?x:
448 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
451 our $typeTypedefs = qr{(?x:
453 $typeOtherOSTypedefs\b|
454 $typeKernelTypedefs\b
457 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
459 our $logFunctions = qr{(?x:
460 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
461 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
463 WARN(?:_RATELIMIT|_ONCE|)|
466 seq_vprintf|seq_printf|seq_puts
469 our $signature_tags = qr{(?xi:
481 our @typeListMisordered = (
482 qr{char\s+(?:un)?signed},
483 qr{int\s+(?:(?:un)?signed\s+)?short\s},
484 qr{int\s+short(?:\s+(?:un)?signed)},
485 qr{short\s+int(?:\s+(?:un)?signed)},
486 qr{(?:un)?signed\s+int\s+short},
487 qr{short\s+(?:un)?signed},
488 qr{long\s+int\s+(?:un)?signed},
489 qr{int\s+long\s+(?:un)?signed},
490 qr{long\s+(?:un)?signed\s+int},
491 qr{int\s+(?:un)?signed\s+long},
492 qr{int\s+(?:un)?signed},
493 qr{int\s+long\s+long\s+(?:un)?signed},
494 qr{long\s+long\s+int\s+(?:un)?signed},
495 qr{long\s+long\s+(?:un)?signed\s+int},
496 qr{long\s+long\s+(?:un)?signed},
497 qr{long\s+(?:un)?signed},
502 qr{(?:(?:un)?signed\s+)?char},
503 qr{(?:(?:un)?signed\s+)?short\s+int},
504 qr{(?:(?:un)?signed\s+)?short},
505 qr{(?:(?:un)?signed\s+)?int},
506 qr{(?:(?:un)?signed\s+)?long\s+int},
507 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
508 qr{(?:(?:un)?signed\s+)?long\s+long},
509 qr{(?:(?:un)?signed\s+)?long},
518 qr{${Ident}_handler},
519 qr{${Ident}_handler_fn},
523 our $C90_int_types = qr{(?x:
524 long\s+long\s+int\s+(?:un)?signed|
525 long\s+long\s+(?:un)?signed\s+int|
526 long\s+long\s+(?:un)?signed|
527 (?:(?:un)?signed\s+)?long\s+long\s+int|
528 (?:(?:un)?signed\s+)?long\s+long|
529 int\s+long\s+long\s+(?:un)?signed|
530 int\s+(?:(?:un)?signed\s+)?long\s+long|
532 long\s+int\s+(?:un)?signed|
533 long\s+(?:un)?signed\s+int|
534 long\s+(?:un)?signed|
535 (?:(?:un)?signed\s+)?long\s+int|
536 (?:(?:un)?signed\s+)?long|
537 int\s+long\s+(?:un)?signed|
538 int\s+(?:(?:un)?signed\s+)?long|
541 (?:(?:un)?signed\s+)?int
544 our @typeListFile = ();
545 our @typeListWithAttr = (
547 qr{struct\s+$InitAttribute\s+$Ident},
548 qr{union\s+$InitAttribute\s+$Ident},
551 our @modifierList = (
554 our @modifierListFile = ();
556 our @mode_permission_funcs = (
558 ["module_param_(?:array|named|string)", 4],
559 ["module_param_array_named", 5],
560 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
561 ["proc_create(?:_data|)", 2],
562 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
563 ["IIO_DEV_ATTR_[A-Z_]+", 1],
564 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
565 ["SENSOR_TEMPLATE(?:_2|)", 3],
569 #Create a search pattern for all these functions to speed up a loop below
570 our $mode_perms_search = "";
571 foreach my $entry (@mode_permission_funcs) {
572 $mode_perms_search .= '|' if ($mode_perms_search ne "");
573 $mode_perms_search .= $entry->[0];
575 $mode_perms_search = "(?:${mode_perms_search})";
577 our %deprecated_apis = (
578 "synchronize_rcu_bh" => "synchronize_rcu",
579 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
580 "call_rcu_bh" => "call_rcu",
581 "rcu_barrier_bh" => "rcu_barrier",
582 "synchronize_sched" => "synchronize_rcu",
583 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
584 "call_rcu_sched" => "call_rcu",
585 "rcu_barrier_sched" => "rcu_barrier",
586 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
587 "cond_synchronize_sched" => "cond_synchronize_rcu",
590 #Create a search pattern for all these strings to speed up a loop below
591 our $deprecated_apis_search = "";
592 foreach my $entry (keys %deprecated_apis) {
593 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
594 $deprecated_apis_search .= $entry;
596 $deprecated_apis_search = "(?:${deprecated_apis_search})";
598 our $mode_perms_world_writable = qr{
606 our %mode_permission_string_types = (
625 #Create a search pattern for all these strings to speed up a loop below
626 our $mode_perms_string_search = "";
627 foreach my $entry (keys %mode_permission_string_types) {
628 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
629 $mode_perms_string_search .= $entry;
631 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
632 our $multi_mode_perms_string_search = qr{
633 ${single_mode_perms_string_search}
634 (?:\s*\|\s*${single_mode_perms_string_search})*
640 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
647 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
648 $curpos = pos($string);
651 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
653 $to |= $mode_permission_string_types{$match};
654 $val .= '\s*\|\s*' if ($val ne "");
658 $oval =~ s/^\s*\|\s*//;
659 $oval =~ s/\s*\|\s*$//;
660 return sprintf("%04o", $to);
663 our $allowed_asm_includes = qr{(?x:
669 # memory.h: ARM has a custom one
671 # Load common spelling mistakes and build regular expression list.
675 if (open(my $spelling, '<', $spelling_file)) {
676 while (<$spelling>) {
679 $line =~ s/\s*\n?$//g;
682 next if ($line =~ m/^\s*#/);
683 next if ($line =~ m/^\s*$/);
685 my ($suspect, $fix) = split(/\|\|/, $line);
687 $spelling_fix{$suspect} = $fix;
691 warn "No typos will be found - file '$spelling_file': $!\n";
695 if (open(my $spelling, '<', $codespellfile)) {
696 while (<$spelling>) {
699 $line =~ s/\s*\n?$//g;
702 next if ($line =~ m/^\s*#/);
703 next if ($line =~ m/^\s*$/);
704 next if ($line =~ m/, disabled/i);
708 my ($suspect, $fix) = split(/->/, $line);
710 $spelling_fix{$suspect} = $fix;
714 warn "No codespell typos will be found - file '$codespellfile': $!\n";
718 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
721 my ($wordsRef, $file) = @_;
723 if (open(my $words, '<', $file)) {
727 $line =~ s/\s*\n?$//g;
730 next if ($line =~ m/^\s*#/);
731 next if ($line =~ m/^\s*$/);
733 print("$file: '$line' invalid - ignored\n");
737 $$wordsRef .= '|' if ($$wordsRef ne "");
747 my $const_structs = "";
748 read_words(\$const_structs, $conststructsfile)
749 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
751 my $typeOtherTypedefs = "";
752 if (length($typedefsfile)) {
753 read_words(\$typeOtherTypedefs, $typedefsfile)
754 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
756 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
759 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
760 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
761 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
762 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
763 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
769 (?:$Modifier\s+|const\s+)*
771 (?:typeof|__typeof__)\s*\([^\)]*\)|
775 (?:\s+$Modifier|\s+const)*
777 $NonptrTypeMisordered = qr{
778 (?:$Modifier\s+|const\s+)*
782 (?:\s+$Modifier|\s+const)*
784 $NonptrTypeWithAttr = qr{
785 (?:$Modifier\s+|const\s+)*
787 (?:typeof|__typeof__)\s*\([^\)]*\)|
791 (?:\s+$Modifier|\s+const)*
795 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
796 (?:\s+$Inline|\s+$Modifier)*
798 $TypeMisordered = qr{
799 $NonptrTypeMisordered
800 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
801 (?:\s+$Inline|\s+$Modifier)*
803 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
804 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
808 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
810 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
811 # requires at least perl version v5.10.0
812 # Any use must be runtime checked with $^V
814 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
815 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
816 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
818 our $declaration_macros = qr{(?x:
819 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
820 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
821 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
822 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
827 return "" if (!defined($string));
829 while ($string =~ /^\s*\(.*\)\s*$/) {
830 $string =~ s@^\s*\(\s*@@;
831 $string =~ s@\s*\)\s*$@@;
834 $string =~ s@\s+@ @g;
839 sub seed_camelcase_file {
842 return if (!(-f $file));
846 open(my $include_file, '<', "$file")
847 or warn "$P: Can't read '$file' $!\n";
848 my $text = <$include_file>;
849 close($include_file);
851 my @lines = split('\n', $text);
853 foreach my $line (@lines) {
854 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
855 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
857 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
859 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
865 sub is_maintained_obsolete {
868 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
870 my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
872 return $status =~ /obsolete/i;
875 sub is_SPDX_License_valid {
878 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
880 my $root_path = abs_path($root);
881 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
882 return 0 if ($status ne "");
886 my $camelcase_seeded = 0;
887 sub seed_camelcase_includes {
888 return if ($camelcase_seeded);
891 my $camelcase_cache = "";
892 my @include_files = ();
894 $camelcase_seeded = 1;
897 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
898 chomp $git_last_include_commit;
899 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
901 my $last_mod_date = 0;
902 $files = `find $root/include -name "*.h"`;
903 @include_files = split('\n', $files);
904 foreach my $file (@include_files) {
905 my $date = POSIX::strftime("%Y%m%d%H%M",
906 localtime((stat $file)[9]));
907 $last_mod_date = $date if ($last_mod_date < $date);
909 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
912 if ($camelcase_cache ne "" && -f $camelcase_cache) {
913 open(my $camelcase_file, '<', "$camelcase_cache")
914 or warn "$P: Can't read '$camelcase_cache' $!\n";
915 while (<$camelcase_file>) {
919 close($camelcase_file);
925 $files = `git ls-files "include/*.h"`;
926 @include_files = split('\n', $files);
929 foreach my $file (@include_files) {
930 seed_camelcase_file($file);
933 if ($camelcase_cache ne "") {
934 unlink glob ".checkpatch-camelcase.*";
935 open(my $camelcase_file, '>', "$camelcase_cache")
936 or warn "$P: Can't write '$camelcase_cache' $!\n";
937 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
938 print $camelcase_file ("$_\n");
940 close($camelcase_file);
944 sub git_commit_info {
945 my ($commit, $id, $desc) = @_;
947 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
949 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
950 $output =~ s/^\s*//gm;
951 my @lines = split("\n", $output);
953 return ($id, $desc) if ($#lines < 0);
955 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
956 # Maybe one day convert this block of bash into something that returns
957 # all matching commit ids, but it's very slow...
959 # echo "checking commits $1..."
960 # git rev-list --remotes | grep -i "^$1" |
961 # while read line ; do
962 # git log --format='%H %s' -1 $line |
963 # echo "commit $(cut -c 1-12,41-)"
965 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
968 $id = substr($lines[0], 0, 12);
969 $desc = substr($lines[0], 41);
975 $chk_signoff = 0 if ($file);
980 my @fixed_inserted = ();
981 my @fixed_deleted = ();
984 # If input is git commits, extract all commits from the commit expressions.
985 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
986 die "$P: No git repository found\n" if ($git && !-e ".git");
990 foreach my $commit_expr (@ARGV) {
992 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
993 $git_range = "-$2 $1";
994 } elsif ($commit_expr =~ m/\.\./) {
995 $git_range = "$commit_expr";
997 $git_range = "-1 $commit_expr";
999 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1000 foreach my $line (split(/\n/, $lines)) {
1001 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1002 next if (!defined($1) || !defined($2));
1005 unshift(@commits, $sha1);
1006 $git_commits{$sha1} = $subject;
1009 die "$P: no git commits after extraction!\n" if (@commits == 0);
1014 for my $filename (@ARGV) {
1017 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1018 die "$P: $filename: git format-patch failed - $!\n";
1020 open($FILE, '-|', "diff -u /dev/null $filename") ||
1021 die "$P: $filename: diff failed - $!\n";
1022 } elsif ($filename eq '-') {
1023 open($FILE, '<&STDIN');
1025 open($FILE, '<', "$filename") ||
1026 die "$P: $filename: open failed - $!\n";
1028 if ($filename eq '-') {
1029 $vname = 'Your patch';
1031 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1037 push(@rawlines, $_);
1041 if ($#ARGV > 0 && $quiet == 0) {
1042 print '-' x length($vname) . "\n";
1044 print '-' x length($vname) . "\n";
1047 if (!process($filename)) {
1053 @fixed_inserted = ();
1054 @fixed_deleted = ();
1056 @modifierListFile = ();
1062 hash_show_words(\%use_type, "Used");
1063 hash_show_words(\%ignore_type, "Ignored");
1065 if (!$perl_version_ok) {
1068 NOTE: perl $^V is not modern enough to detect all possible issues.
1069 An upgrade to at least perl $minimum_perl_version is suggested.
1075 NOTE: If any of the errors are false positives, please report
1076 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1083 sub top_of_kernel_tree {
1087 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1088 "README", "Documentation", "arch", "include", "drivers",
1089 "fs", "init", "ipc", "kernel", "lib", "scripts",
1092 foreach my $check (@tree_check) {
1093 if (! -e $root . '/' . $check) {
1101 my ($formatted_email) = @_;
1107 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1110 $comment = $3 if defined $3;
1111 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1113 $comment = $2 if defined $2;
1114 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1116 $comment = $2 if defined $2;
1117 $formatted_email =~ s/\Q$address\E.*$//;
1118 $name = $formatted_email;
1119 $name = trim($name);
1120 $name =~ s/^\"|\"$//g;
1121 # If there's a name left after stripping spaces and
1122 # leading quotes, and the address doesn't have both
1123 # leading and trailing angle brackets, the address
1125 # "joe smith joe@smith.com" bad
1126 # "joe smith <joe@smith.com" bad
1127 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1134 $name = trim($name);
1135 $name =~ s/^\"|\"$//g;
1136 $address = trim($address);
1137 $address =~ s/^\<|\>$//g;
1139 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1140 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1141 $name = "\"$name\"";
1144 return ($name, $address, $comment);
1148 my ($name, $address) = @_;
1150 my $formatted_email;
1152 $name = trim($name);
1153 $name =~ s/^\"|\"$//g;
1154 $address = trim($address);
1156 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1157 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1158 $name = "\"$name\"";
1161 if ("$name" eq "") {
1162 $formatted_email = "$address";
1164 $formatted_email = "$name <$address>";
1167 return $formatted_email;
1173 foreach my $path (split(/:/, $ENV{PATH})) {
1174 if (-e "$path/$bin") {
1175 return "$path/$bin";
1185 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1186 if (-e "$path/$conf") {
1187 return "$path/$conf";
1199 for my $c (split(//, $str)) {
1203 for (; ($n % 8) != 0; $n++) {
1215 (my $res = shift) =~ tr/\t/ /c;
1222 # Drop the diff line leader and expand tabs
1224 $line = expand_tabs($line);
1226 # Pick the indent from the front of the line.
1227 my ($white) = ($line =~ /^(\s*)/);
1229 return (length($line), length($white));
1232 my $sanitise_quote = '';
1234 sub sanitise_line_reset {
1235 my ($in_comment) = @_;
1238 $sanitise_quote = '*/';
1240 $sanitise_quote = '';
1253 # Always copy over the diff marker.
1254 $res = substr($line, 0, 1);
1256 for ($off = 1; $off < length($line); $off++) {
1257 $c = substr($line, $off, 1);
1259 # Comments we are whacking completely including the begin
1260 # and end, all to $;.
1261 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1262 $sanitise_quote = '*/';
1264 substr($res, $off, 2, "$;$;");
1268 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1269 $sanitise_quote = '';
1270 substr($res, $off, 2, "$;$;");
1274 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1275 $sanitise_quote = '//';
1277 substr($res, $off, 2, $sanitise_quote);
1282 # A \ in a string means ignore the next character.
1283 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1285 substr($res, $off, 2, 'XX');
1290 if ($c eq "'" || $c eq '"') {
1291 if ($sanitise_quote eq '') {
1292 $sanitise_quote = $c;
1294 substr($res, $off, 1, $c);
1296 } elsif ($sanitise_quote eq $c) {
1297 $sanitise_quote = '';
1301 #print "c<$c> SQ<$sanitise_quote>\n";
1302 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1303 substr($res, $off, 1, $;);
1304 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1305 substr($res, $off, 1, $;);
1306 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1307 substr($res, $off, 1, 'X');
1309 substr($res, $off, 1, $c);
1313 if ($sanitise_quote eq '//') {
1314 $sanitise_quote = '';
1317 # The pathname on a #include may be surrounded by '<' and '>'.
1318 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1319 my $clean = 'X' x length($1);
1320 $res =~ s@\<.*\>@<$clean>@;
1322 # The whole of a #error is a string.
1323 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1324 my $clean = 'X' x length($1);
1325 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1328 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1330 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1336 sub get_quoted_string {
1337 my ($line, $rawline) = @_;
1339 return "" if (!defined($line) || !defined($rawline));
1340 return "" if ($line !~ m/($String)/g);
1341 return substr($rawline, $-[0], $+[0] - $-[0]);
1344 sub ctx_statement_block {
1345 my ($linenr, $remain, $off) = @_;
1346 my $line = $linenr - 1;
1349 my $coff = $off - 1;
1363 @stack = (['', 0]) if ($#stack == -1);
1365 #warn "CSB: blk<$blk> remain<$remain>\n";
1366 # If we are about to drop off the end, pull in more
1369 for (; $remain > 0; $line++) {
1370 last if (!defined $lines[$line]);
1371 next if ($lines[$line] =~ /^-/);
1374 $blk .= $lines[$line] . "\n";
1375 $len = length($blk);
1379 # Bail if there is no further context.
1380 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1384 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1390 $c = substr($blk, $off, 1);
1391 $remainder = substr($blk, $off);
1393 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1395 # Handle nested #if/#else.
1396 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1397 push(@stack, [ $type, $level ]);
1398 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1399 ($type, $level) = @{$stack[$#stack - 1]};
1400 } elsif ($remainder =~ /^#\s*endif\b/) {
1401 ($type, $level) = @{pop(@stack)};
1404 # Statement ends at the ';' or a close '}' at the
1406 if ($level == 0 && $c eq ';') {
1410 # An else is really a conditional as long as its not else if
1411 if ($level == 0 && $coff_set == 0 &&
1412 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1413 $remainder =~ /^(else)(?:\s|{)/ &&
1414 $remainder !~ /^else\s+if\b/) {
1415 $coff = $off + length($1) - 1;
1417 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1418 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1421 if (($type eq '' || $type eq '(') && $c eq '(') {
1425 if ($type eq '(' && $c eq ')') {
1427 $type = ($level != 0)? '(' : '';
1429 if ($level == 0 && $coff < $soff) {
1432 #warn "CSB: mark coff<$coff>\n";
1435 if (($type eq '' || $type eq '{') && $c eq '{') {
1439 if ($type eq '{' && $c eq '}') {
1441 $type = ($level != 0)? '{' : '';
1444 if (substr($blk, $off + 1, 1) eq ';') {
1450 # Preprocessor commands end at the newline unless escaped.
1451 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1459 # We are truly at the end, so shuffle to the next line.
1466 my $statement = substr($blk, $soff, $off - $soff + 1);
1467 my $condition = substr($blk, $soff, $coff - $soff + 1);
1469 #warn "STATEMENT<$statement>\n";
1470 #warn "CONDITION<$condition>\n";
1472 #print "coff<$coff> soff<$off> loff<$loff>\n";
1474 return ($statement, $condition,
1475 $line, $remain + 1, $off - $loff + 1, $level);
1478 sub statement_lines {
1481 # Strip the diff line prefixes and rip blank lines at start and end.
1482 $stmt =~ s/(^|\n)./$1/g;
1486 my @stmt_lines = ($stmt =~ /\n/g);
1488 return $#stmt_lines + 2;
1491 sub statement_rawlines {
1494 my @stmt_lines = ($stmt =~ /\n/g);
1496 return $#stmt_lines + 2;
1499 sub statement_block_size {
1502 $stmt =~ s/(^|\n)./$1/g;
1508 my @stmt_lines = ($stmt =~ /\n/g);
1509 my @stmt_statements = ($stmt =~ /;/g);
1511 my $stmt_lines = $#stmt_lines + 2;
1512 my $stmt_statements = $#stmt_statements + 1;
1514 if ($stmt_lines > $stmt_statements) {
1517 return $stmt_statements;
1521 sub ctx_statement_full {
1522 my ($linenr, $remain, $off) = @_;
1523 my ($statement, $condition, $level);
1527 # Grab the first conditional/block pair.
1528 ($statement, $condition, $linenr, $remain, $off, $level) =
1529 ctx_statement_block($linenr, $remain, $off);
1530 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1531 push(@chunks, [ $condition, $statement ]);
1532 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1533 return ($level, $linenr, @chunks);
1536 # Pull in the following conditional/block pairs and see if they
1537 # could continue the statement.
1539 ($statement, $condition, $linenr, $remain, $off, $level) =
1540 ctx_statement_block($linenr, $remain, $off);
1541 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1542 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1544 push(@chunks, [ $condition, $statement ]);
1547 return ($level, $linenr, @chunks);
1551 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1553 my $start = $linenr - 1;
1560 my @stack = ($level);
1561 for ($line = $start; $remain > 0; $line++) {
1562 next if ($rawlines[$line] =~ /^-/);
1565 $blk .= $rawlines[$line];
1567 # Handle nested #if/#else.
1568 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1569 push(@stack, $level);
1570 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1571 $level = $stack[$#stack - 1];
1572 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1573 $level = pop(@stack);
1576 foreach my $c (split(//, $lines[$line])) {
1577 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1583 if ($c eq $close && $level > 0) {
1585 last if ($level == 0);
1586 } elsif ($c eq $open) {
1591 if (!$outer || $level <= 1) {
1592 push(@res, $rawlines[$line]);
1595 last if ($level == 0);
1598 return ($level, @res);
1600 sub ctx_block_outer {
1601 my ($linenr, $remain) = @_;
1603 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1607 my ($linenr, $remain) = @_;
1609 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1613 my ($linenr, $remain, $off) = @_;
1615 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1618 sub ctx_block_level {
1619 my ($linenr, $remain) = @_;
1621 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1623 sub ctx_statement_level {
1624 my ($linenr, $remain, $off) = @_;
1626 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1629 sub ctx_locate_comment {
1630 my ($first_line, $end_line) = @_;
1632 # Catch a comment on the end of the line itself.
1633 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1634 return $current_comment if (defined $current_comment);
1636 # Look through the context and try and figure out if there is a
1639 $current_comment = '';
1640 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1641 my $line = $rawlines[$linenr - 1];
1643 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1646 if ($line =~ m@/\*@) {
1649 if (!$in_comment && $current_comment ne '') {
1650 $current_comment = '';
1652 $current_comment .= $line . "\n" if ($in_comment);
1653 if ($line =~ m@\*/@) {
1658 chomp($current_comment);
1659 return($current_comment);
1661 sub ctx_has_comment {
1662 my ($first_line, $end_line) = @_;
1663 my $cmt = ctx_locate_comment($first_line, $end_line);
1665 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1666 ##print "CMMT: $cmt\n";
1668 return ($cmt ne '');
1672 my ($linenr, $cnt) = @_;
1674 my $offset = $linenr - 1;
1679 $line = $rawlines[$offset++];
1680 next if (defined($line) && $line =~ /^-/);
1688 my ($linenr, $lc) = @_;
1690 my $stat_real = raw_line($linenr, 0);
1691 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1692 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1699 my ($linenr, $cnt, $here) = @_;
1701 my $herectx = $here . "\n";
1702 for (my $n = 0; $n < $cnt; $n++) {
1703 $herectx .= raw_line($linenr, $n) . "\n";
1714 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1717 $coded = sprintf("^%c", unpack('C', $2) + 64);
1726 my $av_preprocessor = 0;
1731 sub annotate_reset {
1732 $av_preprocessor = 0;
1734 @av_paren_type = ('E');
1735 $av_pend_colon = 'O';
1738 sub annotate_values {
1739 my ($stream, $type) = @_;
1742 my $var = '_' x length($stream);
1745 print "$stream\n" if ($dbg_values > 1);
1747 while (length($cur)) {
1748 @av_paren_type = ('E') if ($#av_paren_type < 0);
1749 print " <" . join('', @av_paren_type) .
1750 "> <$type> <$av_pending>" if ($dbg_values > 1);
1751 if ($cur =~ /^(\s+)/o) {
1752 print "WS($1)\n" if ($dbg_values > 1);
1753 if ($1 =~ /\n/ && $av_preprocessor) {
1754 $type = pop(@av_paren_type);
1755 $av_preprocessor = 0;
1758 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1759 print "CAST($1)\n" if ($dbg_values > 1);
1760 push(@av_paren_type, $type);
1763 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1764 print "DECLARE($1)\n" if ($dbg_values > 1);
1767 } elsif ($cur =~ /^($Modifier)\s*/) {
1768 print "MODIFIER($1)\n" if ($dbg_values > 1);
1771 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1772 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1773 $av_preprocessor = 1;
1774 push(@av_paren_type, $type);
1780 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1781 print "UNDEF($1)\n" if ($dbg_values > 1);
1782 $av_preprocessor = 1;
1783 push(@av_paren_type, $type);
1785 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1786 print "PRE_START($1)\n" if ($dbg_values > 1);
1787 $av_preprocessor = 1;
1789 push(@av_paren_type, $type);
1790 push(@av_paren_type, $type);
1793 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1794 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1795 $av_preprocessor = 1;
1797 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1801 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1802 print "PRE_END($1)\n" if ($dbg_values > 1);
1804 $av_preprocessor = 1;
1806 # Assume all arms of the conditional end as this
1807 # one does, and continue as if the #endif was not here.
1808 pop(@av_paren_type);
1809 push(@av_paren_type, $type);
1812 } elsif ($cur =~ /^(\\\n)/o) {
1813 print "PRECONT($1)\n" if ($dbg_values > 1);
1815 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1816 print "ATTR($1)\n" if ($dbg_values > 1);
1817 $av_pending = $type;
1820 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1821 print "SIZEOF($1)\n" if ($dbg_values > 1);
1827 } elsif ($cur =~ /^(if|while|for)\b/o) {
1828 print "COND($1)\n" if ($dbg_values > 1);
1832 } elsif ($cur =~/^(case)/o) {
1833 print "CASE($1)\n" if ($dbg_values > 1);
1834 $av_pend_colon = 'C';
1837 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1838 print "KEYWORD($1)\n" if ($dbg_values > 1);
1841 } elsif ($cur =~ /^(\()/o) {
1842 print "PAREN('$1')\n" if ($dbg_values > 1);
1843 push(@av_paren_type, $av_pending);
1847 } elsif ($cur =~ /^(\))/o) {
1848 my $new_type = pop(@av_paren_type);
1849 if ($new_type ne '_') {
1851 print "PAREN('$1') -> $type\n"
1852 if ($dbg_values > 1);
1854 print "PAREN('$1')\n" if ($dbg_values > 1);
1857 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1858 print "FUNC($1)\n" if ($dbg_values > 1);
1862 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1863 if (defined $2 && $type eq 'C' || $type eq 'T') {
1864 $av_pend_colon = 'B';
1865 } elsif ($type eq 'E') {
1866 $av_pend_colon = 'L';
1868 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1871 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1872 print "IDENT($1)\n" if ($dbg_values > 1);
1875 } elsif ($cur =~ /^($Assignment)/o) {
1876 print "ASSIGN($1)\n" if ($dbg_values > 1);
1879 } elsif ($cur =~/^(;|{|})/) {
1880 print "END($1)\n" if ($dbg_values > 1);
1882 $av_pend_colon = 'O';
1884 } elsif ($cur =~/^(,)/) {
1885 print "COMMA($1)\n" if ($dbg_values > 1);
1888 } elsif ($cur =~ /^(\?)/o) {
1889 print "QUESTION($1)\n" if ($dbg_values > 1);
1892 } elsif ($cur =~ /^(:)/o) {
1893 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1895 substr($var, length($res), 1, $av_pend_colon);
1896 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1901 $av_pend_colon = 'O';
1903 } elsif ($cur =~ /^(\[)/o) {
1904 print "CLOSE($1)\n" if ($dbg_values > 1);
1907 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1910 print "OPV($1)\n" if ($dbg_values > 1);
1917 substr($var, length($res), 1, $variant);
1920 } elsif ($cur =~ /^($Operators)/o) {
1921 print "OP($1)\n" if ($dbg_values > 1);
1922 if ($1 ne '++' && $1 ne '--') {
1926 } elsif ($cur =~ /(^.)/o) {
1927 print "C($1)\n" if ($dbg_values > 1);
1930 $cur = substr($cur, length($1));
1931 $res .= $type x length($1);
1935 return ($res, $var);
1939 my ($possible, $line) = @_;
1940 my $notPermitted = qr{(?:
1957 ^(?:typedef|struct|enum)\b
1959 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1960 if ($possible !~ $notPermitted) {
1961 # Check for modifiers.
1962 $possible =~ s/\s*$Storage\s*//g;
1963 $possible =~ s/\s*$Sparse\s*//g;
1964 if ($possible =~ /^\s*$/) {
1966 } elsif ($possible =~ /\s/) {
1967 $possible =~ s/\s*$Type\s*//g;
1968 for my $modifier (split(' ', $possible)) {
1969 if ($modifier !~ $notPermitted) {
1970 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1971 push(@modifierListFile, $modifier);
1976 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1977 push(@typeListFile, $possible);
1981 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1990 $type =~ tr/[a-z]/[A-Z]/;
1992 return defined $use_type{$type} if (scalar keys %use_type > 0);
1994 return !defined $ignore_type{$type};
1998 my ($level, $type, $msg) = @_;
2000 if (!show_type($type) ||
2001 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2006 if ($level eq 'ERROR') {
2008 } elsif ($level eq 'WARNING') {
2014 $output .= $prefix . $level . ':';
2016 $output .= BLUE if ($color);
2017 $output .= "$type:";
2019 $output .= RESET if ($color);
2020 $output .= ' ' . $msg . "\n";
2023 my @lines = split("\n", $output, -1);
2024 splice(@lines, 1, 1);
2025 $output = join("\n", @lines);
2027 $output = (split('\n', $output))[0] . "\n" if ($terse);
2029 push(our @report, $output);
2038 sub fixup_current_range {
2039 my ($lineRef, $offset, $length) = @_;
2041 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2044 my $no = $o + $offset;
2045 my $nl = $l + $length;
2046 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2050 sub fix_inserted_deleted_lines {
2051 my ($linesRef, $insertedRef, $deletedRef) = @_;
2053 my $range_last_linenr = 0;
2054 my $delta_offset = 0;
2059 my $next_insert = 0;
2060 my $next_delete = 0;
2064 my $inserted = @{$insertedRef}[$next_insert++];
2065 my $deleted = @{$deletedRef}[$next_delete++];
2067 foreach my $old_line (@{$linesRef}) {
2069 my $line = $old_line; #don't modify the array
2070 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2072 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2073 $range_last_linenr = $new_linenr;
2074 fixup_current_range(\$line, $delta_offset, 0);
2077 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2078 $deleted = @{$deletedRef}[$next_delete++];
2080 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2083 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2084 push(@lines, ${$inserted}{'LINE'});
2085 $inserted = @{$insertedRef}[$next_insert++];
2087 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2091 push(@lines, $line);
2101 sub fix_insert_line {
2102 my ($linenr, $line) = @_;
2108 push(@fixed_inserted, $inserted);
2111 sub fix_delete_line {
2112 my ($linenr, $line) = @_;
2119 push(@fixed_deleted, $deleted);
2123 my ($type, $msg) = @_;
2125 if (report("ERROR", $type, $msg)) {
2133 my ($type, $msg) = @_;
2135 if (report("WARNING", $type, $msg)) {
2143 my ($type, $msg) = @_;
2145 if ($check && report("CHECK", $type, $msg)) {
2153 sub check_absolute_file {
2154 my ($absolute, $herecurr) = @_;
2155 my $file = $absolute;
2157 ##print "absolute<$absolute>\n";
2159 # See if any suffix of this path is a path within the tree.
2160 while ($file =~ s@^[^/]*/@@) {
2161 if (-f "$root/$file") {
2162 ##print "file<$file>\n";
2170 # It is, so see if the prefix is acceptable.
2171 my $prefix = $absolute;
2172 substr($prefix, -length($file)) = '';
2174 ##print "prefix<$prefix>\n";
2175 if ($prefix ne ".../") {
2176 WARN("USE_RELATIVE_PATH",
2177 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2184 $string =~ s/^\s+|\s+$//g;
2192 $string =~ s/^\s+//;
2200 $string =~ s/\s+$//;
2205 sub string_find_replace {
2206 my ($string, $find, $replace) = @_;
2208 $string =~ s/$find/$replace/g;
2216 my $source_indent = 8;
2217 my $max_spaces_before_tab = $source_indent - 1;
2218 my $spaces_to_tab = " " x $source_indent;
2220 #convert leading spaces to tabs
2221 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2222 #Remove spaces before a tab
2223 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2228 sub pos_last_openparen {
2233 my $opens = $line =~ tr/\(/\(/;
2234 my $closes = $line =~ tr/\)/\)/;
2236 my $last_openparen = 0;
2238 if (($opens == 0) || ($closes >= $opens)) {
2242 my $len = length($line);
2244 for ($pos = 0; $pos < $len; $pos++) {
2245 my $string = substr($line, $pos);
2246 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2247 $pos += length($1) - 1;
2248 } elsif (substr($line, $pos, 1) eq '(') {
2249 $last_openparen = $pos;
2250 } elsif (index($string, '(') == -1) {
2255 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2259 my $filename = shift;
2265 my $stashrawline="";
2275 my $authorsignoff = 0;
2277 my $is_binding_patch = -1;
2278 my $in_header_lines = $file ? 0 : 1;
2279 my $in_commit_log = 0; #Scanning lines before patch
2280 my $has_commit_log = 0; #Encountered lines before patch
2281 my $commit_log_lines = 0; #Number of commit log lines
2282 my $commit_log_possible_stack_dump = 0;
2283 my $commit_log_long_line = 0;
2284 my $commit_log_has_diff = 0;
2285 my $reported_maintainer_file = 0;
2286 my $non_utf8_charset = 0;
2288 my $last_blank_line = 0;
2289 my $last_coalesced_string_linenr = -1;
2297 # Trace the real file/line as we go.
2302 my $context_function; #undef'd unless there's a known function
2304 my $comment_edge = 0;
2308 my $prev_values = 'E';
2311 my %suppress_ifbraces;
2312 my %suppress_whiletrailers;
2313 my %suppress_export;
2314 my $suppress_statement = 0;
2316 my %signatures = ();
2318 # Pre-scan the patch sanitizing the lines.
2319 # Pre-scan the patch looking for any __setup documentation.
2321 my @setup_docs = ();
2324 my $camelcase_file_seeded = 0;
2326 my $checklicenseline = 1;
2328 sanitise_line_reset();
2330 foreach my $rawline (@rawlines) {
2334 push(@fixed, $rawline) if ($fix);
2336 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2338 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2343 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2352 # Guestimate if this is a continuing comment. Run
2353 # the context looking for a comment "edge". If this
2354 # edge is a close comment then we must be in a comment
2358 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2359 next if (defined $rawlines[$ln - 1] &&
2360 $rawlines[$ln - 1] =~ /^-/);
2362 #print "RAW<$rawlines[$ln - 1]>\n";
2363 last if (!defined $rawlines[$ln - 1]);
2364 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2365 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2370 if (defined $edge && $edge eq '*/') {
2374 # Guestimate if this is a continuing comment. If this
2375 # is the start of a diff block and this line starts
2376 # ' *' then it is very likely a comment.
2377 if (!defined $edge &&
2378 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2383 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2384 sanitise_line_reset($in_comment);
2386 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2387 # Standardise the strings and chars within the input to
2388 # simplify matching -- only bother with positive lines.
2389 $line = sanitise_line($rawline);
2391 push(@lines, $line);
2394 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2399 #print "==>$rawline\n";
2400 #print "-->$line\n";
2402 if ($setup_docs && $line =~ /^\+/) {
2403 push(@setup_docs, $line);
2412 foreach my $line (@lines) {
2415 my $sline = $line; #copy of $line
2416 $sline =~ s/$;/ /g; #with comments as spaces
2418 my $rawline = $rawlines[$linenr - 1];
2420 # check if it's a mode change, rename or start of a patch
2421 if (!$in_commit_log &&
2422 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2423 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2424 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2428 #extract the line range in the file after the patch is applied
2429 if (!$in_commit_log &&
2430 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2433 $first_line = $linenr + 1;
2443 %suppress_ifbraces = ();
2444 %suppress_whiletrailers = ();
2445 %suppress_export = ();
2446 $suppress_statement = 0;
2447 if ($context =~ /\b(\w+)\s*\(/) {
2448 $context_function = $1;
2450 undef $context_function;
2454 # track the line number as we move through the hunk, note that
2455 # new versions of GNU diff omit the leading space on completely
2456 # blank context lines so we need to count that too.
2457 } elsif ($line =~ /^( |\+|$)/) {
2459 $realcnt-- if ($realcnt != 0);
2461 # Measure the line length and indent.
2462 ($length, $indent) = line_stats($rawline);
2464 # Track the previous line.
2465 ($prevline, $stashline) = ($stashline, $line);
2466 ($previndent, $stashindent) = ($stashindent, $indent);
2467 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2469 #warn "line<$line>\n";
2471 } elsif ($realcnt == 1) {
2475 my $hunk_line = ($realcnt != 0);
2477 $here = "#$linenr: " if (!$file);
2478 $here = "#$realline: " if ($file);
2481 # extract the filename as it passes
2482 if ($line =~ /^diff --git.*?(\S+)$/) {
2484 $realfile =~ s@^([^/]*)/@@ if (!$file);
2487 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2489 $realfile =~ s@^([^/]*)/@@ if (!$file);
2493 if (!$file && $tree && $p1_prefix ne '' &&
2494 -e "$root/$p1_prefix") {
2495 WARN("PATCH_PREFIX",
2496 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2499 if ($realfile =~ m@^include/asm/@) {
2500 ERROR("MODIFIED_INCLUDE_ASM",
2501 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2506 #make up the handle for any error we report on this line
2508 $prefix = "$realfile:$realline: "
2511 $prefix = "$filename:$realline: ";
2513 $prefix = "$filename:$linenr: ";
2518 if (is_maintained_obsolete($realfile)) {
2520 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2522 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2525 $check = $check_orig;
2527 $checklicenseline = 1;
2529 if ($realfile !~ /^MAINTAINERS/) {
2530 my $last_binding_patch = $is_binding_patch;
2532 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2534 if (($last_binding_patch != -1) &&
2535 ($last_binding_patch ^ $is_binding_patch)) {
2536 WARN("DT_SPLIT_BINDING_PATCH",
2537 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2544 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2546 my $hereline = "$here\n$rawline\n";
2547 my $herecurr = "$here\n$rawline\n";
2548 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2550 $cnt_lines++ if ($realcnt != 0);
2552 # Verify the existence of a commit log if appropriate
2553 # 2 is used because a $signature is counted in $commit_log_lines
2554 if ($in_commit_log) {
2555 if ($line !~ /^\s*$/) {
2556 $commit_log_lines++; #could be a $signature
2558 } elsif ($has_commit_log && $commit_log_lines < 2) {
2559 WARN("COMMIT_MESSAGE",
2560 "Missing commit description - Add an appropriate one\n");
2561 $commit_log_lines = 2; #warn only once
2564 # Check if the commit log has what seems like a diff which can confuse patch
2565 if ($in_commit_log && !$commit_log_has_diff &&
2566 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2567 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2568 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2569 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2570 ERROR("DIFF_IN_COMMIT_MSG",
2571 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2572 $commit_log_has_diff = 1;
2575 # Check for incorrect file permissions
2576 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2577 my $permhere = $here . "FILE: $realfile\n";
2578 if ($realfile !~ m@scripts/@ &&
2579 $realfile !~ /\.(py|pl|awk|sh)$/) {
2580 ERROR("EXECUTE_PERMISSIONS",
2581 "do not set execute permissions for source files\n" . $permhere);
2585 # Check the patch for a From:
2586 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2588 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2592 # Check the patch for a signoff:
2593 if ($line =~ /^\s*signed-off-by:/i) {
2596 if ($author ne '') {
2599 if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2605 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2606 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2607 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2608 $reported_maintainer_file = 1;
2611 # Check signature styles
2612 if (!$in_header_lines &&
2613 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2614 my $space_before = $1;
2616 my $space_after = $3;
2618 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2620 if ($sign_off !~ /$signature_tags/) {
2621 WARN("BAD_SIGN_OFF",
2622 "Non-standard signature: $sign_off\n" . $herecurr);
2624 if (defined $space_before && $space_before ne "") {
2625 if (WARN("BAD_SIGN_OFF",
2626 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2628 $fixed[$fixlinenr] =
2629 "$ucfirst_sign_off $email";
2632 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2633 if (WARN("BAD_SIGN_OFF",
2634 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2636 $fixed[$fixlinenr] =
2637 "$ucfirst_sign_off $email";
2641 if (!defined $space_after || $space_after ne " ") {
2642 if (WARN("BAD_SIGN_OFF",
2643 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2645 $fixed[$fixlinenr] =
2646 "$ucfirst_sign_off $email";
2650 my ($email_name, $email_address, $comment) = parse_email($email);
2651 my $suggested_email = format_email(($email_name, $email_address));
2652 if ($suggested_email eq "") {
2653 ERROR("BAD_SIGN_OFF",
2654 "Unrecognized email address: '$email'\n" . $herecurr);
2656 my $dequoted = $suggested_email;
2657 $dequoted =~ s/^"//;
2658 $dequoted =~ s/" </ </;
2659 # Don't force email to have quotes
2660 # Allow just an angle bracketed address
2661 if ("$dequoted$comment" ne $email &&
2662 "<$email_address>$comment" ne $email &&
2663 "$suggested_email$comment" ne $email) {
2664 WARN("BAD_SIGN_OFF",
2665 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2669 # Check for duplicate signatures
2670 my $sig_nospace = $line;
2671 $sig_nospace =~ s/\s//g;
2672 $sig_nospace = lc($sig_nospace);
2673 if (defined $signatures{$sig_nospace}) {
2674 WARN("BAD_SIGN_OFF",
2675 "Duplicate signature\n" . $herecurr);
2677 $signatures{$sig_nospace} = 1;
2681 # Check email subject for common tools that don't need to be mentioned
2682 if ($in_header_lines &&
2683 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2684 WARN("EMAIL_SUBJECT",
2685 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2688 # Check for unwanted Gerrit info
2689 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2690 ERROR("GERRIT_CHANGE_ID",
2691 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2694 # Check if the commit log is in a possible stack dump
2695 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2696 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2697 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2699 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2700 # stack dump address
2701 $commit_log_possible_stack_dump = 1;
2704 # Check for line lengths > 75 in commit log, warn once
2705 if ($in_commit_log && !$commit_log_long_line &&
2706 length($line) > 75 &&
2707 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2708 # file delta changes
2709 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2711 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2712 # A Fixes: or Link: line
2713 $commit_log_possible_stack_dump)) {
2714 WARN("COMMIT_LOG_LONG_LINE",
2715 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2716 $commit_log_long_line = 1;
2719 # Reset possible stack dump if a blank line is found
2720 if ($in_commit_log && $commit_log_possible_stack_dump &&
2722 $commit_log_possible_stack_dump = 0;
2725 # Check for git id commit length and improperly formed commit descriptions
2726 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2727 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2728 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2729 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2730 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2731 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2732 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2733 my $init_char = "c";
2734 my $orig_commit = "";
2741 my $id = '0123456789ab';
2742 my $orig_desc = "commit description";
2743 my $description = "";
2745 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2747 $orig_commit = lc($2);
2748 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2749 $orig_commit = lc($1);
2752 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2753 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2754 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2755 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2756 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2759 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2760 defined $rawlines[$linenr] &&
2761 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2764 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2765 defined $rawlines[$linenr] &&
2766 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2767 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2769 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2770 $orig_desc .= " " . $1;
2774 ($id, $description) = git_commit_info($orig_commit,
2778 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2779 ERROR("GIT_COMMIT_ID",
2780 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2784 # Check for added, moved or deleted files
2785 if (!$reported_maintainer_file && !$in_commit_log &&
2786 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2787 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2788 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2789 (defined($1) || defined($2))))) {
2791 $reported_maintainer_file = 1;
2792 WARN("FILE_PATH_CHANGES",
2793 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2796 # Check for wrappage within a valid hunk of the file
2797 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2798 ERROR("CORRUPTED_PATCH",
2799 "patch seems to be corrupt (line wrapped?)\n" .
2800 $herecurr) if (!$emitted_corrupt++);
2803 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2804 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2805 $rawline !~ m/^$UTF8*$/) {
2806 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2808 my $blank = copy_spacing($rawline);
2809 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2810 my $hereptr = "$hereline$ptr\n";
2813 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2816 # Check if it's the start of a commit log
2817 # (not a header line and we haven't seen the patch filename)
2818 if ($in_header_lines && $realfile =~ /^$/ &&
2819 !($rawline =~ /^\s+(?:\S|$)/ ||
2820 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2821 $in_header_lines = 0;
2823 $has_commit_log = 1;
2826 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2827 # declined it, i.e defined some charset where it is missing.
2828 if ($in_header_lines &&
2829 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2831 $non_utf8_charset = 1;
2834 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2835 $rawline =~ /$NON_ASCII_UTF8/) {
2836 WARN("UTF8_BEFORE_PATCH",
2837 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2840 # Check for absolute kernel paths in commit message
2841 if ($tree && $in_commit_log) {
2842 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2845 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2846 check_absolute_file($1, $herecurr)) {
2849 check_absolute_file($file, $herecurr);
2854 # Check for various typo / spelling mistakes
2855 if (defined($misspellings) &&
2856 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2857 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2859 my $typo_fix = $spelling_fix{lc($typo)};
2860 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2861 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2862 my $msg_level = \&WARN;
2863 $msg_level = \&CHK if ($file);
2864 if (&{$msg_level}("TYPO_SPELLING",
2865 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2867 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2872 # ignore non-hunk lines and lines being removed
2873 next if (!$hunk_line || $line =~ /^-/);
2875 #trailing whitespace
2876 if ($line =~ /^\+.*\015/) {
2877 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2878 if (ERROR("DOS_LINE_ENDINGS",
2879 "DOS line endings\n" . $herevet) &&
2881 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2883 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2884 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2885 if (ERROR("TRAILING_WHITESPACE",
2886 "trailing whitespace\n" . $herevet) &&
2888 $fixed[$fixlinenr] =~ s/\s+$//;
2894 # Check for FSF mailing addresses.
2895 if ($rawline =~ /\bwrite to the Free/i ||
2896 $rawline =~ /\b675\s+Mass\s+Ave/i ||
2897 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2898 $rawline =~ /\b51\s+Franklin\s+St/i) {
2899 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2900 my $msg_level = \&ERROR;
2901 $msg_level = \&CHK if ($file);
2902 &{$msg_level}("FSF_MAILING_ADDRESS",
2903 "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)
2906 # check for Kconfig help text having a real description
2907 # Only applies when adding the entry originally, after that we do not have
2908 # sufficient context to determine whether it is indeed long enough.
2909 if ($realfile =~ /Kconfig/ &&
2910 # 'choice' is usually the last thing on the line (though
2911 # Kconfig supports named choices), so use a word boundary
2912 # (\b) rather than a whitespace character (\s)
2913 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2916 my $ln = $linenr + 1;
2920 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2921 $f = $lines[$ln - 1];
2922 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2923 $is_end = $lines[$ln - 1] =~ /^\+/;
2925 next if ($f =~ /^-/);
2926 last if (!$file && $f =~ /^\@\@/);
2928 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2930 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
2931 if ($lines[$ln - 1] =~ "---help---") {
2932 WARN("CONFIG_DESCRIPTION",
2933 "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
2941 next if ($f =~ /^$/);
2943 # This only checks context lines in the patch
2944 # and so hopefully shouldn't trigger false
2945 # positives, even though some of these are
2946 # common words in help texts
2947 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
2948 if|endif|menu|endmenu|source)\b/x) {
2954 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2955 WARN("CONFIG_DESCRIPTION",
2956 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2958 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2961 # check for MAINTAINERS entries that don't have the right form
2962 if ($realfile =~ /^MAINTAINERS$/ &&
2963 $rawline =~ /^\+[A-Z]:/ &&
2964 $rawline !~ /^\+[A-Z]:\t\S/) {
2965 if (WARN("MAINTAINERS_STYLE",
2966 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2968 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2972 # discourage the use of boolean for type definition attributes of Kconfig options
2973 if ($realfile =~ /Kconfig/ &&
2974 $line =~ /^\+\s*\bboolean\b/) {
2975 WARN("CONFIG_TYPE_BOOLEAN",
2976 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2979 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2980 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2983 'EXTRA_AFLAGS' => 'asflags-y',
2984 'EXTRA_CFLAGS' => 'ccflags-y',
2985 'EXTRA_CPPFLAGS' => 'cppflags-y',
2986 'EXTRA_LDFLAGS' => 'ldflags-y',
2989 WARN("DEPRECATED_VARIABLE",
2990 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2993 # check for DT compatible documentation
2994 if (defined $root &&
2995 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2996 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2998 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3000 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3001 my $vp_file = $dt_path . "vendor-prefixes.txt";
3003 foreach my $compat (@compats) {
3004 my $compat2 = $compat;
3005 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3006 my $compat3 = $compat;
3007 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3008 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3010 WARN("UNDOCUMENTED_DT_STRING",
3011 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3014 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3016 `grep -Eq "^$vendor\\b" $vp_file`;
3018 WARN("UNDOCUMENTED_DT_STRING",
3019 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3024 # check for using SPDX license tag at beginning of files
3025 if ($realline == $checklicenseline) {
3026 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3027 $checklicenseline = 2;
3028 } elsif ($rawline =~ /^\+/) {
3030 if ($realfile =~ /\.(h|s|S)$/) {
3032 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3034 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3036 } elsif ($realfile =~ /\.rst$/) {
3040 if ($comment !~ /^$/ &&
3041 $rawline !~ /^\+\Q$comment\E SPDX-License-Identifier: /) {
3042 WARN("SPDX_LICENSE_TAG",
3043 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3044 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3045 my $spdx_license = $1;
3046 if (!is_SPDX_License_valid($spdx_license)) {
3047 WARN("SPDX_LICENSE_TAG",
3048 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3054 # check we are in a valid source file if not then ignore this hunk
3055 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3057 # line length limit (with some exclusions)
3059 # There are a few types of lines that may extend beyond $max_line_length:
3060 # logging functions like pr_info that end in a string
3061 # lines with a single string
3062 # #defines that are a single string
3063 # lines with an RFC3986 like URL
3065 # There are 3 different line length message types:
3066 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3067 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3068 # LONG_LINE all other lines longer than $max_line_length
3070 # if LONG_LINE is ignored, the other 2 types are also ignored
3073 if ($line =~ /^\+/ && $length > $max_line_length) {
3074 my $msg_type = "LONG_LINE";
3076 # Check the allowed long line types first
3078 # logging functions that end in a string that starts
3079 # before $max_line_length
3080 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3081 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3084 # lines with only strings (w/ possible termination)
3085 # #defines with only strings
3086 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3087 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3090 # More special cases
3091 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3092 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3095 # URL ($rawline is used in case the URL is in a comment)
3096 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3099 # Otherwise set the alternate message types
3101 # a comment starts before $max_line_length
3102 } elsif ($line =~ /($;[\s$;]*)$/ &&
3103 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3104 $msg_type = "LONG_LINE_COMMENT"
3106 # a quoted string starts before $max_line_length
3107 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3108 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3109 $msg_type = "LONG_LINE_STRING"
3112 if ($msg_type ne "" &&
3113 (show_type("LONG_LINE") || show_type($msg_type))) {
3115 "line over $max_line_length characters\n" . $herecurr);
3119 # check for adding lines without a newline.
3120 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3121 WARN("MISSING_EOF_NEWLINE",
3122 "adding a line without newline at end of file\n" . $herecurr);
3125 # check we are in a valid source file C or perl if not then ignore this hunk
3126 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3128 # at the beginning of a line any tabs must come first and anything
3129 # more than 8 must use tabs.
3130 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3131 $rawline =~ /^\+\s* \s*/) {
3132 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3134 if (ERROR("CODE_INDENT",
3135 "code indent should use tabs where possible\n" . $herevet) &&
3137 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3141 # check for space before tabs.
3142 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3143 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3144 if (WARN("SPACE_BEFORE_TAB",
3145 "please, no space before tabs\n" . $herevet) &&
3147 while ($fixed[$fixlinenr] =~
3148 s/(^\+.*) {8,8}\t/$1\t\t/) {}
3149 while ($fixed[$fixlinenr] =~
3150 s/(^\+.*) +\t/$1\t/) {}
3154 # check for assignments on the start of a line
3155 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3156 CHK("ASSIGNMENT_CONTINUATIONS",
3157 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3160 # check for && or || at the start of a line
3161 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3162 CHK("LOGICAL_CONTINUATIONS",
3163 "Logical continuations should be on the previous line\n" . $hereprev);
3166 # check indentation starts on a tab stop
3167 if ($perl_version_ok &&
3168 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3169 my $indent = length($1);
3172 "Statements should start on a tabstop\n" . $herecurr) &&
3174 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3179 # check multi-line statement indentation matches previous line
3180 if ($perl_version_ok &&
3181 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3182 $prevline =~ /^\+(\t*)(.*)$/;
3186 my $pos = pos_last_openparen($rest);
3188 $line =~ /^(\+| )([ \t]*)/;
3191 my $goodtabindent = $oldindent .
3194 my $goodspaceindent = $oldindent . " " x $pos;
3196 if ($newindent ne $goodtabindent &&
3197 $newindent ne $goodspaceindent) {
3199 if (CHK("PARENTHESIS_ALIGNMENT",
3200 "Alignment should match open parenthesis\n" . $hereprev) &&
3201 $fix && $line =~ /^\+/) {
3202 $fixed[$fixlinenr] =~
3203 s/^\+[ \t]*/\+$goodtabindent/;
3209 # check for space after cast like "(int) foo" or "(struct foo) bar"
3210 # avoid checking a few false positives:
3211 # "sizeof(<type>)" or "__alignof__(<type>)"
3212 # function pointer declarations like "(*foo)(int) = bar;"
3213 # structure definitions like "(struct foo) { 0 };"
3214 # multiline macros that define functions
3215 # known attributes or the __attribute__ keyword
3216 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3217 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3219 "No space is necessary after a cast\n" . $herecurr) &&
3221 $fixed[$fixlinenr] =~
3222 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3226 # Block comment styles
3227 # Networking with an initial /*
3228 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3229 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3230 $rawline =~ /^\+[ \t]*\*/ &&
3232 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3233 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3236 # Block comments use * on subsequent lines
3237 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3238 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3239 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3240 $rawline =~ /^\+/ && #line is new
3241 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3242 WARN("BLOCK_COMMENT_STYLE",
3243 "Block comments use * on subsequent lines\n" . $hereprev);
3246 # Block comments use */ on trailing lines
3247 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3248 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3249 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3250 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3251 WARN("BLOCK_COMMENT_STYLE",
3252 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3255 # Block comment * alignment
3256 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3257 $line =~ /^\+[ \t]*$;/ && #leading comment
3258 $rawline =~ /^\+[ \t]*\*/ && #leading *
3259 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3260 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3261 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3263 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3265 $oldindent = expand_tabs($1);
3267 $prevrawline =~ m@^\+(.*/?)\*@;
3268 $oldindent = expand_tabs($1);
3270 $rawline =~ m@^\+([ \t]*)\*@;
3272 $newindent = expand_tabs($newindent);
3273 if (length($oldindent) ne length($newindent)) {
3274 WARN("BLOCK_COMMENT_STYLE",
3275 "Block comments should align the * on each line\n" . $hereprev);
3279 # check for missing blank lines after struct/union declarations
3280 # with exceptions for various attributes and macros
3281 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3283 !($line =~ /^\+\s*$/ ||
3284 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3285 $line =~ /^\+\s*MODULE_/i ||
3286 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3287 $line =~ /^\+[a-z_]*init/ ||
3288 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3289 $line =~ /^\+\s*DECLARE/ ||
3290 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3291 $line =~ /^\+\s*__setup/)) {
3292 if (CHK("LINE_SPACING",
3293 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3295 fix_insert_line($fixlinenr, "\+");
3299 # check for multiple consecutive blank lines
3300 if ($prevline =~ /^[\+ ]\s*$/ &&
3301 $line =~ /^\+\s*$/ &&
3302 $last_blank_line != ($linenr - 1)) {
3303 if (CHK("LINE_SPACING",
3304 "Please don't use multiple blank lines\n" . $hereprev) &&
3306 fix_delete_line($fixlinenr, $rawline);
3309 $last_blank_line = $linenr;
3312 # check for missing blank lines after declarations
3313 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3314 # actual declarations
3315 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3316 # function pointer declarations
3317 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3318 # foo bar; where foo is some local typedef or #define
3319 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3320 # known declaration macros
3321 $prevline =~ /^\+\s+$declaration_macros/) &&
3322 # for "else if" which can look like "$Ident $Ident"
3323 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3324 # other possible extensions of declaration lines
3325 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3326 # not starting a section or a macro "\" extended line
3327 $prevline =~ /(?:\{\s*|\\)$/) &&
3328 # looks like a declaration
3329 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3330 # function pointer declarations
3331 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3332 # foo bar; where foo is some local typedef or #define
3333 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3334 # known declaration macros
3335 $sline =~ /^\+\s+$declaration_macros/ ||
3336 # start of struct or union or enum
3337 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3338 # start or end of block or continuation of declaration
3339 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3340 # bitfield continuation
3341 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3342 # other possible extensions of declaration lines
3343 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3344 # indentation of previous and current line are the same
3345 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3346 if (WARN("LINE_SPACING",
3347 "Missing a blank line after declarations\n" . $hereprev) &&
3349 fix_insert_line($fixlinenr, "\+");
3353 # check for spaces at the beginning of a line.
3355 # 1) within comments
3356 # 2) indented preprocessor commands
3358 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3359 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3360 if (WARN("LEADING_SPACE",
3361 "please, no spaces at the start of a line\n" . $herevet) &&
3363 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3367 # check we are in a valid C source file if not then ignore this hunk
3368 next if ($realfile !~ /\.(h|c)$/);
3370 # check for unusual line ending [ or (
3371 if ($line =~ /^\+.*([\[\(])\s*$/) {
3372 CHK("OPEN_ENDED_LINE",
3373 "Lines should not end with a '$1'\n" . $herecurr);
3376 # check if this appears to be the start function declaration, save the name
3377 if ($sline =~ /^\+\{\s*$/ &&
3378 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3379 $context_function = $1;
3382 # check if this appears to be the end of function declaration
3383 if ($sline =~ /^\+\}\s*$/) {
3384 undef $context_function;
3387 # check indentation of any line with a bare else
3388 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3389 # if the previous line is a break or return and is indented 1 tab more...
3390 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3391 my $tabs = length($1) + 1;
3392 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3393 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3394 defined $lines[$linenr] &&
3395 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3396 WARN("UNNECESSARY_ELSE",
3397 "else is not generally useful after a break or return\n" . $hereprev);
3401 # check indentation of a line with a break;
3402 # if the previous line is a goto or return and is indented the same # of tabs
3403 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3405 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3406 WARN("UNNECESSARY_BREAK",
3407 "break is not useful after a goto or return\n" . $hereprev);
3411 # check for RCS/CVS revision markers
3412 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3414 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3417 # check for old HOTPLUG __dev<foo> section markings
3418 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3419 WARN("HOTPLUG_SECTION",
3420 "Using $1 is unnecessary\n" . $herecurr);
3423 # Check for potential 'bare' types
3424 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3426 #print "LINE<$line>\n";
3427 if ($linenr > $suppress_statement &&
3428 $realcnt && $sline =~ /.\s*\S/) {
3429 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3430 ctx_statement_block($linenr, $realcnt, 0);
3431 $stat =~ s/\n./\n /g;
3432 $cond =~ s/\n./\n /g;
3434 #print "linenr<$linenr> <$stat>\n";
3435 # If this statement has no statement boundaries within
3436 # it there is no point in retrying a statement scan
3437 # until we hit end of it.
3438 my $frag = $stat; $frag =~ s/;+\s*$//;
3439 if ($frag !~ /(?:{|;)/) {
3440 #print "skip<$line_nr_next>\n";
3441 $suppress_statement = $line_nr_next;
3444 # Find the real next line.
3445 $realline_next = $line_nr_next;
3446 if (defined $realline_next &&
3447 (!defined $lines[$realline_next - 1] ||
3448 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3455 # Ignore goto labels.
3456 if ($s =~ /$Ident:\*$/s) {
3458 # Ignore functions being called
3459 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3461 } elsif ($s =~ /^.\s*else\b/s) {
3463 # declarations always start with types
3464 } 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) {
3467 possible($type, "A:" . $s);
3469 # definitions in global scope can only start with types
3470 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3471 possible($1, "B:" . $s);
3474 # any (foo ... *) is a pointer cast, and foo is a type
3475 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3476 possible($1, "C:" . $s);
3479 # Check for any sort of function declaration.
3480 # int foo(something bar, other baz);
3481 # void (*store_gdt)(x86_descr_ptr *);
3482 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3483 my ($name_len) = length($1);
3486 substr($ctx, 0, $name_len + 1, '');
3487 $ctx =~ s/\)[^\)]*$//;
3489 for my $arg (split(/\s*,\s*/, $ctx)) {
3490 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3492 possible($1, "D:" . $s);
3500 # Checks which may be anchored in the context.
3503 # Check for switch () and associated case and default
3504 # statements should be at the same indent.
3505 if ($line=~/\bswitch\s*\(.*\)/) {
3508 my @ctx = ctx_block_outer($linenr, $realcnt);
3510 for my $ctx (@ctx) {
3511 my ($clen, $cindent) = line_stats($ctx);
3512 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3513 $indent != $cindent) {
3514 $err .= "$sep$ctx\n";
3521 ERROR("SWITCH_CASE_INDENT_LEVEL",
3522 "switch and case should be at the same indent\n$hereline$err");
3526 # if/while/etc brace do not go on next line, unless defining a do while loop,
3527 # or if that brace on the next line is for something else
3528 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3529 my $pre_ctx = "$1$2";
3531 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3533 if ($line =~ /^\+\t{6,}/) {
3534 WARN("DEEP_INDENTATION",
3535 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3538 my $ctx_cnt = $realcnt - $#ctx - 1;
3539 my $ctx = join("\n", @ctx);
3541 my $ctx_ln = $linenr;
3542 my $ctx_skip = $realcnt;
3544 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3545 defined $lines[$ctx_ln - 1] &&
3546 $lines[$ctx_ln - 1] =~ /^-/)) {
3547 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3548 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3552 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3553 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3555 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3557 "that open brace { should be on the previous line\n" .
3558 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3560 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3561 $ctx =~ /\)\s*\;\s*$/ &&
3562 defined $lines[$ctx_ln - 1])
3564 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3565 if ($nindent > $indent) {
3566 WARN("TRAILING_SEMICOLON",
3567 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3568 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3573 # Check relative indent for conditionals and blocks.
3574 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3575 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3576 ctx_statement_block($linenr, $realcnt, 0)
3577 if (!defined $stat);
3578 my ($s, $c) = ($stat, $cond);
3580 substr($s, 0, length($c), '');
3582 # remove inline comments
3586 # Find out how long the conditional actually is.
3587 my @newlines = ($c =~ /\n/gs);
3588 my $cond_lines = 1 + $#newlines;
3590 # Make sure we remove the line prefixes as we have
3591 # none on the first line, and are going to readd them
3594 while ($s =~ /\n\s+\\\n/) {
3595 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3598 # We want to check the first line inside the block
3599 # starting at the end of the conditional, so remove:
3600 # 1) any blank line termination
3601 # 2) any opening brace { on end of the line
3603 my $continuation = 0;
3605 $s =~ s/^.*\bdo\b//;
3607 if ($s =~ s/^\s*\\//) {
3610 if ($s =~ s/^\s*?\n//) {
3615 # Also ignore a loop construct at the end of a
3616 # preprocessor statement.
3617 if (($prevline =~ /^.\s*#\s*define\s/ ||
3618 $prevline =~ /\\\s*$/) && $continuation == 0) {
3624 while ($cond_ptr != $cond_lines) {
3625 $cond_ptr = $cond_lines;
3627 # If we see an #else/#elif then the code
3629 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3634 # 1) blank lines, they should be at 0,
3635 # 2) preprocessor lines, and
3637 if ($continuation ||
3639 $s =~ /^\s*#\s*?/ ||
3640 $s =~ /^\s*$Ident\s*:/) {
3641 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3642 if ($s =~ s/^.*?\n//) {
3648 my (undef, $sindent) = line_stats("+" . $s);
3649 my $stat_real = raw_line($linenr, $cond_lines);
3651 # Check if either of these lines are modified, else
3652 # this is not this patch's fault.
3653 if (!defined($stat_real) ||
3654 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3657 if (defined($stat_real) && $cond_lines > 1) {
3658 $stat_real = "[...]\n$stat_real";
3661 #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";
3663 if ($check && $s ne '' &&
3664 (($sindent % 8) != 0 ||
3665 ($sindent < $indent) ||
3666 ($sindent == $indent &&
3667 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3668 ($sindent > $indent + 8))) {
3669 WARN("SUSPECT_CODE_INDENT",
3670 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3674 # Track the 'values' across context and added lines.
3675 my $opline = $line; $opline =~ s/^./ /;
3676 my ($curr_values, $curr_vars) =
3677 annotate_values($opline . "\n", $prev_values);
3678 $curr_values = $prev_values . $curr_values;
3680 my $outline = $opline; $outline =~ s/\t/ /g;
3681 print "$linenr > .$outline\n";
3682 print "$linenr > $curr_values\n";
3683 print "$linenr > $curr_vars\n";
3685 $prev_values = substr($curr_values, -1);
3687 #ignore lines not being added
3688 next if ($line =~ /^[^\+]/);
3690 # check for dereferences that span multiple lines
3691 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3692 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3693 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3695 $line =~ /^.\s*($Lval)/;
3698 WARN("MULTILINE_DEREFERENCE",
3699 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3702 # check for declarations of signed or unsigned without int
3703 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3706 $var = "" if (!defined $var);
3707 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3711 $pointer = "" if (!defined $pointer);
3713 if (WARN("UNSPECIFIED_INT",
3714 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3716 my $decl = trim($sign) . " int ";
3717 my $comp_pointer = $pointer;
3718 $comp_pointer =~ s/\s//g;
3719 $decl .= $comp_pointer;
3720 $decl = rtrim($decl) if ($var eq "");
3721 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3726 # TEST: allow direct testing of the type matcher.
3728 if ($line =~ /^.\s*$Declare\s*$/) {
3730 "TEST: is type\n" . $herecurr);
3731 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3732 ERROR("TEST_NOT_TYPE",
3733 "TEST: is not type ($1 is)\n". $herecurr);
3737 # TEST: allow direct testing of the attribute matcher.
3739 if ($line =~ /^.\s*$Modifier\s*$/) {
3741 "TEST: is attr\n" . $herecurr);
3742 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3743 ERROR("TEST_NOT_ATTR",
3744 "TEST: is not attr ($1 is)\n". $herecurr);
3749 # check for initialisation to aggregates open brace on the next line
3750 if ($line =~ /^.\s*{/ &&
3751 $prevline =~ /(?:^|[^=])=\s*$/) {
3752 if (ERROR("OPEN_BRACE",
3753 "that open brace { should be on the previous line\n" . $hereprev) &&
3754 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3755 fix_delete_line($fixlinenr - 1, $prevrawline);
3756 fix_delete_line($fixlinenr, $rawline);
3757 my $fixedline = $prevrawline;
3758 $fixedline =~ s/\s*=\s*$/ = {/;
3759 fix_insert_line($fixlinenr, $fixedline);
3761 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3762 fix_insert_line($fixlinenr, $fixedline);
3767 # Checks which are anchored on the added line.
3770 # check for malformed paths in #include statements (uses RAW line)
3771 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3773 if ($path =~ m{//}) {
3774 ERROR("MALFORMED_INCLUDE",
3775 "malformed #include filename\n" . $herecurr);
3777 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3778 ERROR("UAPI_INCLUDE",
3779 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3783 # no C99 // comments
3784 if ($line =~ m{//}) {
3785 if (ERROR("C99_COMMENTS",
3786 "do not use C99 // comments\n" . $herecurr) &&
3788 my $line = $fixed[$fixlinenr];
3789 if ($line =~ /\/\/(.*)$/) {
3790 my $comment = trim($1);
3791 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3795 # Remove C99 comments.
3797 $opline =~ s@//.*@@;
3799 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3800 # the whole statement.
3801 #print "APW <$lines[$realline_next - 1]>\n";
3802 if (defined $realline_next &&
3803 exists $lines[$realline_next - 1] &&
3804 !defined $suppress_export{$realline_next} &&
3805 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3806 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3807 # Handle definitions which produce identifiers with
3810 # EXPORT_SYMBOL(something_foo);
3812 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3813 $name =~ /^${Ident}_$2/) {
3814 #print "FOO C name<$name>\n";
3815 $suppress_export{$realline_next} = 1;
3817 } elsif ($stat !~ /(?:
3819 ^.DEFINE_$Ident\(\Q$name\E\)|
3820 ^.DECLARE_$Ident\(\Q$name\E\)|
3821 ^.LIST_HEAD\(\Q$name\E\)|
3822 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3823 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3825 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3826 $suppress_export{$realline_next} = 2;
3828 $suppress_export{$realline_next} = 1;
3831 if (!defined $suppress_export{$linenr} &&
3832 $prevline =~ /^.\s*$/ &&
3833 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3834 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3835 #print "FOO B <$lines[$linenr - 1]>\n";
3836 $suppress_export{$linenr} = 2;
3838 if (defined $suppress_export{$linenr} &&
3839 $suppress_export{$linenr} == 2) {
3840 WARN("EXPORT_SYMBOL",
3841 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3844 # check for global initialisers.
3845 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3846 if (ERROR("GLOBAL_INITIALISERS",
3847 "do not initialise globals to $1\n" . $herecurr) &&
3849 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3852 # check for static initialisers.
3853 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3854 if (ERROR("INITIALISED_STATIC",
3855 "do not initialise statics to $1\n" .
3858 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3862 # check for misordered declarations of char/short/int/long with signed/unsigned
3863 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3865 WARN("MISORDERED_TYPE",
3866 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3869 # check for unnecessary <signed> int declarations of short/long/long long
3870 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3871 my $type = trim($1);
3872 next if ($type !~ /\bint\b/);
3873 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3874 my $new_type = $type;
3875 $new_type =~ s/\b\s*int\s*\b/ /;
3876 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3877 $new_type =~ s/^const\s+//;
3878 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3879 $new_type = "const $new_type" if ($type =~ /^const\b/);
3880 $new_type =~ s/\s+/ /g;
3881 $new_type = trim($new_type);
3882 if (WARN("UNNECESSARY_INT",
3883 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3885 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3889 # check for static const char * arrays.
3890 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3891 WARN("STATIC_CONST_CHAR_ARRAY",
3892 "static const char * array should probably be static const char * const\n" .
3896 # check for initialized const char arrays that should be static const
3897 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
3898 if (WARN("STATIC_CONST_CHAR_ARRAY",
3899 "const array should probably be static const\n" . $herecurr) &&
3901 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
3905 # check for static char foo[] = "bar" declarations.
3906 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3907 WARN("STATIC_CONST_CHAR_ARRAY",
3908 "static char array declaration should probably be static const char\n" .
3912 # check for const <foo> const where <foo> is not a pointer or array type
3913 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3915 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3917 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3918 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3920 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3924 # check for non-global char *foo[] = {"bar", ...} declarations.
3925 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3926 WARN("STATIC_CONST_CHAR_ARRAY",
3927 "char * array declaration might be better as static const\n" .
3931 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3932 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3934 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3936 if (WARN("ARRAY_SIZE",
3937 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3939 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3944 # check for function declarations without arguments like "int foo()"
3945 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3946 if (ERROR("FUNCTION_WITHOUT_ARGS",
3947 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3949 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3953 # check for new typedefs, only function parameters and sparse annotations
3955 if ($line =~ /\btypedef\s/ &&
3956 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3957 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3958 $line !~ /\b$typeTypedefs\b/ &&
3959 $line !~ /\b__bitwise\b/) {
3960 WARN("NEW_TYPEDEFS",
3961 "do not add new typedefs\n" . $herecurr);
3964 # * goes on variable not on type
3966 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3968 my ($ident, $from, $to) = ($1, $2, $2);
3970 # Should start with a space.
3971 $to =~ s/^(\S)/ $1/;
3972 # Should not end with a space.
3974 # '*'s should not have spaces between.
3975 while ($to =~ s/\*\s+\*/\*\*/) {
3978 ## print "1: from<$from> to<$to> ident<$ident>\n";
3980 if (ERROR("POINTER_LOCATION",
3981 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3983 my $sub_from = $ident;
3984 my $sub_to = $ident;
3985 $sub_to =~ s/\Q$from\E/$to/;
3986 $fixed[$fixlinenr] =~
3987 s@\Q$sub_from\E@$sub_to@;
3991 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3993 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3995 # Should start with a space.
3996 $to =~ s/^(\S)/ $1/;
3997 # Should not end with a space.
3999 # '*'s should not have spaces between.
4000 while ($to =~ s/\*\s+\*/\*\*/) {
4002 # Modifiers should have spaces.
4003 $to =~ s/(\b$Modifier$)/$1 /;
4005 ## print "2: from<$from> to<$to> ident<$ident>\n";
4006 if ($from ne $to && $ident !~ /^$Modifier$/) {
4007 if (ERROR("POINTER_LOCATION",
4008 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4011 my $sub_from = $match;
4012 my $sub_to = $match;
4013 $sub_to =~ s/\Q$from\E/$to/;
4014 $fixed[$fixlinenr] =~
4015 s@\Q$sub_from\E@$sub_to@;
4020 # avoid BUG() or BUG_ON()
4021 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4022 my $msg_level = \&WARN;
4023 $msg_level = \&CHK if ($file);
4024 &{$msg_level}("AVOID_BUG",
4025 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4028 # avoid LINUX_VERSION_CODE
4029 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4030 WARN("LINUX_VERSION_CODE",
4031 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4034 # check for uses of printk_ratelimit
4035 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4036 WARN("PRINTK_RATELIMITED",
4037 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4040 # printk should use KERN_* levels
4041 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4042 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4043 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4046 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4048 my $level = lc($orig);
4049 $level = "warn" if ($level eq "warning");
4050 my $level2 = $level;
4051 $level2 = "dbg" if ($level eq "debug");
4052 WARN("PREFER_PR_LEVEL",
4053 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4056 if ($line =~ /\bpr_warning\s*\(/) {
4057 if (WARN("PREFER_PR_LEVEL",
4058 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4060 $fixed[$fixlinenr] =~
4061 s/\bpr_warning\b/pr_warn/;
4065 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4067 my $level = lc($orig);
4068 $level = "warn" if ($level eq "warning");
4069 $level = "dbg" if ($level eq "debug");
4070 WARN("PREFER_DEV_LEVEL",
4071 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4074 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4075 # number of false positives, but assembly files are not checked, so at
4076 # least the arch entry code will not trigger this warning.
4077 if ($line =~ /\bENOSYS\b/) {
4079 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4082 # function brace can't be on same line, except for #defines of do while,
4083 # or if closed on same line
4084 if ($perl_version_ok &&
4085 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4086 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4088 if (ERROR("OPEN_BRACE",
4089 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4091 fix_delete_line($fixlinenr, $rawline);
4092 my $fixed_line = $rawline;
4093 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4096 fix_insert_line($fixlinenr, ltrim($line1));
4097 fix_insert_line($fixlinenr, "\+{");
4098 if ($line2 !~ /^\s*$/) {
4099 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4104 # open braces for enum, union and struct go on the same line.
4105 if ($line =~ /^.\s*{/ &&
4106 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4107 if (ERROR("OPEN_BRACE",
4108 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4109 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4110 fix_delete_line($fixlinenr - 1, $prevrawline);
4111 fix_delete_line($fixlinenr, $rawline);
4112 my $fixedline = rtrim($prevrawline) . " {";
4113 fix_insert_line($fixlinenr, $fixedline);
4114 $fixedline = $rawline;
4115 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4116 if ($fixedline !~ /^\+\s*$/) {
4117 fix_insert_line($fixlinenr, $fixedline);
4122 # missing space after union, struct or enum definition
4123 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4125 "missing space after $1 definition\n" . $herecurr) &&
4127 $fixed[$fixlinenr] =~
4128 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4132 # Function pointer declarations
4133 # check spacing between type, funcptr, and args
4134 # canonical declaration is "type (*funcptr)(args...)"
4135 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4137 my $pre_pointer_space = $2;
4138 my $post_pointer_space = $3;
4140 my $post_funcname_space = $5;
4141 my $pre_args_space = $6;
4143 # the $Declare variable will capture all spaces after the type
4144 # so check it for a missing trailing missing space but pointer return types
4145 # don't need a space so don't warn for those.
4146 my $post_declare_space = "";
4147 if ($declare =~ /(\s+)$/) {
4148 $post_declare_space = $1;
4149 $declare = rtrim($declare);
4151 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4153 "missing space after return type\n" . $herecurr);
4154 $post_declare_space = " ";
4157 # unnecessary space "type (*funcptr)(args...)"
4158 # This test is not currently implemented because these declarations are
4160 # int foo(int bar, ...)
4161 # and this is form shouldn't/doesn't generate a checkpatch warning.
4163 # elsif ($declare =~ /\s{2,}$/) {
4165 # "Multiple spaces after return type\n" . $herecurr);
4168 # unnecessary space "type ( *funcptr)(args...)"
4169 if (defined $pre_pointer_space &&
4170 $pre_pointer_space =~ /^\s/) {
4172 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4175 # unnecessary space "type (* funcptr)(args...)"
4176 if (defined $post_pointer_space &&
4177 $post_pointer_space =~ /^\s/) {
4179 "Unnecessary space before function pointer name\n" . $herecurr);
4182 # unnecessary space "type (*funcptr )(args...)"
4183 if (defined $post_funcname_space &&
4184 $post_funcname_space =~ /^\s/) {
4186 "Unnecessary space after function pointer name\n" . $herecurr);
4189 # unnecessary space "type (*funcptr) (args...)"
4190 if (defined $pre_args_space &&
4191 $pre_args_space =~ /^\s/) {
4193 "Unnecessary space before function pointer arguments\n" . $herecurr);
4196 if (show_type("SPACING") && $fix) {
4197 $fixed[$fixlinenr] =~
4198 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4202 # check for spacing round square brackets; allowed:
4203 # 1. with a type on the left -- int [] a;
4204 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4205 # 3. inside a curly brace -- = { [0...10] = 5 }
4206 while ($line =~ /(.*?\s)\[/g) {
4207 my ($where, $prefix) = ($-[1], $1);
4208 if ($prefix !~ /$Type\s+$/ &&
4209 ($where != 0 || $prefix !~ /^.\s+$/) &&
4210 $prefix !~ /[{,:]\s+$/) {
4211 if (ERROR("BRACKET_SPACE",
4212 "space prohibited before open square bracket '['\n" . $herecurr) &&
4214 $fixed[$fixlinenr] =~
4215 s/^(\+.*?)\s+\[/$1\[/;
4220 # check for spaces between functions and their parentheses.
4221 while ($line =~ /($Ident)\s+\(/g) {
4223 my $ctx_before = substr($line, 0, $-[1]);
4224 my $ctx = "$ctx_before$name";
4226 # Ignore those directives where spaces _are_ permitted.
4228 if|for|while|switch|return|case|
4229 volatile|__volatile__|
4230 __attribute__|format|__extension__|
4233 # cpp #define statements have non-optional spaces, ie
4234 # if there is a space between the name and the open
4235 # parenthesis it is simply not a parameter group.
4236 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4238 # cpp #elif statement condition may start with a (
4239 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4241 # If this whole things ends with a type its most
4242 # likely a typedef for a function.
4243 } elsif ($ctx =~ /$Type$/) {
4247 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4249 $fixed[$fixlinenr] =~
4250 s/\b$name\s+\(/$name\(/;
4255 # Check operator spacing.
4256 if (!($line=~/\#\s*include/)) {
4257 my $fixed_line = "";
4261 <<=|>>=|<=|>=|==|!=|
4262 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4263 =>|->|<<|>>|<|>|=|!|~|
4264 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4267 my @elements = split(/($ops|;)/, $opline);
4269 ## print("element count: <" . $#elements . ">\n");
4270 ## foreach my $el (@elements) {
4271 ## print("el: <$el>\n");
4274 my @fix_elements = ();
4277 foreach my $el (@elements) {
4278 push(@fix_elements, substr($rawline, $off, length($el)));
4279 $off += length($el);
4284 my $blank = copy_spacing($opline);
4285 my $last_after = -1;
4287 for (my $n = 0; $n < $#elements; $n += 2) {
4289 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4291 ## print("n: <$n> good: <$good>\n");
4293 $off += length($elements[$n]);
4295 # Pick up the preceding and succeeding characters.
4296 my $ca = substr($opline, 0, $off);
4298 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4299 $cc = substr($opline, $off + length($elements[$n + 1]));
4301 my $cb = "$ca$;$cc";
4304 $a = 'V' if ($elements[$n] ne '');
4305 $a = 'W' if ($elements[$n] =~ /\s$/);
4306 $a = 'C' if ($elements[$n] =~ /$;$/);
4307 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4308 $a = 'O' if ($elements[$n] eq '');
4309 $a = 'E' if ($ca =~ /^\s*$/);
4311 my $op = $elements[$n + 1];
4314 if (defined $elements[$n + 2]) {
4315 $c = 'V' if ($elements[$n + 2] ne '');
4316 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4317 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4318 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4319 $c = 'O' if ($elements[$n + 2] eq '');
4320 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4325 my $ctx = "${a}x${c}";
4327 my $at = "(ctx:$ctx)";
4329 my $ptr = substr($blank, 0, $off) . "^";
4330 my $hereptr = "$hereline$ptr\n";
4332 # Pull out the value of this operator.
4333 my $op_type = substr($curr_values, $off + 1, 1);
4335 # Get the full operator variant.
4336 my $opv = $op . substr($curr_vars, $off, 1);
4338 # Ignore operators passed as parameters.
4339 if ($op_type ne 'V' &&
4340 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4343 # } elsif ($op =~ /^$;+$/) {
4345 # ; should have either the end of line or a space or \ after it
4346 } elsif ($op eq ';') {
4347 if ($ctx !~ /.x[WEBC]/ &&
4348 $cc !~ /^\\/ && $cc !~ /^;/) {
4349 if (ERROR("SPACING",
4350 "space required after that '$op' $at\n" . $hereptr)) {
4351 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4357 } elsif ($op eq '//') {
4359 # : when part of a bitfield
4360 } elsif ($opv eq ':B') {
4361 # skip the bitfield test for now
4365 } elsif ($op eq '->') {
4366 if ($ctx =~ /Wx.|.xW/) {
4367 if (ERROR("SPACING",
4368 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4369 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4370 if (defined $fix_elements[$n + 2]) {
4371 $fix_elements[$n + 2] =~ s/^\s+//;
4377 # , must not have a space before and must have a space on the right.
4378 } elsif ($op eq ',') {
4379 my $rtrim_before = 0;
4380 my $space_after = 0;
4381 if ($ctx =~ /Wx./) {
4382 if (ERROR("SPACING",
4383 "space prohibited before that '$op' $at\n" . $hereptr)) {
4388 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4389 if (ERROR("SPACING",
4390 "space required after that '$op' $at\n" . $hereptr)) {
4396 if ($rtrim_before || $space_after) {
4397 if ($rtrim_before) {
4398 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4400 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4407 # '*' as part of a type definition -- reported already.
4408 } elsif ($opv eq '*_') {
4409 #warn "'*' is part of type\n";
4411 # unary operators should have a space before and
4412 # none after. May be left adjacent to another
4413 # unary operator, or a cast
4414 } elsif ($op eq '!' || $op eq '~' ||
4415 $opv eq '*U' || $opv eq '-U' ||
4416 $opv eq '&U' || $opv eq '&&U') {
4417 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4418 if (ERROR("SPACING",
4419 "space required before that '$op' $at\n" . $hereptr)) {
4420 if ($n != $last_after + 2) {
4421 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4426 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4427 # A unary '*' may be const
4429 } elsif ($ctx =~ /.xW/) {
4430 if (ERROR("SPACING",
4431 "space prohibited after that '$op' $at\n" . $hereptr)) {
4432 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4433 if (defined $fix_elements[$n + 2]) {
4434 $fix_elements[$n + 2] =~ s/^\s+//;
4440 # unary ++ and unary -- are allowed no space on one side.
4441 } elsif ($op eq '++' or $op eq '--') {
4442 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4443 if (ERROR("SPACING",
4444 "space required one side of that '$op' $at\n" . $hereptr)) {
4445 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4449 if ($ctx =~ /Wx[BE]/ ||
4450 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4451 if (ERROR("SPACING",
4452 "space prohibited before that '$op' $at\n" . $hereptr)) {
4453 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4457 if ($ctx =~ /ExW/) {
4458 if (ERROR("SPACING",
4459 "space prohibited after that '$op' $at\n" . $hereptr)) {
4460 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4461 if (defined $fix_elements[$n + 2]) {
4462 $fix_elements[$n + 2] =~ s/^\s+//;
4468 # << and >> may either have or not have spaces both sides
4469 } elsif ($op eq '<<' or $op eq '>>' or
4470 $op eq '&' or $op eq '^' or $op eq '|' or
4471 $op eq '+' or $op eq '-' or
4472 $op eq '*' or $op eq '/' or
4476 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4478 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4479 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4480 $fix_elements[$n + 2] =~ s/^\s+//;
4483 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4485 "space preferred before that '$op' $at\n" . $hereptr)) {
4486 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4490 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4491 if (ERROR("SPACING",
4492 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4493 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4494 if (defined $fix_elements[$n + 2]) {
4495 $fix_elements[$n + 2] =~ s/^\s+//;
4501 # A colon needs no spaces before when it is
4502 # terminating a case value or a label.
4503 } elsif ($opv eq ':C' || $opv eq ':L') {
4504 if ($ctx =~ /Wx./) {
4505 if (ERROR("SPACING",
4506 "space prohibited before that '$op' $at\n" . $hereptr)) {
4507 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4512 # All the others need spaces both sides.
4513 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4516 # Ignore email addresses <foo@bar>
4518 $cc =~ /^\S+\@\S+>/) ||
4520 $ca =~ /<\S+\@\S+$/))
4525 # for asm volatile statements
4526 # ignore a colon with another
4527 # colon immediately before or after
4529 ($ca =~ /:$/ || $cc =~ /^:/)) {
4533 # messages are ERROR, but ?: are CHK
4535 my $msg_level = \&ERROR;
4536 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4538 if (&{$msg_level}("SPACING",
4539 "spaces required around that '$op' $at\n" . $hereptr)) {
4540 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4541 if (defined $fix_elements[$n + 2]) {
4542 $fix_elements[$n + 2] =~ s/^\s+//;
4548 $off += length($elements[$n + 1]);
4550 ## print("n: <$n> GOOD: <$good>\n");
4552 $fixed_line = $fixed_line . $good;
4555 if (($#elements % 2) == 0) {
4556 $fixed_line = $fixed_line . $fix_elements[$#elements];
4559 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4560 $fixed[$fixlinenr] = $fixed_line;
4566 # check for whitespace before a non-naked semicolon
4567 if ($line =~ /^\+.*\S\s+;\s*$/) {
4569 "space prohibited before semicolon\n" . $herecurr) &&
4571 1 while $fixed[$fixlinenr] =~
4572 s/^(\+.*\S)\s+;/$1;/;
4576 # check for multiple assignments
4577 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4578 CHK("MULTIPLE_ASSIGNMENTS",
4579 "multiple assignments should be avoided\n" . $herecurr);
4582 ## # check for multiple declarations, allowing for a function declaration
4584 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4585 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4587 ## # Remove any bracketed sections to ensure we do not
4588 ## # falsly report the parameters of functions.
4590 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4592 ## if ($ln =~ /,/) {
4593 ## WARN("MULTIPLE_DECLARATION",
4594 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4598 #need space before brace following if, while, etc
4599 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4600 $line =~ /\b(?:else|do)\{/) {
4601 if (ERROR("SPACING",
4602 "space required before the open brace '{'\n" . $herecurr) &&
4604 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4608 ## # check for blank lines before declarations
4609 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4610 ## $prevrawline =~ /^.\s*$/) {
4612 ## "No blank lines before declarations\n" . $hereprev);
4616 # closing brace should have a space following it when it has anything
4618 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4619 if (ERROR("SPACING",
4620 "space required after that close brace '}'\n" . $herecurr) &&
4622 $fixed[$fixlinenr] =~
4623 s/}((?!(?:,|;|\)))\S)/} $1/;
4627 # check spacing on square brackets
4628 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4629 if (ERROR("SPACING",
4630 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4632 $fixed[$fixlinenr] =~
4636 if ($line =~ /\s\]/) {
4637 if (ERROR("SPACING",
4638 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4640 $fixed[$fixlinenr] =~
4645 # check spacing on parentheses
4646 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4647 $line !~ /for\s*\(\s+;/) {
4648 if (ERROR("SPACING",
4649 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4651 $fixed[$fixlinenr] =~
4655 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4656 $line !~ /for\s*\(.*;\s+\)/ &&
4657 $line !~ /:\s+\)/) {
4658 if (ERROR("SPACING",
4659 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4661 $fixed[$fixlinenr] =~
4666 # check unnecessary parentheses around addressof/dereference single $Lvals
4667 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4669 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4671 if (CHK("UNNECESSARY_PARENTHESES",
4672 "Unnecessary parentheses around $var\n" . $herecurr) &&
4674 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4678 # check for unnecessary parentheses around function pointer uses
4679 # ie: (foo->bar)(); should be foo->bar();
4680 # but not "if (foo->bar) (" to avoid some false positives
4681 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4683 if (CHK("UNNECESSARY_PARENTHESES",
4684 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4686 my $var2 = deparenthesize($var);
4688 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4692 # check for unnecessary parentheses around comparisons in if uses
4693 # when !drivers/staging or command-line uses --strict
4694 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4695 $perl_version_ok && defined($stat) &&
4696 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4698 my $test = substr($2, 1, -1);
4700 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4702 # avoid parentheses around potential macro args
4703 next if ($match =~ /^\s*\w+\s*$/);
4704 if (!defined($herectx)) {
4705 $herectx = $here . "\n";
4706 my $cnt = statement_rawlines($if_stat);
4707 for (my $n = 0; $n < $cnt; $n++) {
4708 my $rl = raw_line($linenr, $n);
4709 $herectx .= $rl . "\n";
4710 last if $rl =~ /^[ \+].*\{/;
4713 CHK("UNNECESSARY_PARENTHESES",
4714 "Unnecessary parentheses around '$match'\n" . $herectx);
4718 #goto labels aren't indented, allow a single space however
4719 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4720 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4721 if (WARN("INDENTED_LABEL",
4722 "labels should not be indented\n" . $herecurr) &&
4724 $fixed[$fixlinenr] =~
4729 # return is not a function
4730 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4732 if ($perl_version_ok &&
4733 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4735 $value = deparenthesize($value);
4736 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4737 ERROR("RETURN_PARENTHESES",
4738 "return is not a function, parentheses are not required\n" . $herecurr);
4740 } elsif ($spacing !~ /\s+/) {
4742 "space required before the open parenthesis '('\n" . $herecurr);
4746 # unnecessary return in a void function
4747 # at end-of-function, with the previous line a single leading tab, then return;
4748 # and the line before that not a goto label target like "out:"
4749 if ($sline =~ /^[ \+]}\s*$/ &&
4750 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4752 $lines[$linenr - 3] =~ /^[ +]/ &&
4753 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4755 "void function return statements are not generally useful\n" . $hereprev);
4758 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4759 if ($perl_version_ok &&
4760 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4761 my $openparens = $1;
4762 my $count = $openparens =~ tr@\(@\(@;
4764 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4765 my $comp = $4; #Not $1 because of $LvalOrFunc
4766 $msg = " - maybe == should be = ?" if ($comp eq "==");
4767 WARN("UNNECESSARY_PARENTHESES",
4768 "Unnecessary parentheses$msg\n" . $herecurr);
4772 # comparisons with a constant or upper case identifier on the left
4773 # avoid cases like "foo + BAR < baz"
4774 # only fix matches surrounded by parentheses to avoid incorrect
4775 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4776 if ($perl_version_ok &&
4777 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4782 my $newcomp = $comp;
4783 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4784 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4785 WARN("CONSTANT_COMPARISON",
4786 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4790 } elsif ($comp eq "<=") {
4792 } elsif ($comp eq ">") {
4794 } elsif ($comp eq ">=") {
4797 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4801 # Return of what appears to be an errno should normally be negative
4802 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4804 if ($name ne 'EOF' && $name ne 'ERROR') {
4805 WARN("USE_NEGATIVE_ERRNO",
4806 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4810 # Need a space before open parenthesis after if, while etc
4811 if ($line =~ /\b(if|while|for|switch)\(/) {
4812 if (ERROR("SPACING",
4813 "space required before the open parenthesis '('\n" . $herecurr) &&
4815 $fixed[$fixlinenr] =~
4816 s/\b(if|while|for|switch)\(/$1 \(/;
4820 # Check for illegal assignment in if conditional -- and check for trailing
4821 # statements after the conditional.
4822 if ($line =~ /do\s*(?!{)/) {
4823 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4824 ctx_statement_block($linenr, $realcnt, 0)
4825 if (!defined $stat);
4826 my ($stat_next) = ctx_statement_block($line_nr_next,
4827 $remain_next, $off_next);
4828 $stat_next =~ s/\n./\n /g;
4829 ##print "stat<$stat> stat_next<$stat_next>\n";
4831 if ($stat_next =~ /^\s*while\b/) {
4832 # If the statement carries leading newlines,
4833 # then count those as offsets.
4835 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4837 statement_rawlines($whitespace) - 1;
4839 $suppress_whiletrailers{$line_nr_next +
4843 if (!defined $suppress_whiletrailers{$linenr} &&
4844 defined($stat) && defined($cond) &&
4845 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4846 my ($s, $c) = ($stat, $cond);
4848 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4849 ERROR("ASSIGN_IN_IF",
4850 "do not use assignment in if condition\n" . $herecurr);
4853 # Find out what is on the end of the line after the
4855 substr($s, 0, length($c), '');
4857 $s =~ s/$;//g; # Remove any comments
4858 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4859 $c !~ /}\s*while\s*/)
4861 # Find out how long the conditional actually is.
4862 my @newlines = ($c =~ /\n/gs);
4863 my $cond_lines = 1 + $#newlines;
4866 $stat_real = raw_line($linenr, $cond_lines)
4867 . "\n" if ($cond_lines);
4868 if (defined($stat_real) && $cond_lines > 1) {
4869 $stat_real = "[...]\n$stat_real";
4872 ERROR("TRAILING_STATEMENTS",
4873 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4877 # Check for bitwise tests written as boolean
4889 WARN("HEXADECIMAL_BOOLEAN_TEST",
4890 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4893 # if and else should not have general statements after it
4894 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4896 $s =~ s/$;//g; # Remove any comments
4897 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4898 ERROR("TRAILING_STATEMENTS",
4899 "trailing statements should be on next line\n" . $herecurr);
4902 # if should not continue a brace
4903 if ($line =~ /}\s*if\b/) {
4904 ERROR("TRAILING_STATEMENTS",
4905 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4908 # case and default should not have general statements after them
4909 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4911 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4915 ERROR("TRAILING_STATEMENTS",
4916 "trailing statements should be on next line\n" . $herecurr);
4919 # Check for }<nl>else {, these must be at the same
4920 # indent level to be relevant to each other.
4921 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4922 $previndent == $indent) {
4923 if (ERROR("ELSE_AFTER_BRACE",
4924 "else should follow close brace '}'\n" . $hereprev) &&
4925 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4926 fix_delete_line($fixlinenr - 1, $prevrawline);
4927 fix_delete_line($fixlinenr, $rawline);
4928 my $fixedline = $prevrawline;
4929 $fixedline =~ s/}\s*$//;
4930 if ($fixedline !~ /^\+\s*$/) {
4931 fix_insert_line($fixlinenr, $fixedline);
4933 $fixedline = $rawline;
4934 $fixedline =~ s/^(.\s*)else/$1} else/;
4935 fix_insert_line($fixlinenr, $fixedline);
4939 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4940 $previndent == $indent) {
4941 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4943 # Find out what is on the end of the line after the
4945 substr($s, 0, length($c), '');
4948 if ($s =~ /^\s*;/) {
4949 if (ERROR("WHILE_AFTER_BRACE",
4950 "while should follow close brace '}'\n" . $hereprev) &&
4951 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4952 fix_delete_line($fixlinenr - 1, $prevrawline);
4953 fix_delete_line($fixlinenr, $rawline);
4954 my $fixedline = $prevrawline;
4955 my $trailing = $rawline;
4956 $trailing =~ s/^\+//;
4957 $trailing = trim($trailing);
4958 $fixedline =~ s/}\s*$/} $trailing/;
4959 fix_insert_line($fixlinenr, $fixedline);
4964 #Specific variable tests
4965 while ($line =~ m{($Constant|$Lval)}g) {
4969 if ($var !~ /^$Constant$/ &&
4970 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4971 #Ignore Page<foo> variants
4972 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4973 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4974 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4975 #Ignore some three character SI units explicitly, like MiB and KHz
4976 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4977 while ($var =~ m{($Ident)}g) {
4979 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4981 seed_camelcase_includes();
4982 if (!$file && !$camelcase_file_seeded) {
4983 seed_camelcase_file($realfile);
4984 $camelcase_file_seeded = 1;
4987 if (!defined $camelcase{$word}) {
4988 $camelcase{$word} = 1;
4990 "Avoid CamelCase: <$word>\n" . $herecurr);
4996 #no spaces allowed after \ in define
4997 if ($line =~ /\#\s*define.*\\\s+$/) {
4998 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4999 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5001 $fixed[$fixlinenr] =~ s/\s+$//;
5005 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5006 # itself <asm/foo.h> (uses RAW line)
5007 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5009 my $checkfile = "include/linux/$file";
5010 if (-f "$root/$checkfile" &&
5011 $realfile ne $checkfile &&
5012 $1 !~ /$allowed_asm_includes/)
5014 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5015 if ($asminclude > 0) {
5016 if ($realfile =~ m{^arch/}) {
5017 CHK("ARCH_INCLUDE_LINUX",
5018 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5020 WARN("INCLUDE_LINUX",
5021 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5027 # multi-statement macros should be enclosed in a do while loop, grab the
5028 # first statement and ensure its the whole macro if its not enclosed
5029 # in a known good container
5030 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5031 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5034 my ($off, $dstat, $dcond, $rest);
5036 my $has_flow_statement = 0;
5037 my $has_arg_concat = 0;
5038 ($dstat, $dcond, $ln, $cnt, $off) =
5039 ctx_statement_block($linenr, $realcnt, 0);
5041 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5042 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5044 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5045 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5047 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5048 my $define_args = $1;
5049 my $define_stmt = $dstat;
5052 if (defined $define_args && $define_args ne "") {
5053 $define_args = substr($define_args, 1, length($define_args) - 2);
5054 $define_args =~ s/\s*//g;
5055 $define_args =~ s/\\\+?//g;
5056 @def_args = split(",", $define_args);
5060 $dstat =~ s/\\\n.//g;
5061 $dstat =~ s/^\s*//s;
5062 $dstat =~ s/\s*$//s;
5064 # Flatten any parentheses and braces
5065 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5066 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5067 $dstat =~ s/.\[[^\[\]]*\]/1/)
5071 # Flatten any obvious string concatentation.
5072 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5073 $dstat =~ s/$Ident\s*($String)/$1/)
5077 # Make asm volatile uses seem like a generic function
5078 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5080 my $exceptions = qr{
5093 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5096 my $stmt_cnt = statement_rawlines($ctx);
5097 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5100 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5101 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5102 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5103 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5104 $dstat !~ /$exceptions/ &&
5105 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5106 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5107 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5108 $dstat !~ /^for\s*$Constant$/ && # for (...)
5109 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5110 $dstat !~ /^do\s*{/ && # do {...
5111 $dstat !~ /^\(\{/ && # ({...
5112 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5114 if ($dstat =~ /^\s*if\b/) {
5115 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5116 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5117 } elsif ($dstat =~ /;/) {
5118 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5119 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5121 ERROR("COMPLEX_MACRO",
5122 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5127 # Make $define_stmt single line, comment-free, etc
5128 my @stmt_array = split('\n', $define_stmt);
5131 foreach my $l (@stmt_array) {
5136 } elsif ($l =~ /^[\+ ]/) {
5137 $define_stmt .= substr($l, 1);
5140 $define_stmt =~ s/$;//g;
5141 $define_stmt =~ s/\s+/ /g;
5142 $define_stmt = trim($define_stmt);
5144 # check if any macro arguments are reused (ignore '...' and 'type')
5145 foreach my $arg (@def_args) {
5146 next if ($arg =~ /\.\.\./);
5147 next if ($arg =~ /^type$/i);
5148 my $tmp_stmt = $define_stmt;
5149 $tmp_stmt =~ s/\b(typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5150 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5151 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5152 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5154 CHK("MACRO_ARG_REUSE",
5155 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5157 # check if any macro arguments may have other precedence issues
5158 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5159 ((defined($1) && $1 ne ',') ||
5160 (defined($2) && $2 ne ','))) {
5161 CHK("MACRO_ARG_PRECEDENCE",
5162 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5166 # check for macros with flow control, but without ## concatenation
5167 # ## concatenation is commonly a macro that defines a function so ignore those
5168 if ($has_flow_statement && !$has_arg_concat) {
5169 my $cnt = statement_rawlines($ctx);
5170 my $herectx = get_stat_here($linenr, $cnt, $here);
5172 WARN("MACRO_WITH_FLOW_CONTROL",
5173 "Macros with flow control statements should be avoided\n" . "$herectx");
5176 # check for line continuations outside of #defines, preprocessor #, and asm
5179 if ($prevline !~ /^..*\\$/ &&
5180 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5181 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5182 $line =~ /^\+.*\\$/) {
5183 WARN("LINE_CONTINUATIONS",
5184 "Avoid unnecessary line continuations\n" . $herecurr);
5188 # do {} while (0) macro tests:
5189 # single-statement macros do not need to be enclosed in do while (0) loop,
5190 # macro should not end with a semicolon
5191 if ($perl_version_ok &&
5192 $realfile !~ m@/vmlinux.lds.h$@ &&
5193 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5196 my ($off, $dstat, $dcond, $rest);
5198 ($dstat, $dcond, $ln, $cnt, $off) =
5199 ctx_statement_block($linenr, $realcnt, 0);
5202 $dstat =~ s/\\\n.//g;
5205 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5210 my $cnt = statement_rawlines($ctx);
5211 my $herectx = get_stat_here($linenr, $cnt, $here);
5213 if (($stmts =~ tr/;/;/) == 1 &&
5214 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5215 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5216 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5218 if (defined $semis && $semis ne "") {
5219 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5220 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5222 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5224 my $cnt = statement_rawlines($ctx);
5225 my $herectx = get_stat_here($linenr, $cnt, $here);
5227 WARN("TRAILING_SEMICOLON",
5228 "macros should not use a trailing semicolon\n" . "$herectx");
5232 # check for redundant bracing round if etc
5233 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5234 my ($level, $endln, @chunks) =
5235 ctx_statement_full($linenr, $realcnt, 1);
5236 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5237 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5238 if ($#chunks > 0 && $level == 0) {
5242 my $herectx = $here . "\n";
5243 my $ln = $linenr - 1;
5244 for my $chunk (@chunks) {
5245 my ($cond, $block) = @{$chunk};
5247 # If the condition carries leading newlines, then count those as offsets.
5248 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5249 my $offset = statement_rawlines($whitespace) - 1;
5251 $allowed[$allow] = 0;
5252 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5254 # We have looked at and allowed this specific line.
5255 $suppress_ifbraces{$ln + $offset} = 1;
5257 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5258 $ln += statement_rawlines($block) - 1;
5260 substr($block, 0, length($cond), '');
5262 $seen++ if ($block =~ /^\s*{/);
5264 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5265 if (statement_lines($cond) > 1) {
5266 #print "APW: ALLOWED: cond<$cond>\n";
5267 $allowed[$allow] = 1;
5269 if ($block =~/\b(?:if|for|while)\b/) {
5270 #print "APW: ALLOWED: block<$block>\n";
5271 $allowed[$allow] = 1;
5273 if (statement_block_size($block) > 1) {
5274 #print "APW: ALLOWED: lines block<$block>\n";
5275 $allowed[$allow] = 1;
5280 my $sum_allowed = 0;
5281 foreach (@allowed) {
5284 if ($sum_allowed == 0) {
5286 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5287 } elsif ($sum_allowed != $allow &&
5290 "braces {} should be used on all arms of this statement\n" . $herectx);
5295 if (!defined $suppress_ifbraces{$linenr - 1} &&
5296 $line =~ /\b(if|while|for|else)\b/) {
5299 # Check the pre-context.
5300 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5301 #print "APW: ALLOWED: pre<$1>\n";
5305 my ($level, $endln, @chunks) =
5306 ctx_statement_full($linenr, $realcnt, $-[0]);
5308 # Check the condition.
5309 my ($cond, $block) = @{$chunks[0]};
5310 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5311 if (defined $cond) {
5312 substr($block, 0, length($cond), '');
5314 if (statement_lines($cond) > 1) {
5315 #print "APW: ALLOWED: cond<$cond>\n";
5318 if ($block =~/\b(?:if|for|while)\b/) {
5319 #print "APW: ALLOWED: block<$block>\n";
5322 if (statement_block_size($block) > 1) {
5323 #print "APW: ALLOWED: lines block<$block>\n";
5326 # Check the post-context.
5327 if (defined $chunks[1]) {
5328 my ($cond, $block) = @{$chunks[1]};
5329 if (defined $cond) {
5330 substr($block, 0, length($cond), '');
5332 if ($block =~ /^\s*\{/) {
5333 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5337 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5338 my $cnt = statement_rawlines($block);
5339 my $herectx = get_stat_here($linenr, $cnt, $here);
5342 "braces {} are not necessary for single statement blocks\n" . $herectx);
5346 # check for single line unbalanced braces
5347 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5348 $sline =~ /^.\s*else\s*\{\s*$/) {
5349 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5352 # check for unnecessary blank lines around braces
5353 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5355 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5356 $fix && $prevrawline =~ /^\+/) {
5357 fix_delete_line($fixlinenr - 1, $prevrawline);
5360 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5362 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5364 fix_delete_line($fixlinenr, $rawline);
5368 # no volatiles please
5369 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5370 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5372 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5375 # Check for user-visible strings broken across lines, which breaks the ability
5376 # to grep for the string. Make exceptions when the previous string ends in a
5377 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5378 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5379 if ($line =~ /^\+\s*$String/ &&
5380 $prevline =~ /"\s*$/ &&
5381 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5382 if (WARN("SPLIT_STRING",
5383 "quoted string split across lines\n" . $hereprev) &&
5385 $prevrawline =~ /^\+.*"\s*$/ &&
5386 $last_coalesced_string_linenr != $linenr - 1) {
5387 my $extracted_string = get_quoted_string($line, $rawline);
5388 my $comma_close = "";
5389 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5393 fix_delete_line($fixlinenr - 1, $prevrawline);
5394 fix_delete_line($fixlinenr, $rawline);
5395 my $fixedline = $prevrawline;
5396 $fixedline =~ s/"\s*$//;
5397 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5398 fix_insert_line($fixlinenr - 1, $fixedline);
5399 $fixedline = $rawline;
5400 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5401 if ($fixedline !~ /\+\s*$/) {
5402 fix_insert_line($fixlinenr, $fixedline);
5404 $last_coalesced_string_linenr = $linenr;
5408 # check for missing a space in a string concatenation
5409 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5410 WARN('MISSING_SPACE',
5411 "break quoted strings at a space character\n" . $hereprev);
5414 # check for an embedded function name in a string when the function is known
5415 # This does not work very well for -f --file checking as it depends on patch
5416 # context providing the function name or a single line form for in-file
5417 # function declarations
5418 if ($line =~ /^\+.*$String/ &&
5419 defined($context_function) &&
5420 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5421 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5422 WARN("EMBEDDED_FUNCTION_NAME",
5423 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5426 # check for spaces before a quoted newline
5427 if ($rawline =~ /^.*\".*\s\\n/) {
5428 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5429 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5431 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5436 # concatenated string without spaces between elements
5437 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5438 if (CHK("CONCATENATED_STRING",
5439 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5441 while ($line =~ /($String)/g) {
5442 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5443 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5444 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5449 # uncoalesced string fragments
5450 if ($line =~ /$String\s*"/) {
5451 if (WARN("STRING_FRAGMENTS",
5452 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5454 while ($line =~ /($String)(?=\s*")/g) {
5455 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5456 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5461 # check for non-standard and hex prefixed decimal printf formats
5462 my $show_L = 1; #don't show the same defect twice
5464 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5465 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5466 $string =~ s/%%/__/g;
5468 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5470 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5474 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5476 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5479 # check for 0x<decimal>
5480 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5481 ERROR("PRINTF_0XDECIMAL",
5482 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5486 # check for line continuations in quoted strings with odd counts of "
5487 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5488 WARN("LINE_CONTINUATIONS",
5489 "Avoid line continuations in quoted strings\n" . $herecurr);
5493 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5495 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5499 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5501 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5504 # check for needless "if (<foo>) fn(<foo>)" uses
5505 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5506 my $tested = quotemeta($1);
5507 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5508 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5510 if (WARN('NEEDLESS_IF',
5511 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5514 my $leading_tabs = "";
5515 my $new_leading_tabs = "";
5516 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5521 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5522 $new_leading_tabs = $1;
5523 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5530 fix_delete_line($fixlinenr - 1, $prevrawline);
5531 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5537 # check for unnecessary "Out of Memory" messages
5538 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5539 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5540 (defined $1 || defined $3) &&
5543 my $testline = $lines[$linenr - 3];
5545 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5546 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5548 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|kmemdup|(?:dev_)?alloc_skb)/) {
5550 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5554 # check for logging functions with KERN_<LEVEL>
5555 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5556 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5558 if (WARN("UNNECESSARY_KERN_LEVEL",
5559 "Possible unnecessary $level\n" . $herecurr) &&
5561 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5565 # check for logging continuations
5566 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5567 WARN("LOGGING_CONTINUATION",
5568 "Avoid logging continuation uses where feasible\n" . $herecurr);
5571 # check for mask then right shift without a parentheses
5572 if ($perl_version_ok &&
5573 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5574 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5575 WARN("MASK_THEN_SHIFT",
5576 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5579 # check for pointer comparisons to NULL
5580 if ($perl_version_ok) {
5581 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5584 $equal = "" if ($4 eq "!=");
5585 if (CHK("COMPARISON_TO_NULL",
5586 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5588 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5593 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5594 if ($line =~ /(\b$InitAttribute\b)/) {
5596 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5599 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5600 ERROR("MISPLACED_INIT",
5601 "$attr should be placed after $var\n" . $herecurr)) ||
5602 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5603 WARN("MISPLACED_INIT",
5604 "$attr should be placed after $var\n" . $herecurr))) &&
5606 $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;
5611 # check for $InitAttributeData (ie: __initdata) with const
5612 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5614 $attr =~ /($InitAttributePrefix)(.*)/;
5615 my $attr_prefix = $1;
5617 if (ERROR("INIT_ATTRIBUTE",
5618 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5620 $fixed[$fixlinenr] =~
5621 s/$InitAttributeData/${attr_prefix}initconst/;
5625 # check for $InitAttributeConst (ie: __initconst) without const
5626 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5628 if (ERROR("INIT_ATTRIBUTE",
5629 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5631 my $lead = $fixed[$fixlinenr] =~
5632 /(^\+\s*(?:static\s+))/;
5634 $lead = "$lead " if ($lead !~ /^\+$/);
5635 $lead = "${lead}const ";
5636 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5640 # check for __read_mostly with const non-pointer (should just be const)
5641 if ($line =~ /\b__read_mostly\b/ &&
5642 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5643 if (ERROR("CONST_READ_MOSTLY",
5644 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5646 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5650 # don't use __constant_<foo> functions outside of include/uapi/
5651 if ($realfile !~ m@^include/uapi/@ &&
5652 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5653 my $constant_func = $1;
5654 my $func = $constant_func;
5655 $func =~ s/^__constant_//;
5656 if (WARN("CONSTANT_CONVERSION",
5657 "$constant_func should be $func\n" . $herecurr) &&
5659 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5663 # prefer usleep_range over udelay
5664 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5666 # ignore udelay's < 10, however
5667 if (! ($delay < 10) ) {
5669 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5671 if ($delay > 2000) {
5673 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5677 # warn about unexpectedly long msleep's
5678 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5681 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5685 # check for comparisons of jiffies
5686 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5687 WARN("JIFFIES_COMPARISON",
5688 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5691 # check for comparisons of get_jiffies_64()
5692 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5693 WARN("JIFFIES_COMPARISON",
5694 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5697 # warn about #ifdefs in C files
5698 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5699 # print "#ifdef in C files should be avoided\n";
5700 # print "$herecurr";
5704 # warn about spacing in #ifdefs
5705 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5706 if (ERROR("SPACING",
5707 "exactly one space required after that #$1\n" . $herecurr) &&
5709 $fixed[$fixlinenr] =~
5710 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5715 # check for spinlock_t definitions without a comment.
5716 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5717 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5719 if (!ctx_has_comment($first_line, $linenr)) {
5720 CHK("UNCOMMENTED_DEFINITION",
5721 "$1 definition without comment\n" . $herecurr);
5724 # check for memory barriers without a comment.
5730 read_barrier_depends
5732 my $barrier_stems = qr{
5740 my $all_barriers = qr{
5742 smp_(?:$barrier_stems)|
5743 virt_(?:$barrier_stems)
5746 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5747 if (!ctx_has_comment($first_line, $linenr)) {
5748 WARN("MEMORY_BARRIER",
5749 "memory barrier without comment\n" . $herecurr);
5753 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5755 if ($realfile !~ m@^include/asm-generic/@ &&
5756 $realfile !~ m@/barrier\.h$@ &&
5757 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5758 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5759 WARN("MEMORY_BARRIER",
5760 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5763 # check for waitqueue_active without a comment.
5764 if ($line =~ /\bwaitqueue_active\s*\(/) {
5765 if (!ctx_has_comment($first_line, $linenr)) {
5766 WARN("WAITQUEUE_ACTIVE",
5767 "waitqueue_active without comment\n" . $herecurr);
5771 # check for smp_read_barrier_depends and read_barrier_depends
5772 if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5773 WARN("READ_BARRIER_DEPENDS",
5774 "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5777 # check of hardware specific defines
5778 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5780 "architecture specific defines should be avoided\n" . $herecurr);
5783 # check that the storage class is not after a type
5784 if ($line =~ /\b($Type)\s+($Storage)\b/) {
5785 WARN("STORAGE_CLASS",
5786 "storage class '$2' should be located before type '$1'\n" . $herecurr);
5788 # Check that the storage class is at the beginning of a declaration
5789 if ($line =~ /\b$Storage\b/ &&
5790 $line !~ /^.\s*$Storage/ &&
5791 $line =~ /^.\s*(.+?)\$Storage\s/ &&
5792 $1 !~ /[\,\)]\s*$/) {
5793 WARN("STORAGE_CLASS",
5794 "storage class should be at the beginning of the declaration\n" . $herecurr);
5797 # check the location of the inline attribute, that it is between
5798 # storage class and type.
5799 if ($line =~ /\b$Type\s+$Inline\b/ ||
5800 $line =~ /\b$Inline\s+$Storage\b/) {
5801 ERROR("INLINE_LOCATION",
5802 "inline keyword should sit between storage class and type\n" . $herecurr);
5805 # Check for __inline__ and __inline, prefer inline
5806 if ($realfile !~ m@\binclude/uapi/@ &&
5807 $line =~ /\b(__inline__|__inline)\b/) {
5809 "plain inline is preferred over $1\n" . $herecurr) &&
5811 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5816 # Check for __attribute__ packed, prefer __packed
5817 if ($realfile !~ m@\binclude/uapi/@ &&
5818 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5819 WARN("PREFER_PACKED",
5820 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5823 # Check for __attribute__ aligned, prefer __aligned
5824 if ($realfile !~ m@\binclude/uapi/@ &&
5825 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5826 WARN("PREFER_ALIGNED",
5827 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5830 # Check for __attribute__ format(printf, prefer __printf
5831 if ($realfile !~ m@\binclude/uapi/@ &&
5832 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5833 if (WARN("PREFER_PRINTF",
5834 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5836 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5841 # Check for __attribute__ format(scanf, prefer __scanf
5842 if ($realfile !~ m@\binclude/uapi/@ &&
5843 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5844 if (WARN("PREFER_SCANF",
5845 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5847 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5851 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5852 if ($perl_version_ok &&
5853 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5854 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5855 $line =~ /\b__weak\b/)) {
5856 ERROR("WEAK_DECLARATION",
5857 "Using weak declarations can have unintended link defects\n" . $herecurr);
5860 # check for c99 types like uint8_t used outside of uapi/ and tools/
5861 if ($realfile !~ m@\binclude/uapi/@ &&
5862 $realfile !~ m@\btools/@ &&
5863 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5865 if ($type =~ /\b($typeC99Typedefs)\b/) {
5867 my $kernel_type = 'u';
5868 $kernel_type = 's' if ($type =~ /^_*[si]/);
5871 if (CHK("PREFER_KERNEL_TYPES",
5872 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5874 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5879 # check for cast of C90 native int or longer types constants
5880 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5883 if (WARN("TYPECAST_INT_CONSTANT",
5884 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5887 my $newconst = $const;
5888 $newconst =~ s/${Int_type}$//;
5889 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5890 if ($cast =~ /\blong\s+long\b/) {
5892 } elsif ($cast =~ /\blong\b/) {
5895 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5899 # check for sizeof(&)
5900 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5901 WARN("SIZEOF_ADDRESS",
5902 "sizeof(& should be avoided\n" . $herecurr);
5905 # check for sizeof without parenthesis
5906 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5907 if (WARN("SIZEOF_PARENTHESIS",
5908 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5910 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5914 # check for struct spinlock declarations
5915 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5916 WARN("USE_SPINLOCK_T",
5917 "struct spinlock should be spinlock_t\n" . $herecurr);
5920 # check for seq_printf uses that could be seq_puts
5921 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5922 my $fmt = get_quoted_string($line, $rawline);
5925 if (WARN("PREFER_SEQ_PUTS",
5926 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5928 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5933 # check for vsprintf extension %p<foo> misuses
5934 if ($perl_version_ok &&
5936 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
5937 $1 !~ /^_*volatile_*$/) {
5940 my $lc = $stat =~ tr@\n@@;
5941 $lc = $lc + $linenr;
5942 for (my $count = $linenr; $count <= $lc; $count++) {
5945 my $bad_specifier = "";
5946 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
5949 while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
5952 if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOx]/) {
5953 $bad_specifier = $specifier;
5956 if ($extension eq "x" && !defined($stat_real)) {
5957 if (!defined($stat_real)) {
5958 $stat_real = get_stat_real($linenr, $lc);
5960 WARN("VSPRINTF_SPECIFIER_PX",
5961 "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");
5964 if ($bad_specifier ne "") {
5965 my $stat_real = get_stat_real($linenr, $lc);
5966 my $ext_type = "Invalid";
5968 if ($bad_specifier =~ /p[Ff]/) {
5969 $ext_type = "Deprecated";
5970 $use = " - use %pS instead";
5971 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
5974 WARN("VSPRINTF_POINTER_EXTENSION",
5975 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
5980 # Check for misused memsets
5981 if ($perl_version_ok &&
5983 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5989 if ($ms_size =~ /^(0x|)0$/i) {
5991 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5992 } elsif ($ms_size =~ /^(0x|)1$/i) {
5994 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5998 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5999 # if ($perl_version_ok &&
6001 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6002 # if (WARN("PREFER_ETHER_ADDR_COPY",
6003 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6005 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6009 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6010 # if ($perl_version_ok &&
6012 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6013 # WARN("PREFER_ETHER_ADDR_EQUAL",
6014 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6017 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6018 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6019 # if ($perl_version_ok &&
6021 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6025 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6026 # if (WARN("PREFER_ETH_ZERO_ADDR",
6027 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6029 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6031 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6032 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6033 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6035 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6040 # typecasts on min/max could be min_t/max_t
6041 if ($perl_version_ok &&
6043 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6044 if (defined $2 || defined $7) {
6046 my $cast1 = deparenthesize($2);
6048 my $cast2 = deparenthesize($7);
6052 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6053 $cast = "$cast1 or $cast2";
6054 } elsif ($cast1 ne "") {
6060 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6064 # check usleep_range arguments
6065 if ($perl_version_ok &&
6067 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6071 WARN("USLEEP_RANGE",
6072 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6073 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6075 WARN("USLEEP_RANGE",
6076 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
6080 # check for naked sscanf
6081 if ($perl_version_ok &&
6083 $line =~ /\bsscanf\b/ &&
6084 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6085 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6086 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6087 my $lc = $stat =~ tr@\n@@;
6088 $lc = $lc + $linenr;
6089 my $stat_real = get_stat_real($linenr, $lc);
6090 WARN("NAKED_SSCANF",
6091 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6094 # check for simple sscanf that should be kstrto<foo>
6095 if ($perl_version_ok &&
6097 $line =~ /\bsscanf\b/) {
6098 my $lc = $stat =~ tr@\n@@;
6099 $lc = $lc + $linenr;
6100 my $stat_real = get_stat_real($linenr, $lc);
6101 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6103 my $count = $format =~ tr@%@%@;
6105 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6106 WARN("SSCANF_TO_KSTRTO",
6107 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6112 # check for new externs in .h files.
6113 if ($realfile =~ /\.h$/ &&
6114 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6115 if (CHK("AVOID_EXTERNS",
6116 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6118 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6122 # check for new externs in .c files.
6123 if ($realfile =~ /\.c$/ && defined $stat &&
6124 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6126 my $function_name = $1;
6127 my $paren_space = $2;
6130 if (defined $cond) {
6131 substr($s, 0, length($cond), '');
6133 if ($s =~ /^\s*;/ &&
6134 $function_name ne 'uninitialized_var')
6136 WARN("AVOID_EXTERNS",
6137 "externs should be avoided in .c files\n" . $herecurr);
6140 if ($paren_space =~ /\n/) {
6141 WARN("FUNCTION_ARGUMENTS",
6142 "arguments for function declarations should follow identifier\n" . $herecurr);
6145 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6146 $stat =~ /^.\s*extern\s+/)
6148 WARN("AVOID_EXTERNS",
6149 "externs should be avoided in .c files\n" . $herecurr);
6152 # check for function declarations that have arguments without identifier names
6153 if (defined $stat &&
6154 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6156 my $args = trim($1);
6157 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6159 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6160 WARN("FUNCTION_ARGUMENTS",
6161 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6166 # check for function definitions
6167 if ($perl_version_ok &&
6169 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6170 $context_function = $1;
6172 # check for multiline function definition with misplaced open brace
6174 my $cnt = statement_rawlines($stat);
6175 my $herectx = $here . "\n";
6176 for (my $n = 0; $n < $cnt; $n++) {
6177 my $rl = raw_line($linenr, $n);
6178 $herectx .= $rl . "\n";
6179 $ok = 1 if ($rl =~ /^[ \+]\{/);
6180 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6181 last if $rl =~ /^[ \+].*\{/;
6185 "open brace '{' following function definitions go on the next line\n" . $herectx);
6189 # checks for new __setup's
6190 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6193 if (!grep(/$name/, @setup_docs)) {
6194 CHK("UNDOCUMENTED_SETUP",
6195 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6199 # check for pointless casting of kmalloc return
6200 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
6201 WARN("UNNECESSARY_CASTS",
6202 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6206 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6207 if ($perl_version_ok &&
6208 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6209 CHK("ALLOC_SIZEOF_STRUCT",
6210 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6213 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6214 if ($perl_version_ok &&
6216 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6220 my $newfunc = "kmalloc_array";
6221 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6224 if ($a1 =~ /^sizeof\s*\S/) {
6228 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6229 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6230 my $cnt = statement_rawlines($stat);
6231 my $herectx = get_stat_here($linenr, $cnt, $here);
6233 if (WARN("ALLOC_WITH_MULTIPLY",
6234 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6237 $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;
6242 # check for krealloc arg reuse
6243 if ($perl_version_ok &&
6244 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6246 WARN("KREALLOC_ARG_REUSE",
6247 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6250 # check for alloc argument mismatch
6251 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6252 WARN("ALLOC_ARRAY_ARGS",
6253 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6256 # check for multiple semicolons
6257 if ($line =~ /;\s*;\s*$/) {
6258 if (WARN("ONE_SEMICOLON",
6259 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6261 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6265 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6266 if ($realfile !~ m@^include/uapi/@ &&
6267 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6269 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6270 if (CHK("BIT_MACRO",
6271 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6273 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6277 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6278 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6280 if (WARN("PREFER_IS_ENABLED",
6281 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6283 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6287 # check for case / default statements not preceded by break/fallthrough/switch
6288 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6290 my $has_statement = 0;
6292 my $prevline = $linenr;
6293 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6295 my $rline = $rawlines[$prevline - 1];
6296 my $fline = $lines[$prevline - 1];
6297 last if ($fline =~ /^\@\@/);
6298 next if ($fline =~ /^\-/);
6299 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6300 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6301 next if ($fline =~ /^.[\s$;]*$/);
6304 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6306 if (!$has_break && $has_statement) {
6307 WARN("MISSING_BREAK",
6308 "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6312 # check for switch/default statements without a break;
6313 if ($perl_version_ok &&
6315 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6316 my $cnt = statement_rawlines($stat);
6317 my $herectx = get_stat_here($linenr, $cnt, $here);
6319 WARN("DEFAULT_NO_BREAK",
6320 "switch default: should use break\n" . $herectx);
6323 # check for gcc specific __FUNCTION__
6324 if ($line =~ /\b__FUNCTION__\b/) {
6325 if (WARN("USE_FUNC",
6326 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6328 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6332 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6333 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6335 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6338 # check for use of yield()
6339 if ($line =~ /\byield\s*\(\s*\)/) {
6341 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6344 # check for comparisons against true and false
6345 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6353 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6355 my $type = lc($otype);
6356 if ($type =~ /^(?:true|false)$/) {
6357 if (("$test" eq "==" && "$type" eq "true") ||
6358 ("$test" eq "!=" && "$type" eq "false")) {
6362 CHK("BOOL_COMPARISON",
6363 "Using comparison to $otype is error prone\n" . $herecurr);
6365 ## maybe suggesting a correct construct would better
6366 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6371 # check for bool bitfields
6372 if ($sline =~ /^.\s+bool\s*$Ident\s*:\s*\d+\s*;/) {
6373 WARN("BOOL_BITFIELD",
6374 "Avoid using bool as bitfield. Prefer bool bitfields as unsigned int or u<8|16|32>\n" . $herecurr);
6377 # check for bool use in .h files
6378 if ($realfile =~ /\.h$/ &&
6379 $sline =~ /^.\s+bool\s*$Ident\s*(?::\s*d+\s*)?;/) {
6381 "Avoid using bool structure members because of possible alignment issues - see: https://lkml.org/lkml/2017/11/21/384\n" . $herecurr);
6384 # check for semaphores initialized locked
6385 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6386 WARN("CONSIDER_COMPLETION",
6387 "consider using a completion\n" . $herecurr);
6390 # recommend kstrto* over simple_strto* and strict_strto*
6391 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6392 WARN("CONSIDER_KSTRTO",
6393 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6396 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6397 if ($line =~ /^.\s*__initcall\s*\(/) {
6398 WARN("USE_DEVICE_INITCALL",
6399 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6402 # check for spin_is_locked(), suggest lockdep instead
6403 if ($line =~ /\bspin_is_locked\(/) {
6405 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6408 # check for deprecated apis
6409 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6410 my $deprecated_api = $1;
6411 my $new_api = $deprecated_apis{$deprecated_api};
6412 WARN("DEPRECATED_API",
6413 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6416 # check for various structs that are normally const (ops, kgdb, device_tree)
6417 # and avoid what seem like struct definitions 'struct foo {'
6418 if ($line !~ /\bconst\b/ &&
6419 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6420 WARN("CONST_STRUCT",
6421 "struct $1 should normally be const\n" . $herecurr);
6424 # use of NR_CPUS is usually wrong
6425 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6426 if ($line =~ /\bNR_CPUS\b/ &&
6427 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6428 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6429 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6430 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6431 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6434 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6437 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6438 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6439 ERROR("DEFINE_ARCH_HAS",
6440 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6443 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6444 if ($perl_version_ok &&
6445 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6446 WARN("LIKELY_MISUSE",
6447 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6450 # whine mightly about in_atomic
6451 if ($line =~ /\bin_atomic\s*\(/) {
6452 if ($realfile =~ m@^drivers/@) {
6454 "do not use in_atomic in drivers\n" . $herecurr);
6455 } elsif ($realfile !~ m@^kernel/@) {
6457 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6461 # check for mutex_trylock_recursive usage
6462 if ($line =~ /mutex_trylock_recursive/) {
6464 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6467 # check for lockdep_set_novalidate_class
6468 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6469 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6470 if ($realfile !~ m@^kernel/lockdep@ &&
6471 $realfile !~ m@^include/linux/lockdep@ &&
6472 $realfile !~ m@^drivers/base/core@) {
6474 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6478 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6479 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6480 WARN("EXPORTED_WORLD_WRITABLE",
6481 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6484 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6485 # and whether or not function naming is typical and if
6486 # DEVICE_ATTR permissions uses are unusual too
6487 if ($perl_version_ok &&
6489 $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*\)/) {
6494 my $octal_perms = perms_to_octal($perms);
6495 if ($show =~ /^${var}_show$/ &&
6496 $store =~ /^${var}_store$/ &&
6497 $octal_perms eq "0644") {
6498 if (WARN("DEVICE_ATTR_RW",
6499 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6501 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6503 } elsif ($show =~ /^${var}_show$/ &&
6504 $store =~ /^NULL$/ &&
6505 $octal_perms eq "0444") {
6506 if (WARN("DEVICE_ATTR_RO",
6507 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6509 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6511 } elsif ($show =~ /^NULL$/ &&
6512 $store =~ /^${var}_store$/ &&
6513 $octal_perms eq "0200") {
6514 if (WARN("DEVICE_ATTR_WO",
6515 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6517 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6519 } elsif ($octal_perms eq "0644" ||
6520 $octal_perms eq "0444" ||
6521 $octal_perms eq "0200") {
6522 my $newshow = "$show";
6523 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6524 my $newstore = $store;
6525 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6527 if ($show ne $newshow) {
6528 $rename .= " '$show' to '$newshow'";
6530 if ($store ne $newstore) {
6531 $rename .= " '$store' to '$newstore'";
6533 WARN("DEVICE_ATTR_FUNCTIONS",
6534 "Consider renaming function(s)$rename\n" . $herecurr);
6536 WARN("DEVICE_ATTR_PERMS",
6537 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6541 # Mode permission misuses where it seems decimal should be octal
6542 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6543 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6544 # specific definition of not visible in sysfs.
6545 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6546 # use the default permissions
6547 if ($perl_version_ok &&
6549 $line =~ /$mode_perms_search/) {
6550 foreach my $entry (@mode_permission_funcs) {
6551 my $func = $entry->[0];
6552 my $arg_pos = $entry->[1];
6554 my $lc = $stat =~ tr@\n@@;
6555 $lc = $lc + $linenr;
6556 my $stat_real = get_stat_real($linenr, $lc);
6561 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6563 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6564 if ($stat =~ /$test/) {
6566 $val = $6 if ($skip_args ne "");
6567 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6568 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6569 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6570 ERROR("NON_OCTAL_PERMISSIONS",
6571 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6573 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6574 ERROR("EXPORTED_WORLD_WRITABLE",
6575 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6581 # check for uses of S_<PERMS> that could be octal for readability
6582 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6584 my $octal = perms_to_octal($oval);
6585 if (WARN("SYMBOLIC_PERMS",
6586 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6588 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6592 # validate content of MODULE_LICENSE against list from include/linux/module.h
6593 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6594 my $extracted_string = get_quoted_string($line, $rawline);
6595 my $valid_licenses = qr{
6598 GPL\ and\ additional\ rights|
6604 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6605 WARN("MODULE_LICENSE",
6606 "unknown module license " . $extracted_string . "\n" . $herecurr);
6611 # If we have no input at all, then there is nothing to report on
6612 # so just keep quiet.
6613 if ($#rawlines == -1) {
6617 # In mailback mode only produce a report in the negative, for
6618 # things that appear to be patches.
6619 if ($mailback && ($clean == 1 || !$is_patch)) {
6623 # This is not a patch, and we are are in 'no-patch' mode so
6625 if (!$chk_patch && !$is_patch) {
6629 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6630 ERROR("NOT_UNIFIED_DIFF",
6631 "Does not appear to be a unified-diff format patch\n");
6633 if ($is_patch && $has_commit_log && $chk_signoff) {
6634 if ($signoff == 0) {
6635 ERROR("MISSING_SIGN_OFF",
6636 "Missing Signed-off-by: line(s)\n");
6637 } elsif (!$authorsignoff) {
6638 WARN("NO_AUTHOR_SIGN_OFF",
6639 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6643 print report_dump();
6644 if ($summary && !($clean == 1 && $quiet == 1)) {
6645 print "$filename " if ($summary_file);
6646 print "total: $cnt_error errors, $cnt_warn warnings, " .
6647 (($check)? "$cnt_chk checks, " : "") .
6648 "$cnt_lines lines checked\n";
6652 # If there were any defects found and not already fixing them
6653 if (!$clean and !$fix) {
6656 NOTE: For some of the reported defects, checkpatch may be able to
6657 mechanically convert to the typical style using --fix or --fix-inplace.
6660 # If there were whitespace errors which cleanpatch can fix
6661 # then suggest that.
6662 if ($rpt_cleaners) {
6666 NOTE: Whitespace errors detected.
6667 You may wish to use scripts/cleanpatch or scripts/cleanfile
6672 if ($clean == 0 && $fix &&
6673 ("@rawlines" ne "@fixed" ||
6674 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6675 my $newfile = $filename;
6676 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6680 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6682 open($f, '>', $newfile)
6683 or die "$P: Can't open $newfile for write\n";
6684 foreach my $fixed_line (@fixed) {
6687 if ($linecount > 3) {
6688 $fixed_line =~ s/^\+//;
6689 print $f $fixed_line . "\n";
6692 print $f $fixed_line . "\n";
6700 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6702 Do _NOT_ trust the results written to this file.
6703 Do _NOT_ submit these changes without inspecting them for correctness.
6705 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6706 No warranties, expressed or implied...
6714 print "$vname has no obvious style problems and is ready for submission.\n";
6716 print "$vname has style problems, please review.\n";