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);
46 my $gitroot = $ENV{'GIT_DIR'};
47 $gitroot = ".git" if !defined($gitroot);
55 my $configuration_file = ".checkpatch.conf";
56 my $max_line_length = 100;
57 my $ignore_perl_version = 0;
58 my $minimum_perl_version = 5.10.0;
59 my $min_conf_desc_length = 4;
60 my $spelling_file = "$D/spelling.txt";
62 my $codespellfile = "/usr/share/codespell/dictionary.txt";
63 my $conststructsfile = "$D/const_structs.checkpatch";
66 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
67 # git output parsing needs US English output, so first set backtick child process LANGUAGE
68 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
70 my ${CONFIG_} = "CONFIG_";
76 Usage: $P [OPTION]... [FILE]...
81 --no-tree run without a kernel tree
82 --no-signoff do not check for 'Signed-off-by' line
83 --patch treat FILE as patchfile (default)
84 --emacs emacs compile window format
85 --terse one line per report
86 --showfile emit diffed file position, not input file position
87 -g, --git treat FILE as a single commit or git revision range
88 single git commit with:
92 multiple git commits with:
96 git merges are ignored
97 -f, --file treat FILE as regular source file
98 --subjective, --strict enable more subjective tests
99 --list-types list the possible message types
100 --types TYPE(,TYPE2...) show only these comma separated message types
101 --ignore TYPE(,TYPE2...) ignore various comma separated message types
102 --show-types show the specific message type in the output
103 --max-line-length=n set the maximum line length, (default $max_line_length)
104 if exceeded, warn on patches
105 requires --strict for use with --file
106 --min-conf-desc-length=n set the min description length, if shorter, warn
107 --tab-size=n set the number of spaces for tab (default $tabsize)
108 --root=PATH PATH to the kernel tree root
109 --no-summary suppress the per-file summary
110 --mailback only produce a report in case of warnings/errors
111 --summary-file include the filename in summary
112 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
113 'values', 'possible', 'type', and 'attr' (default
115 --test-only=WORD report only warnings/errors containing WORD
117 --fix EXPERIMENTAL - may create horrible results
118 If correctable single-line errors exist, create
119 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
120 with potential errors corrected to the preferred
122 --fix-inplace EXPERIMENTAL - may create horrible results
123 Is the same as --fix, but overwrites the input
124 file. It's your fault if there's no backup or git
125 --ignore-perl-version override checking of perl version. expect
127 --codespell Use the codespell dictionary for spelling/typos
128 (default:/usr/share/codespell/dictionary.txt)
129 --codespellfile Use this codespell dictionary
130 --typedefsfile Read additional types from this file
131 --color[=WHEN] Use colors 'always', 'never', or only when output
132 is a terminal ('auto'). Default is 'auto'.
133 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
135 -h, --help, --version display this help and exit
137 When FILE is - read standard input.
145 return grep { !$seen{$_}++ } @_;
155 open(my $script, '<', abs_path($P)) or
156 die "$P: Can't read '$P' $!\n";
158 my $text = <$script>;
162 # Also catch when type or level is passed through a variable
163 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
166 @types = sort(uniq(@types));
167 print("#\tMessage type\n\n");
168 foreach my $type (@types) {
169 print(++$count . "\t" . $type . "\n");
175 my $conf = which_conf($configuration_file);
178 open(my $conffile, '<', "$conf")
179 or warn "$P: Can't find a readable $configuration_file file $!\n";
181 while (<$conffile>) {
184 $line =~ s/\s*\n?$//g;
188 next if ($line =~ m/^\s*#/);
189 next if ($line =~ m/^\s*$/);
191 my @words = split(" ", $line);
192 foreach my $word (@words) {
193 last if ($word =~ m/^#/);
194 push (@conf_args, $word);
198 unshift(@ARGV, @conf_args) if @conf_args;
201 # Perl's Getopt::Long allows options to take optional arguments after a space.
202 # Prevent --color by itself from consuming other arguments
204 if ($_ eq "--color" || $_ eq "-color") {
205 $_ = "--color=$color";
210 'q|quiet+' => \$quiet,
212 'signoff!' => \$chk_signoff,
213 'patch!' => \$chk_patch,
216 'showfile!' => \$showfile,
219 'subjective!' => \$check,
220 'strict!' => \$check,
221 'ignore=s' => \@ignore,
223 'show-types!' => \$show_types,
224 'list-types!' => \$list_types,
225 'max-line-length=i' => \$max_line_length,
226 'min-conf-desc-length=i' => \$min_conf_desc_length,
227 'tab-size=i' => \$tabsize,
229 'summary!' => \$summary,
230 'mailback!' => \$mailback,
231 'summary-file!' => \$summary_file,
233 'fix-inplace!' => \$fix_inplace,
234 'ignore-perl-version!' => \$ignore_perl_version,
235 'debug=s' => \%debug,
236 'test-only=s' => \$tst_only,
237 'codespell!' => \$codespell,
238 'codespellfile=s' => \$codespellfile,
239 'typedefsfile=s' => \$typedefsfile,
240 'color=s' => \$color,
241 'no-color' => \$color, #keep old behaviors of -nocolor
242 'nocolor' => \$color, #keep old behaviors of -nocolor
243 'kconfig-prefix=s' => \${CONFIG_},
250 list_types(0) if ($list_types);
252 $fix = 1 if ($fix_inplace);
253 $check_orig = $check;
255 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
259 my $perl_version_ok = 1;
260 if ($^V && $^V lt $minimum_perl_version) {
261 $perl_version_ok = 0;
262 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
263 exit(1) if (!$ignore_perl_version);
266 #if no filenames are given, push '-' to read patch from stdin
271 if ($color =~ /^[01]$/) {
273 } elsif ($color =~ /^always$/i) {
275 } elsif ($color =~ /^never$/i) {
277 } elsif ($color =~ /^auto$/i) {
278 $color = (-t STDOUT);
280 die "$P: Invalid color mode: $color\n";
283 # skip TAB size 1 to avoid additional checks on $tabsize - 1
284 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
286 sub hash_save_array_words {
287 my ($hashRef, $arrayRef) = @_;
289 my @array = split(/,/, join(',', @$arrayRef));
290 foreach my $word (@array) {
291 $word =~ s/\s*\n?$//g;
294 $word =~ tr/[a-z]/[A-Z]/;
296 next if ($word =~ m/^\s*#/);
297 next if ($word =~ m/^\s*$/);
303 sub hash_show_words {
304 my ($hashRef, $prefix) = @_;
306 if (keys %$hashRef) {
307 print "\nNOTE: $prefix message types:";
308 foreach my $word (sort keys %$hashRef) {
315 hash_save_array_words(\%ignore_type, \@ignore);
316 hash_save_array_words(\%use_type, \@use);
319 my $dbg_possible = 0;
322 for my $key (keys %debug) {
324 eval "\${dbg_$key} = '$debug{$key}';";
328 my $rpt_cleaners = 0;
337 if (!top_of_kernel_tree($root)) {
338 die "$P: $root: --root does not point at a valid tree\n";
341 if (top_of_kernel_tree('.')) {
343 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
344 top_of_kernel_tree($1)) {
349 if (!defined $root) {
350 print "Must be run from the top-level dir. of a kernel tree\n";
355 my $emitted_corrupt = 0;
358 [A-Za-z_][A-Za-z\d_]*
359 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
361 our $Storage = qr{extern|static|asmlinkage};
375 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
376 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
377 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
378 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
379 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
381 # Notes to $Attribute:
382 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
404 ____cacheline_aligned|
405 ____cacheline_aligned_in_smp|
406 ____cacheline_internodealigned_in_smp|
410 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
411 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
412 our $Lval = qr{$Ident(?:$Member)*};
414 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
415 our $Binary = qr{(?i)0b[01]+$Int_type?};
416 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
417 our $Int = qr{[0-9]+$Int_type?};
418 our $Octal = qr{0[0-7]+$Int_type?};
419 our $String = qr{"[X\t]*"};
420 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
421 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
422 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
423 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
424 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
425 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
426 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
427 our $Arithmetic = qr{\+|-|\*|\/|%};
431 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
434 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
438 our $NonptrTypeMisordered;
439 our $NonptrTypeWithAttr;
443 our $DeclareMisordered;
445 our $NON_ASCII_UTF8 = qr{
446 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
447 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
448 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
449 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
450 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
451 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
452 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
456 [\x09\x0A\x0D\x20-\x7E] # ASCII
460 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
461 our $typeOtherOSTypedefs = qr{(?x:
462 u_(?:char|short|int|long) | # bsd
463 u(?:nchar|short|int|long) # sysv
465 our $typeKernelTypedefs = qr{(?x:
466 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
469 our $typeTypedefs = qr{(?x:
471 $typeOtherOSTypedefs\b|
472 $typeKernelTypedefs\b
475 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
477 our $logFunctions = qr{(?x:
478 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
479 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
481 WARN(?:_RATELIMIT|_ONCE|)|
484 seq_vprintf|seq_printf|seq_puts
487 our $allocFunctions = qr{(?x:
489 (?:kv|k|v)[czm]alloc(?:_node|_array)? |
492 (?:\w+)?alloc_skb(?:_ip_align)? |
493 # dev_alloc_skb/netdev_alloc_skb, et al
497 our $signature_tags = qr{(?xi:
509 our @typeListMisordered = (
510 qr{char\s+(?:un)?signed},
511 qr{int\s+(?:(?:un)?signed\s+)?short\s},
512 qr{int\s+short(?:\s+(?:un)?signed)},
513 qr{short\s+int(?:\s+(?:un)?signed)},
514 qr{(?:un)?signed\s+int\s+short},
515 qr{short\s+(?:un)?signed},
516 qr{long\s+int\s+(?:un)?signed},
517 qr{int\s+long\s+(?:un)?signed},
518 qr{long\s+(?:un)?signed\s+int},
519 qr{int\s+(?:un)?signed\s+long},
520 qr{int\s+(?:un)?signed},
521 qr{int\s+long\s+long\s+(?:un)?signed},
522 qr{long\s+long\s+int\s+(?:un)?signed},
523 qr{long\s+long\s+(?:un)?signed\s+int},
524 qr{long\s+long\s+(?:un)?signed},
525 qr{long\s+(?:un)?signed},
530 qr{(?:(?:un)?signed\s+)?char},
531 qr{(?:(?:un)?signed\s+)?short\s+int},
532 qr{(?:(?:un)?signed\s+)?short},
533 qr{(?:(?:un)?signed\s+)?int},
534 qr{(?:(?:un)?signed\s+)?long\s+int},
535 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
536 qr{(?:(?:un)?signed\s+)?long\s+long},
537 qr{(?:(?:un)?signed\s+)?long},
546 qr{${Ident}_handler},
547 qr{${Ident}_handler_fn},
551 our $C90_int_types = qr{(?x:
552 long\s+long\s+int\s+(?:un)?signed|
553 long\s+long\s+(?:un)?signed\s+int|
554 long\s+long\s+(?:un)?signed|
555 (?:(?:un)?signed\s+)?long\s+long\s+int|
556 (?:(?:un)?signed\s+)?long\s+long|
557 int\s+long\s+long\s+(?:un)?signed|
558 int\s+(?:(?:un)?signed\s+)?long\s+long|
560 long\s+int\s+(?:un)?signed|
561 long\s+(?:un)?signed\s+int|
562 long\s+(?:un)?signed|
563 (?:(?:un)?signed\s+)?long\s+int|
564 (?:(?:un)?signed\s+)?long|
565 int\s+long\s+(?:un)?signed|
566 int\s+(?:(?:un)?signed\s+)?long|
569 (?:(?:un)?signed\s+)?int
572 our @typeListFile = ();
573 our @typeListWithAttr = (
575 qr{struct\s+$InitAttribute\s+$Ident},
576 qr{union\s+$InitAttribute\s+$Ident},
579 our @modifierList = (
582 our @modifierListFile = ();
584 our @mode_permission_funcs = (
586 ["module_param_(?:array|named|string)", 4],
587 ["module_param_array_named", 5],
588 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
589 ["proc_create(?:_data|)", 2],
590 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
591 ["IIO_DEV_ATTR_[A-Z_]+", 1],
592 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
593 ["SENSOR_TEMPLATE(?:_2|)", 3],
597 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
599 #Create a search pattern for all these functions to speed up a loop below
600 our $mode_perms_search = "";
601 foreach my $entry (@mode_permission_funcs) {
602 $mode_perms_search .= '|' if ($mode_perms_search ne "");
603 $mode_perms_search .= $entry->[0];
605 $mode_perms_search = "(?:${mode_perms_search})";
607 our %deprecated_apis = (
608 "synchronize_rcu_bh" => "synchronize_rcu",
609 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
610 "call_rcu_bh" => "call_rcu",
611 "rcu_barrier_bh" => "rcu_barrier",
612 "synchronize_sched" => "synchronize_rcu",
613 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
614 "call_rcu_sched" => "call_rcu",
615 "rcu_barrier_sched" => "rcu_barrier",
616 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
617 "cond_synchronize_sched" => "cond_synchronize_rcu",
620 #Create a search pattern for all these strings to speed up a loop below
621 our $deprecated_apis_search = "";
622 foreach my $entry (keys %deprecated_apis) {
623 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
624 $deprecated_apis_search .= $entry;
626 $deprecated_apis_search = "(?:${deprecated_apis_search})";
628 our $mode_perms_world_writable = qr{
636 our %mode_permission_string_types = (
655 #Create a search pattern for all these strings to speed up a loop below
656 our $mode_perms_string_search = "";
657 foreach my $entry (keys %mode_permission_string_types) {
658 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
659 $mode_perms_string_search .= $entry;
661 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
662 our $multi_mode_perms_string_search = qr{
663 ${single_mode_perms_string_search}
664 (?:\s*\|\s*${single_mode_perms_string_search})*
670 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
677 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
678 $curpos = pos($string);
681 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
683 $to |= $mode_permission_string_types{$match};
684 $val .= '\s*\|\s*' if ($val ne "");
688 $oval =~ s/^\s*\|\s*//;
689 $oval =~ s/\s*\|\s*$//;
690 return sprintf("%04o", $to);
693 our $allowed_asm_includes = qr{(?x:
699 # memory.h: ARM has a custom one
701 # Load common spelling mistakes and build regular expression list.
705 if (open(my $spelling, '<', $spelling_file)) {
706 while (<$spelling>) {
709 $line =~ s/\s*\n?$//g;
712 next if ($line =~ m/^\s*#/);
713 next if ($line =~ m/^\s*$/);
715 my ($suspect, $fix) = split(/\|\|/, $line);
717 $spelling_fix{$suspect} = $fix;
721 warn "No typos will be found - file '$spelling_file': $!\n";
725 if (open(my $spelling, '<', $codespellfile)) {
726 while (<$spelling>) {
729 $line =~ s/\s*\n?$//g;
732 next if ($line =~ m/^\s*#/);
733 next if ($line =~ m/^\s*$/);
734 next if ($line =~ m/, disabled/i);
738 my ($suspect, $fix) = split(/->/, $line);
740 $spelling_fix{$suspect} = $fix;
744 warn "No codespell typos will be found - file '$codespellfile': $!\n";
748 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
751 my ($wordsRef, $file) = @_;
753 if (open(my $words, '<', $file)) {
757 $line =~ s/\s*\n?$//g;
760 next if ($line =~ m/^\s*#/);
761 next if ($line =~ m/^\s*$/);
763 print("$file: '$line' invalid - ignored\n");
767 $$wordsRef .= '|' if (defined $$wordsRef);
778 if (show_type("CONST_STRUCT")) {
779 read_words(\$const_structs, $conststructsfile)
780 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
783 if (defined($typedefsfile)) {
784 my $typeOtherTypedefs;
785 read_words(\$typeOtherTypedefs, $typedefsfile)
786 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
787 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
791 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
792 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
793 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
794 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
795 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
801 (?:$Modifier\s+|const\s+)*
803 (?:typeof|__typeof__)\s*\([^\)]*\)|
807 (?:\s+$Modifier|\s+const)*
809 $NonptrTypeMisordered = qr{
810 (?:$Modifier\s+|const\s+)*
814 (?:\s+$Modifier|\s+const)*
816 $NonptrTypeWithAttr = qr{
817 (?:$Modifier\s+|const\s+)*
819 (?:typeof|__typeof__)\s*\([^\)]*\)|
823 (?:\s+$Modifier|\s+const)*
827 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
828 (?:\s+$Inline|\s+$Modifier)*
830 $TypeMisordered = qr{
831 $NonptrTypeMisordered
832 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
833 (?:\s+$Inline|\s+$Modifier)*
835 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
836 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
840 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
842 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
843 # requires at least perl version v5.10.0
844 # Any use must be runtime checked with $^V
846 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
847 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
848 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
850 our $declaration_macros = qr{(?x:
851 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
852 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
853 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
856 our %allow_repeated_words = (
865 return "" if (!defined($string));
867 while ($string =~ /^\s*\(.*\)\s*$/) {
868 $string =~ s@^\s*\(\s*@@;
869 $string =~ s@\s*\)\s*$@@;
872 $string =~ s@\s+@ @g;
877 sub seed_camelcase_file {
880 return if (!(-f $file));
884 open(my $include_file, '<', "$file")
885 or warn "$P: Can't read '$file' $!\n";
886 my $text = <$include_file>;
887 close($include_file);
889 my @lines = split('\n', $text);
891 foreach my $line (@lines) {
892 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
893 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
895 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
897 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
903 our %maintained_status = ();
905 sub is_maintained_obsolete {
908 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
910 if (!exists($maintained_status{$filename})) {
911 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
914 return $maintained_status{$filename} =~ /obsolete/i;
917 sub is_SPDX_License_valid {
920 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
922 my $root_path = abs_path($root);
923 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
924 return 0 if ($status ne "");
928 my $camelcase_seeded = 0;
929 sub seed_camelcase_includes {
930 return if ($camelcase_seeded);
933 my $camelcase_cache = "";
934 my @include_files = ();
936 $camelcase_seeded = 1;
939 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
940 chomp $git_last_include_commit;
941 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
943 my $last_mod_date = 0;
944 $files = `find $root/include -name "*.h"`;
945 @include_files = split('\n', $files);
946 foreach my $file (@include_files) {
947 my $date = POSIX::strftime("%Y%m%d%H%M",
948 localtime((stat $file)[9]));
949 $last_mod_date = $date if ($last_mod_date < $date);
951 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
954 if ($camelcase_cache ne "" && -f $camelcase_cache) {
955 open(my $camelcase_file, '<', "$camelcase_cache")
956 or warn "$P: Can't read '$camelcase_cache' $!\n";
957 while (<$camelcase_file>) {
961 close($camelcase_file);
967 $files = `${git_command} ls-files "include/*.h"`;
968 @include_files = split('\n', $files);
971 foreach my $file (@include_files) {
972 seed_camelcase_file($file);
975 if ($camelcase_cache ne "") {
976 unlink glob ".checkpatch-camelcase.*";
977 open(my $camelcase_file, '>', "$camelcase_cache")
978 or warn "$P: Can't write '$camelcase_cache' $!\n";
979 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
980 print $camelcase_file ("$_\n");
982 close($camelcase_file);
986 sub git_is_single_file {
989 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
991 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
992 my $count = $output =~ tr/\n//;
993 return $count eq 1 && $output =~ m{^${filename}$};
996 sub git_commit_info {
997 my ($commit, $id, $desc) = @_;
999 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1001 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1002 $output =~ s/^\s*//gm;
1003 my @lines = split("\n", $output);
1005 return ($id, $desc) if ($#lines < 0);
1007 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1008 # Maybe one day convert this block of bash into something that returns
1009 # all matching commit ids, but it's very slow...
1011 # echo "checking commits $1..."
1012 # git rev-list --remotes | grep -i "^$1" |
1013 # while read line ; do
1014 # git log --format='%H %s' -1 $line |
1015 # echo "commit $(cut -c 1-12,41-)"
1017 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1020 $id = substr($lines[0], 0, 12);
1021 $desc = substr($lines[0], 41);
1024 return ($id, $desc);
1027 $chk_signoff = 0 if ($file);
1032 my @fixed_inserted = ();
1033 my @fixed_deleted = ();
1036 # If input is git commits, extract all commits from the commit expressions.
1037 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1038 die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1042 foreach my $commit_expr (@ARGV) {
1044 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1045 $git_range = "-$2 $1";
1046 } elsif ($commit_expr =~ m/\.\./) {
1047 $git_range = "$commit_expr";
1049 $git_range = "-1 $commit_expr";
1051 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1052 foreach my $line (split(/\n/, $lines)) {
1053 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1054 next if (!defined($1) || !defined($2));
1057 unshift(@commits, $sha1);
1058 $git_commits{$sha1} = $subject;
1061 die "$P: no git commits after extraction!\n" if (@commits == 0);
1066 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1067 for my $filename (@ARGV) {
1069 my $is_git_file = git_is_single_file($filename);
1070 my $oldfile = $file;
1071 $file = 1 if ($is_git_file);
1073 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1074 die "$P: $filename: git format-patch failed - $!\n";
1076 open($FILE, '-|', "diff -u /dev/null $filename") ||
1077 die "$P: $filename: diff failed - $!\n";
1078 } elsif ($filename eq '-') {
1079 open($FILE, '<&STDIN');
1081 open($FILE, '<', "$filename") ||
1082 die "$P: $filename: open failed - $!\n";
1084 if ($filename eq '-') {
1085 $vname = 'Your patch';
1087 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1093 push(@rawlines, $_);
1094 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1098 if ($#ARGV > 0 && $quiet == 0) {
1099 print '-' x length($vname) . "\n";
1101 print '-' x length($vname) . "\n";
1104 if (!process($filename)) {
1110 @fixed_inserted = ();
1111 @fixed_deleted = ();
1113 @modifierListFile = ();
1116 $file = $oldfile if ($is_git_file);
1120 hash_show_words(\%use_type, "Used");
1121 hash_show_words(\%ignore_type, "Ignored");
1123 if (!$perl_version_ok) {
1126 NOTE: perl $^V is not modern enough to detect all possible issues.
1127 An upgrade to at least perl $minimum_perl_version is suggested.
1133 NOTE: If any of the errors are false positives, please report
1134 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1141 sub top_of_kernel_tree {
1145 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1146 "README", "Documentation", "arch", "include", "drivers",
1147 "fs", "init", "ipc", "kernel", "lib", "scripts",
1150 foreach my $check (@tree_check) {
1151 if (! -e $root . '/' . $check) {
1159 my ($formatted_email) = @_;
1162 my $name_comment = "";
1166 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1169 $comment = $3 if defined $3;
1170 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1172 $comment = $2 if defined $2;
1173 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1175 $comment = $2 if defined $2;
1176 $formatted_email =~ s/\Q$address\E.*$//;
1177 $name = $formatted_email;
1178 $name = trim($name);
1179 $name =~ s/^\"|\"$//g;
1180 # If there's a name left after stripping spaces and
1181 # leading quotes, and the address doesn't have both
1182 # leading and trailing angle brackets, the address
1184 # "joe smith joe@smith.com" bad
1185 # "joe smith <joe@smith.com" bad
1186 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1193 $comment = trim($comment);
1194 $name = trim($name);
1195 $name =~ s/^\"|\"$//g;
1196 if ($name =~ s/(\s*\([^\)]+\))\s*//) {
1197 $name_comment = trim($1);
1199 $address = trim($address);
1200 $address =~ s/^\<|\>$//g;
1202 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1203 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1204 $name = "\"$name\"";
1207 return ($name, $name_comment, $address, $comment);
1211 my ($name, $name_comment, $address, $comment) = @_;
1213 my $formatted_email;
1215 $name_comment = trim($name_comment);
1216 $comment = trim($comment);
1217 $name = trim($name);
1218 $name =~ s/^\"|\"$//g;
1219 $address = trim($address);
1221 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1222 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1223 $name = "\"$name\"";
1226 if ("$name" eq "") {
1227 $formatted_email = "$address";
1229 $formatted_email = "$name$name_comment <$address>";
1231 $formatted_email .= "$comment";
1232 return $formatted_email;
1235 sub reformat_email {
1238 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1239 return format_email($email_name, $name_comment, $email_address, $comment);
1242 sub same_email_addresses {
1243 my ($email1, $email2, $match_comment) = @_;
1245 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1246 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1248 if ($match_comment != 1) {
1249 return $email1_name eq $email2_name &&
1250 $email1_address eq $email2_address;
1252 return $email1_name eq $email2_name &&
1253 $email1_address eq $email2_address &&
1254 $name1_comment eq $name2_comment &&
1255 $comment1 eq $comment2;
1261 foreach my $path (split(/:/, $ENV{PATH})) {
1262 if (-e "$path/$bin") {
1263 return "$path/$bin";
1273 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1274 if (-e "$path/$conf") {
1275 return "$path/$conf";
1287 for my $c (split(//, $str)) {
1291 for (; ($n % $tabsize) != 0; $n++) {
1303 (my $res = shift) =~ tr/\t/ /c;
1310 # Drop the diff line leader and expand tabs
1312 $line = expand_tabs($line);
1314 # Pick the indent from the front of the line.
1315 my ($white) = ($line =~ /^(\s*)/);
1317 return (length($line), length($white));
1320 my $sanitise_quote = '';
1322 sub sanitise_line_reset {
1323 my ($in_comment) = @_;
1326 $sanitise_quote = '*/';
1328 $sanitise_quote = '';
1341 # Always copy over the diff marker.
1342 $res = substr($line, 0, 1);
1344 for ($off = 1; $off < length($line); $off++) {
1345 $c = substr($line, $off, 1);
1347 # Comments we are whacking completely including the begin
1348 # and end, all to $;.
1349 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1350 $sanitise_quote = '*/';
1352 substr($res, $off, 2, "$;$;");
1356 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1357 $sanitise_quote = '';
1358 substr($res, $off, 2, "$;$;");
1362 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1363 $sanitise_quote = '//';
1365 substr($res, $off, 2, $sanitise_quote);
1370 # A \ in a string means ignore the next character.
1371 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1373 substr($res, $off, 2, 'XX');
1378 if ($c eq "'" || $c eq '"') {
1379 if ($sanitise_quote eq '') {
1380 $sanitise_quote = $c;
1382 substr($res, $off, 1, $c);
1384 } elsif ($sanitise_quote eq $c) {
1385 $sanitise_quote = '';
1389 #print "c<$c> SQ<$sanitise_quote>\n";
1390 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1391 substr($res, $off, 1, $;);
1392 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1393 substr($res, $off, 1, $;);
1394 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1395 substr($res, $off, 1, 'X');
1397 substr($res, $off, 1, $c);
1401 if ($sanitise_quote eq '//') {
1402 $sanitise_quote = '';
1405 # The pathname on a #include may be surrounded by '<' and '>'.
1406 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1407 my $clean = 'X' x length($1);
1408 $res =~ s@\<.*\>@<$clean>@;
1410 # The whole of a #error is a string.
1411 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1412 my $clean = 'X' x length($1);
1413 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1416 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1418 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1424 sub get_quoted_string {
1425 my ($line, $rawline) = @_;
1427 return "" if (!defined($line) || !defined($rawline));
1428 return "" if ($line !~ m/($String)/g);
1429 return substr($rawline, $-[0], $+[0] - $-[0]);
1432 sub ctx_statement_block {
1433 my ($linenr, $remain, $off) = @_;
1434 my $line = $linenr - 1;
1437 my $coff = $off - 1;
1451 @stack = (['', 0]) if ($#stack == -1);
1453 #warn "CSB: blk<$blk> remain<$remain>\n";
1454 # If we are about to drop off the end, pull in more
1457 for (; $remain > 0; $line++) {
1458 last if (!defined $lines[$line]);
1459 next if ($lines[$line] =~ /^-/);
1462 $blk .= $lines[$line] . "\n";
1463 $len = length($blk);
1467 # Bail if there is no further context.
1468 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1472 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1478 $c = substr($blk, $off, 1);
1479 $remainder = substr($blk, $off);
1481 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1483 # Handle nested #if/#else.
1484 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1485 push(@stack, [ $type, $level ]);
1486 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1487 ($type, $level) = @{$stack[$#stack - 1]};
1488 } elsif ($remainder =~ /^#\s*endif\b/) {
1489 ($type, $level) = @{pop(@stack)};
1492 # Statement ends at the ';' or a close '}' at the
1494 if ($level == 0 && $c eq ';') {
1498 # An else is really a conditional as long as its not else if
1499 if ($level == 0 && $coff_set == 0 &&
1500 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1501 $remainder =~ /^(else)(?:\s|{)/ &&
1502 $remainder !~ /^else\s+if\b/) {
1503 $coff = $off + length($1) - 1;
1505 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1506 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1509 if (($type eq '' || $type eq '(') && $c eq '(') {
1513 if ($type eq '(' && $c eq ')') {
1515 $type = ($level != 0)? '(' : '';
1517 if ($level == 0 && $coff < $soff) {
1520 #warn "CSB: mark coff<$coff>\n";
1523 if (($type eq '' || $type eq '{') && $c eq '{') {
1527 if ($type eq '{' && $c eq '}') {
1529 $type = ($level != 0)? '{' : '';
1532 if (substr($blk, $off + 1, 1) eq ';') {
1538 # Preprocessor commands end at the newline unless escaped.
1539 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1547 # We are truly at the end, so shuffle to the next line.
1554 my $statement = substr($blk, $soff, $off - $soff + 1);
1555 my $condition = substr($blk, $soff, $coff - $soff + 1);
1557 #warn "STATEMENT<$statement>\n";
1558 #warn "CONDITION<$condition>\n";
1560 #print "coff<$coff> soff<$off> loff<$loff>\n";
1562 return ($statement, $condition,
1563 $line, $remain + 1, $off - $loff + 1, $level);
1566 sub statement_lines {
1569 # Strip the diff line prefixes and rip blank lines at start and end.
1570 $stmt =~ s/(^|\n)./$1/g;
1574 my @stmt_lines = ($stmt =~ /\n/g);
1576 return $#stmt_lines + 2;
1579 sub statement_rawlines {
1582 my @stmt_lines = ($stmt =~ /\n/g);
1584 return $#stmt_lines + 2;
1587 sub statement_block_size {
1590 $stmt =~ s/(^|\n)./$1/g;
1596 my @stmt_lines = ($stmt =~ /\n/g);
1597 my @stmt_statements = ($stmt =~ /;/g);
1599 my $stmt_lines = $#stmt_lines + 2;
1600 my $stmt_statements = $#stmt_statements + 1;
1602 if ($stmt_lines > $stmt_statements) {
1605 return $stmt_statements;
1609 sub ctx_statement_full {
1610 my ($linenr, $remain, $off) = @_;
1611 my ($statement, $condition, $level);
1615 # Grab the first conditional/block pair.
1616 ($statement, $condition, $linenr, $remain, $off, $level) =
1617 ctx_statement_block($linenr, $remain, $off);
1618 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1619 push(@chunks, [ $condition, $statement ]);
1620 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1621 return ($level, $linenr, @chunks);
1624 # Pull in the following conditional/block pairs and see if they
1625 # could continue the statement.
1627 ($statement, $condition, $linenr, $remain, $off, $level) =
1628 ctx_statement_block($linenr, $remain, $off);
1629 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1630 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1632 push(@chunks, [ $condition, $statement ]);
1635 return ($level, $linenr, @chunks);
1639 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1641 my $start = $linenr - 1;
1648 my @stack = ($level);
1649 for ($line = $start; $remain > 0; $line++) {
1650 next if ($rawlines[$line] =~ /^-/);
1653 $blk .= $rawlines[$line];
1655 # Handle nested #if/#else.
1656 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1657 push(@stack, $level);
1658 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1659 $level = $stack[$#stack - 1];
1660 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1661 $level = pop(@stack);
1664 foreach my $c (split(//, $lines[$line])) {
1665 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1671 if ($c eq $close && $level > 0) {
1673 last if ($level == 0);
1674 } elsif ($c eq $open) {
1679 if (!$outer || $level <= 1) {
1680 push(@res, $rawlines[$line]);
1683 last if ($level == 0);
1686 return ($level, @res);
1688 sub ctx_block_outer {
1689 my ($linenr, $remain) = @_;
1691 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1695 my ($linenr, $remain) = @_;
1697 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1701 my ($linenr, $remain, $off) = @_;
1703 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1706 sub ctx_block_level {
1707 my ($linenr, $remain) = @_;
1709 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1711 sub ctx_statement_level {
1712 my ($linenr, $remain, $off) = @_;
1714 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1717 sub ctx_locate_comment {
1718 my ($first_line, $end_line) = @_;
1720 # If c99 comment on the current line, or the line before or after
1721 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1722 return $current_comment if (defined $current_comment);
1723 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1724 return $current_comment if (defined $current_comment);
1725 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1726 return $current_comment if (defined $current_comment);
1728 # Catch a comment on the end of the line itself.
1729 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1730 return $current_comment if (defined $current_comment);
1732 # Look through the context and try and figure out if there is a
1735 $current_comment = '';
1736 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1737 my $line = $rawlines[$linenr - 1];
1739 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1742 if ($line =~ m@/\*@) {
1745 if (!$in_comment && $current_comment ne '') {
1746 $current_comment = '';
1748 $current_comment .= $line . "\n" if ($in_comment);
1749 if ($line =~ m@\*/@) {
1754 chomp($current_comment);
1755 return($current_comment);
1757 sub ctx_has_comment {
1758 my ($first_line, $end_line) = @_;
1759 my $cmt = ctx_locate_comment($first_line, $end_line);
1761 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1762 ##print "CMMT: $cmt\n";
1764 return ($cmt ne '');
1768 my ($linenr, $cnt) = @_;
1770 my $offset = $linenr - 1;
1775 $line = $rawlines[$offset++];
1776 next if (defined($line) && $line =~ /^-/);
1784 my ($linenr, $lc) = @_;
1786 my $stat_real = raw_line($linenr, 0);
1787 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1788 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1795 my ($linenr, $cnt, $here) = @_;
1797 my $herectx = $here . "\n";
1798 for (my $n = 0; $n < $cnt; $n++) {
1799 $herectx .= raw_line($linenr, $n) . "\n";
1810 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1813 $coded = sprintf("^%c", unpack('C', $2) + 64);
1822 my $av_preprocessor = 0;
1827 sub annotate_reset {
1828 $av_preprocessor = 0;
1830 @av_paren_type = ('E');
1831 $av_pend_colon = 'O';
1834 sub annotate_values {
1835 my ($stream, $type) = @_;
1838 my $var = '_' x length($stream);
1841 print "$stream\n" if ($dbg_values > 1);
1843 while (length($cur)) {
1844 @av_paren_type = ('E') if ($#av_paren_type < 0);
1845 print " <" . join('', @av_paren_type) .
1846 "> <$type> <$av_pending>" if ($dbg_values > 1);
1847 if ($cur =~ /^(\s+)/o) {
1848 print "WS($1)\n" if ($dbg_values > 1);
1849 if ($1 =~ /\n/ && $av_preprocessor) {
1850 $type = pop(@av_paren_type);
1851 $av_preprocessor = 0;
1854 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1855 print "CAST($1)\n" if ($dbg_values > 1);
1856 push(@av_paren_type, $type);
1859 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1860 print "DECLARE($1)\n" if ($dbg_values > 1);
1863 } elsif ($cur =~ /^($Modifier)\s*/) {
1864 print "MODIFIER($1)\n" if ($dbg_values > 1);
1867 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1868 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1869 $av_preprocessor = 1;
1870 push(@av_paren_type, $type);
1876 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1877 print "UNDEF($1)\n" if ($dbg_values > 1);
1878 $av_preprocessor = 1;
1879 push(@av_paren_type, $type);
1881 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1882 print "PRE_START($1)\n" if ($dbg_values > 1);
1883 $av_preprocessor = 1;
1885 push(@av_paren_type, $type);
1886 push(@av_paren_type, $type);
1889 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1890 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1891 $av_preprocessor = 1;
1893 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1897 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1898 print "PRE_END($1)\n" if ($dbg_values > 1);
1900 $av_preprocessor = 1;
1902 # Assume all arms of the conditional end as this
1903 # one does, and continue as if the #endif was not here.
1904 pop(@av_paren_type);
1905 push(@av_paren_type, $type);
1908 } elsif ($cur =~ /^(\\\n)/o) {
1909 print "PRECONT($1)\n" if ($dbg_values > 1);
1911 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1912 print "ATTR($1)\n" if ($dbg_values > 1);
1913 $av_pending = $type;
1916 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1917 print "SIZEOF($1)\n" if ($dbg_values > 1);
1923 } elsif ($cur =~ /^(if|while|for)\b/o) {
1924 print "COND($1)\n" if ($dbg_values > 1);
1928 } elsif ($cur =~/^(case)/o) {
1929 print "CASE($1)\n" if ($dbg_values > 1);
1930 $av_pend_colon = 'C';
1933 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1934 print "KEYWORD($1)\n" if ($dbg_values > 1);
1937 } elsif ($cur =~ /^(\()/o) {
1938 print "PAREN('$1')\n" if ($dbg_values > 1);
1939 push(@av_paren_type, $av_pending);
1943 } elsif ($cur =~ /^(\))/o) {
1944 my $new_type = pop(@av_paren_type);
1945 if ($new_type ne '_') {
1947 print "PAREN('$1') -> $type\n"
1948 if ($dbg_values > 1);
1950 print "PAREN('$1')\n" if ($dbg_values > 1);
1953 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1954 print "FUNC($1)\n" if ($dbg_values > 1);
1958 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1959 if (defined $2 && $type eq 'C' || $type eq 'T') {
1960 $av_pend_colon = 'B';
1961 } elsif ($type eq 'E') {
1962 $av_pend_colon = 'L';
1964 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1967 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1968 print "IDENT($1)\n" if ($dbg_values > 1);
1971 } elsif ($cur =~ /^($Assignment)/o) {
1972 print "ASSIGN($1)\n" if ($dbg_values > 1);
1975 } elsif ($cur =~/^(;|{|})/) {
1976 print "END($1)\n" if ($dbg_values > 1);
1978 $av_pend_colon = 'O';
1980 } elsif ($cur =~/^(,)/) {
1981 print "COMMA($1)\n" if ($dbg_values > 1);
1984 } elsif ($cur =~ /^(\?)/o) {
1985 print "QUESTION($1)\n" if ($dbg_values > 1);
1988 } elsif ($cur =~ /^(:)/o) {
1989 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1991 substr($var, length($res), 1, $av_pend_colon);
1992 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1997 $av_pend_colon = 'O';
1999 } elsif ($cur =~ /^(\[)/o) {
2000 print "CLOSE($1)\n" if ($dbg_values > 1);
2003 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2006 print "OPV($1)\n" if ($dbg_values > 1);
2013 substr($var, length($res), 1, $variant);
2016 } elsif ($cur =~ /^($Operators)/o) {
2017 print "OP($1)\n" if ($dbg_values > 1);
2018 if ($1 ne '++' && $1 ne '--') {
2022 } elsif ($cur =~ /(^.)/o) {
2023 print "C($1)\n" if ($dbg_values > 1);
2026 $cur = substr($cur, length($1));
2027 $res .= $type x length($1);
2031 return ($res, $var);
2035 my ($possible, $line) = @_;
2036 my $notPermitted = qr{(?:
2053 ^(?:typedef|struct|enum)\b
2055 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2056 if ($possible !~ $notPermitted) {
2057 # Check for modifiers.
2058 $possible =~ s/\s*$Storage\s*//g;
2059 $possible =~ s/\s*$Sparse\s*//g;
2060 if ($possible =~ /^\s*$/) {
2062 } elsif ($possible =~ /\s/) {
2063 $possible =~ s/\s*$Type\s*//g;
2064 for my $modifier (split(' ', $possible)) {
2065 if ($modifier !~ $notPermitted) {
2066 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2067 push(@modifierListFile, $modifier);
2072 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2073 push(@typeListFile, $possible);
2077 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2086 $type =~ tr/[a-z]/[A-Z]/;
2088 return defined $use_type{$type} if (scalar keys %use_type > 0);
2090 return !defined $ignore_type{$type};
2094 my ($level, $type, $msg) = @_;
2096 if (!show_type($type) ||
2097 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2102 if ($level eq 'ERROR') {
2104 } elsif ($level eq 'WARNING') {
2110 $output .= $prefix . $level . ':';
2112 $output .= BLUE if ($color);
2113 $output .= "$type:";
2115 $output .= RESET if ($color);
2116 $output .= ' ' . $msg . "\n";
2119 my @lines = split("\n", $output, -1);
2120 splice(@lines, 1, 1);
2121 $output = join("\n", @lines);
2123 $output = (split('\n', $output))[0] . "\n" if ($terse);
2125 push(our @report, $output);
2134 sub fixup_current_range {
2135 my ($lineRef, $offset, $length) = @_;
2137 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2140 my $no = $o + $offset;
2141 my $nl = $l + $length;
2142 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2146 sub fix_inserted_deleted_lines {
2147 my ($linesRef, $insertedRef, $deletedRef) = @_;
2149 my $range_last_linenr = 0;
2150 my $delta_offset = 0;
2155 my $next_insert = 0;
2156 my $next_delete = 0;
2160 my $inserted = @{$insertedRef}[$next_insert++];
2161 my $deleted = @{$deletedRef}[$next_delete++];
2163 foreach my $old_line (@{$linesRef}) {
2165 my $line = $old_line; #don't modify the array
2166 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2168 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2169 $range_last_linenr = $new_linenr;
2170 fixup_current_range(\$line, $delta_offset, 0);
2173 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2174 $deleted = @{$deletedRef}[$next_delete++];
2176 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2179 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2180 push(@lines, ${$inserted}{'LINE'});
2181 $inserted = @{$insertedRef}[$next_insert++];
2183 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2187 push(@lines, $line);
2197 sub fix_insert_line {
2198 my ($linenr, $line) = @_;
2204 push(@fixed_inserted, $inserted);
2207 sub fix_delete_line {
2208 my ($linenr, $line) = @_;
2215 push(@fixed_deleted, $deleted);
2219 my ($type, $msg) = @_;
2221 if (report("ERROR", $type, $msg)) {
2229 my ($type, $msg) = @_;
2231 if (report("WARNING", $type, $msg)) {
2239 my ($type, $msg) = @_;
2241 if ($check && report("CHECK", $type, $msg)) {
2249 sub check_absolute_file {
2250 my ($absolute, $herecurr) = @_;
2251 my $file = $absolute;
2253 ##print "absolute<$absolute>\n";
2255 # See if any suffix of this path is a path within the tree.
2256 while ($file =~ s@^[^/]*/@@) {
2257 if (-f "$root/$file") {
2258 ##print "file<$file>\n";
2266 # It is, so see if the prefix is acceptable.
2267 my $prefix = $absolute;
2268 substr($prefix, -length($file)) = '';
2270 ##print "prefix<$prefix>\n";
2271 if ($prefix ne ".../") {
2272 WARN("USE_RELATIVE_PATH",
2273 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2280 $string =~ s/^\s+|\s+$//g;
2288 $string =~ s/^\s+//;
2296 $string =~ s/\s+$//;
2301 sub string_find_replace {
2302 my ($string, $find, $replace) = @_;
2304 $string =~ s/$find/$replace/g;
2312 my $source_indent = $tabsize;
2313 my $max_spaces_before_tab = $source_indent - 1;
2314 my $spaces_to_tab = " " x $source_indent;
2316 #convert leading spaces to tabs
2317 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2318 #Remove spaces before a tab
2319 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2324 sub pos_last_openparen {
2329 my $opens = $line =~ tr/\(/\(/;
2330 my $closes = $line =~ tr/\)/\)/;
2332 my $last_openparen = 0;
2334 if (($opens == 0) || ($closes >= $opens)) {
2338 my $len = length($line);
2340 for ($pos = 0; $pos < $len; $pos++) {
2341 my $string = substr($line, $pos);
2342 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2343 $pos += length($1) - 1;
2344 } elsif (substr($line, $pos, 1) eq '(') {
2345 $last_openparen = $pos;
2346 } elsif (index($string, '(') == -1) {
2351 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2354 sub get_raw_comment {
2355 my ($line, $rawline) = @_;
2358 for my $i (0 .. (length($line) - 1)) {
2359 if (substr($line, $i, 1) eq "$;") {
2360 $comment .= substr($rawline, $i, 1);
2368 my $filename = shift;
2374 my $stashrawline="";
2384 my $authorsignoff = 0;
2385 my $author_sob = '';
2387 my $is_binding_patch = -1;
2388 my $in_header_lines = $file ? 0 : 1;
2389 my $in_commit_log = 0; #Scanning lines before patch
2390 my $has_patch_separator = 0; #Found a --- line
2391 my $has_commit_log = 0; #Encountered lines before patch
2392 my $commit_log_lines = 0; #Number of commit log lines
2393 my $commit_log_possible_stack_dump = 0;
2394 my $commit_log_long_line = 0;
2395 my $commit_log_has_diff = 0;
2396 my $reported_maintainer_file = 0;
2397 my $non_utf8_charset = 0;
2399 my $last_blank_line = 0;
2400 my $last_coalesced_string_linenr = -1;
2408 # Trace the real file/line as we go.
2413 my $context_function; #undef'd unless there's a known function
2415 my $comment_edge = 0;
2419 my $prev_values = 'E';
2422 my %suppress_ifbraces;
2423 my %suppress_whiletrailers;
2424 my %suppress_export;
2425 my $suppress_statement = 0;
2427 my %signatures = ();
2429 # Pre-scan the patch sanitizing the lines.
2430 # Pre-scan the patch looking for any __setup documentation.
2432 my @setup_docs = ();
2435 my $camelcase_file_seeded = 0;
2437 my $checklicenseline = 1;
2439 sanitise_line_reset();
2441 foreach my $rawline (@rawlines) {
2445 push(@fixed, $rawline) if ($fix);
2447 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2449 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2454 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2463 # Guestimate if this is a continuing comment. Run
2464 # the context looking for a comment "edge". If this
2465 # edge is a close comment then we must be in a comment
2469 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2470 next if (defined $rawlines[$ln - 1] &&
2471 $rawlines[$ln - 1] =~ /^-/);
2473 #print "RAW<$rawlines[$ln - 1]>\n";
2474 last if (!defined $rawlines[$ln - 1]);
2475 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2476 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2481 if (defined $edge && $edge eq '*/') {
2485 # Guestimate if this is a continuing comment. If this
2486 # is the start of a diff block and this line starts
2487 # ' *' then it is very likely a comment.
2488 if (!defined $edge &&
2489 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2494 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2495 sanitise_line_reset($in_comment);
2497 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2498 # Standardise the strings and chars within the input to
2499 # simplify matching -- only bother with positive lines.
2500 $line = sanitise_line($rawline);
2502 push(@lines, $line);
2505 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2510 #print "==>$rawline\n";
2511 #print "-->$line\n";
2513 if ($setup_docs && $line =~ /^\+/) {
2514 push(@setup_docs, $line);
2523 foreach my $line (@lines) {
2526 my $sline = $line; #copy of $line
2527 $sline =~ s/$;/ /g; #with comments as spaces
2529 my $rawline = $rawlines[$linenr - 1];
2530 my $raw_comment = get_raw_comment($line, $rawline);
2532 # check if it's a mode change, rename or start of a patch
2533 if (!$in_commit_log &&
2534 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2535 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2536 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2540 #extract the line range in the file after the patch is applied
2541 if (!$in_commit_log &&
2542 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2545 $first_line = $linenr + 1;
2555 %suppress_ifbraces = ();
2556 %suppress_whiletrailers = ();
2557 %suppress_export = ();
2558 $suppress_statement = 0;
2559 if ($context =~ /\b(\w+)\s*\(/) {
2560 $context_function = $1;
2562 undef $context_function;
2566 # track the line number as we move through the hunk, note that
2567 # new versions of GNU diff omit the leading space on completely
2568 # blank context lines so we need to count that too.
2569 } elsif ($line =~ /^( |\+|$)/) {
2571 $realcnt-- if ($realcnt != 0);
2573 # Measure the line length and indent.
2574 ($length, $indent) = line_stats($rawline);
2576 # Track the previous line.
2577 ($prevline, $stashline) = ($stashline, $line);
2578 ($previndent, $stashindent) = ($stashindent, $indent);
2579 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2581 #warn "line<$line>\n";
2583 } elsif ($realcnt == 1) {
2587 my $hunk_line = ($realcnt != 0);
2589 $here = "#$linenr: " if (!$file);
2590 $here = "#$realline: " if ($file);
2593 # extract the filename as it passes
2594 if ($line =~ /^diff --git.*?(\S+)$/) {
2596 $realfile =~ s@^([^/]*)/@@ if (!$file);
2599 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2601 $realfile =~ s@^([^/]*)/@@ if (!$file);
2605 if (!$file && $tree && $p1_prefix ne '' &&
2606 -e "$root/$p1_prefix") {
2607 WARN("PATCH_PREFIX",
2608 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2611 if ($realfile =~ m@^include/asm/@) {
2612 ERROR("MODIFIED_INCLUDE_ASM",
2613 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2618 #make up the handle for any error we report on this line
2620 $prefix = "$realfile:$realline: "
2623 $prefix = "$filename:$realline: ";
2625 $prefix = "$filename:$linenr: ";
2630 if (is_maintained_obsolete($realfile)) {
2632 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2634 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2637 $check = $check_orig;
2639 $checklicenseline = 1;
2641 if ($realfile !~ /^MAINTAINERS/) {
2642 my $last_binding_patch = $is_binding_patch;
2644 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2646 if (($last_binding_patch != -1) &&
2647 ($last_binding_patch ^ $is_binding_patch)) {
2648 WARN("DT_SPLIT_BINDING_PATCH",
2649 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2656 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2658 my $hereline = "$here\n$rawline\n";
2659 my $herecurr = "$here\n$rawline\n";
2660 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2662 $cnt_lines++ if ($realcnt != 0);
2664 # Verify the existence of a commit log if appropriate
2665 # 2 is used because a $signature is counted in $commit_log_lines
2666 if ($in_commit_log) {
2667 if ($line !~ /^\s*$/) {
2668 $commit_log_lines++; #could be a $signature
2670 } elsif ($has_commit_log && $commit_log_lines < 2) {
2671 WARN("COMMIT_MESSAGE",
2672 "Missing commit description - Add an appropriate one\n");
2673 $commit_log_lines = 2; #warn only once
2676 # Check if the commit log has what seems like a diff which can confuse patch
2677 if ($in_commit_log && !$commit_log_has_diff &&
2678 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2679 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2680 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2681 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2682 ERROR("DIFF_IN_COMMIT_MSG",
2683 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2684 $commit_log_has_diff = 1;
2687 # Check for incorrect file permissions
2688 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2689 my $permhere = $here . "FILE: $realfile\n";
2690 if ($realfile !~ m@scripts/@ &&
2691 $realfile !~ /\.(py|pl|awk|sh)$/) {
2692 ERROR("EXECUTE_PERMISSIONS",
2693 "do not set execute permissions for source files\n" . $permhere);
2697 # Check the patch for a From:
2698 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2700 my $curline = $linenr;
2701 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2704 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2706 $author = reformat_email($author);
2709 # Check the patch for a signoff:
2710 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2713 if ($author ne '' && $authorsignoff != 1) {
2714 if (same_email_addresses($1, $author, 1)) {
2718 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2719 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2721 if ($email_address eq $author_address && $email_name eq $author_name) {
2724 } elsif ($email_address eq $author_address) {
2727 } elsif ($email_name eq $author_name) {
2731 my $address1 = $email_address;
2732 my $address2 = $author_address;
2734 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2737 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2740 if ($address1 eq $address2) {
2748 # Check for patch separator
2749 if ($line =~ /^---$/) {
2750 $has_patch_separator = 1;
2754 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2755 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2756 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2757 $reported_maintainer_file = 1;
2760 # Check signature styles
2761 if (!$in_header_lines &&
2762 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2763 my $space_before = $1;
2765 my $space_after = $3;
2767 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2769 if ($sign_off !~ /$signature_tags/) {
2770 WARN("BAD_SIGN_OFF",
2771 "Non-standard signature: $sign_off\n" . $herecurr);
2773 if (defined $space_before && $space_before ne "") {
2774 if (WARN("BAD_SIGN_OFF",
2775 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2777 $fixed[$fixlinenr] =
2778 "$ucfirst_sign_off $email";
2781 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2782 if (WARN("BAD_SIGN_OFF",
2783 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2785 $fixed[$fixlinenr] =
2786 "$ucfirst_sign_off $email";
2790 if (!defined $space_after || $space_after ne " ") {
2791 if (WARN("BAD_SIGN_OFF",
2792 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2794 $fixed[$fixlinenr] =
2795 "$ucfirst_sign_off $email";
2799 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2800 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
2801 if ($suggested_email eq "") {
2802 ERROR("BAD_SIGN_OFF",
2803 "Unrecognized email address: '$email'\n" . $herecurr);
2805 my $dequoted = $suggested_email;
2806 $dequoted =~ s/^"//;
2807 $dequoted =~ s/" </ </;
2808 # Don't force email to have quotes
2809 # Allow just an angle bracketed address
2810 if (!same_email_addresses($email, $suggested_email, 0)) {
2811 WARN("BAD_SIGN_OFF",
2812 "email address '$email' might be better as '$suggested_email'\n" . $herecurr);
2816 # Check for duplicate signatures
2817 my $sig_nospace = $line;
2818 $sig_nospace =~ s/\s//g;
2819 $sig_nospace = lc($sig_nospace);
2820 if (defined $signatures{$sig_nospace}) {
2821 WARN("BAD_SIGN_OFF",
2822 "Duplicate signature\n" . $herecurr);
2824 $signatures{$sig_nospace} = 1;
2827 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2828 if ($sign_off =~ /^co-developed-by:$/i) {
2829 if ($email eq $author) {
2830 WARN("BAD_SIGN_OFF",
2831 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2833 if (!defined $lines[$linenr]) {
2834 WARN("BAD_SIGN_OFF",
2835 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2836 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2837 WARN("BAD_SIGN_OFF",
2838 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2839 } elsif ($1 ne $email) {
2840 WARN("BAD_SIGN_OFF",
2841 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2846 # Check email subject for common tools that don't need to be mentioned
2847 if ($in_header_lines &&
2848 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2849 WARN("EMAIL_SUBJECT",
2850 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2853 # Check for Gerrit Change-Ids not in any patch context
2854 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2855 ERROR("GERRIT_CHANGE_ID",
2856 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr);
2859 # Check if the commit log is in a possible stack dump
2860 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2861 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2862 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2864 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2865 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2866 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2867 # stack dump address styles
2868 $commit_log_possible_stack_dump = 1;
2871 # Check for line lengths > 75 in commit log, warn once
2872 if ($in_commit_log && !$commit_log_long_line &&
2873 length($line) > 75 &&
2874 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2875 # file delta changes
2876 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2878 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2879 # A Fixes: or Link: line
2880 $commit_log_possible_stack_dump)) {
2881 WARN("COMMIT_LOG_LONG_LINE",
2882 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2883 $commit_log_long_line = 1;
2886 # Reset possible stack dump if a blank line is found
2887 if ($in_commit_log && $commit_log_possible_stack_dump &&
2889 $commit_log_possible_stack_dump = 0;
2892 # Check for git id commit length and improperly formed commit descriptions
2893 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2894 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
2895 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2896 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2897 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2898 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2899 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2900 my $init_char = "c";
2901 my $orig_commit = "";
2908 my $id = '0123456789ab';
2909 my $orig_desc = "commit description";
2910 my $description = "";
2912 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2914 $orig_commit = lc($2);
2915 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2916 $orig_commit = lc($1);
2919 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2920 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2921 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2922 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2923 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2926 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2927 defined $rawlines[$linenr] &&
2928 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2931 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2932 defined $rawlines[$linenr] &&
2933 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2934 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2936 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2937 $orig_desc .= " " . $1;
2941 ($id, $description) = git_commit_info($orig_commit,
2945 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2946 ERROR("GIT_COMMIT_ID",
2947 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2951 # Check for added, moved or deleted files
2952 if (!$reported_maintainer_file && !$in_commit_log &&
2953 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2954 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2955 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2956 (defined($1) || defined($2))))) {
2958 $reported_maintainer_file = 1;
2959 WARN("FILE_PATH_CHANGES",
2960 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2963 # Check for adding new DT bindings not in schema format
2964 if (!$in_commit_log &&
2965 ($line =~ /^new file mode\s*\d+\s*$/) &&
2966 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
2967 WARN("DT_SCHEMA_BINDING_PATCH",
2968 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
2971 # Check for wrappage within a valid hunk of the file
2972 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2973 ERROR("CORRUPTED_PATCH",
2974 "patch seems to be corrupt (line wrapped?)\n" .
2975 $herecurr) if (!$emitted_corrupt++);
2978 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2979 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2980 $rawline !~ m/^$UTF8*$/) {
2981 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2983 my $blank = copy_spacing($rawline);
2984 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2985 my $hereptr = "$hereline$ptr\n";
2988 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2991 # Check if it's the start of a commit log
2992 # (not a header line and we haven't seen the patch filename)
2993 if ($in_header_lines && $realfile =~ /^$/ &&
2994 !($rawline =~ /^\s+(?:\S|$)/ ||
2995 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2996 $in_header_lines = 0;
2998 $has_commit_log = 1;
3001 # Check if there is UTF-8 in a commit log when a mail header has explicitly
3002 # declined it, i.e defined some charset where it is missing.
3003 if ($in_header_lines &&
3004 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3006 $non_utf8_charset = 1;
3009 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3010 $rawline =~ /$NON_ASCII_UTF8/) {
3011 WARN("UTF8_BEFORE_PATCH",
3012 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3015 # Check for absolute kernel paths in commit message
3016 if ($tree && $in_commit_log) {
3017 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3020 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3021 check_absolute_file($1, $herecurr)) {
3024 check_absolute_file($file, $herecurr);
3029 # Check for various typo / spelling mistakes
3030 if (defined($misspellings) &&
3031 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3032 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
3034 my $typo_fix = $spelling_fix{lc($typo)};
3035 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3036 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3037 my $msg_level = \&WARN;
3038 $msg_level = \&CHK if ($file);
3039 if (&{$msg_level}("TYPO_SPELLING",
3040 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
3042 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3047 # check for invalid commit id
3048 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3051 ($id, $description) = git_commit_info($2, undef, undef);
3052 if (!defined($id)) {
3053 WARN("UNKNOWN_COMMIT_ID",
3054 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3058 # check for repeated words separated by a single space
3059 # avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3060 if (($rawline =~ /^\+/ || $in_commit_log) &&
3061 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3062 pos($rawline) = 1 if (!$in_commit_log);
3063 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3067 my $start_pos = $-[1];
3068 my $end_pos = $+[2];
3069 if ($first =~ /(?:struct|union|enum)/) {
3070 pos($rawline) += length($first) + length($second) + 1;
3074 next if (lc($first) ne lc($second));
3075 next if ($first eq 'long');
3077 # check for character before and after the word matches
3078 my $start_char = '';
3080 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3081 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3083 next if ($start_char =~ /^\S$/);
3084 next if (index(" \t.,;?!", $end_char) == -1);
3086 # avoid repeating hex occurrences like 'ff ff fe 09 ...'
3087 if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3088 next if (!exists($allow_repeated_words{lc($first)}));
3091 if (WARN("REPEATED_WORD",
3092 "Possible repeated word: '$first'\n" . $herecurr) &&
3094 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3098 # if it's a repeated word on consecutive lines in a comment block
3099 if ($prevline =~ /$;+\s*$/ &&
3100 $prevrawline =~ /($word_pattern)\s*$/) {
3102 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3103 if (WARN("REPEATED_WORD",
3104 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3106 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3112 # ignore non-hunk lines and lines being removed
3113 next if (!$hunk_line || $line =~ /^-/);
3115 #trailing whitespace
3116 if ($line =~ /^\+.*\015/) {
3117 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3118 if (ERROR("DOS_LINE_ENDINGS",
3119 "DOS line endings\n" . $herevet) &&
3121 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3123 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3124 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3125 if (ERROR("TRAILING_WHITESPACE",
3126 "trailing whitespace\n" . $herevet) &&
3128 $fixed[$fixlinenr] =~ s/\s+$//;
3134 # Check for FSF mailing addresses.
3135 if ($rawline =~ /\bwrite to the Free/i ||
3136 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3137 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3138 $rawline =~ /\b51\s+Franklin\s+St/i) {
3139 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3140 my $msg_level = \&ERROR;
3141 $msg_level = \&CHK if ($file);
3142 &{$msg_level}("FSF_MAILING_ADDRESS",
3143 "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)
3146 # check for Kconfig help text having a real description
3147 # Only applies when adding the entry originally, after that we do not have
3148 # sufficient context to determine whether it is indeed long enough.
3149 if ($realfile =~ /Kconfig/ &&
3150 # 'choice' is usually the last thing on the line (though
3151 # Kconfig supports named choices), so use a word boundary
3152 # (\b) rather than a whitespace character (\s)
3153 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3156 my $ln = $linenr + 1;
3160 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3161 $f = $lines[$ln - 1];
3162 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3163 $is_end = $lines[$ln - 1] =~ /^\+/;
3165 next if ($f =~ /^-/);
3166 last if (!$file && $f =~ /^\@\@/);
3168 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3170 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3177 next if ($f =~ /^$/);
3179 # This only checks context lines in the patch
3180 # and so hopefully shouldn't trigger false
3181 # positives, even though some of these are
3182 # common words in help texts
3183 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3184 if|endif|menu|endmenu|source)\b/x) {
3190 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3191 WARN("CONFIG_DESCRIPTION",
3192 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3194 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3197 # check MAINTAINERS entries
3198 if ($realfile =~ /^MAINTAINERS$/) {
3199 # check MAINTAINERS entries for the right form
3200 if ($rawline =~ /^\+[A-Z]:/ &&
3201 $rawline !~ /^\+[A-Z]:\t\S/) {
3202 if (WARN("MAINTAINERS_STYLE",
3203 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3205 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3208 # check MAINTAINERS entries for the right ordering too
3209 my $preferred_order = 'MRLSWQBCPTFXNK';
3210 if ($rawline =~ /^\+[A-Z]:/ &&
3211 $prevrawline =~ /^[\+ ][A-Z]:/) {
3212 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3215 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3218 my $curindex = index($preferred_order, $cur);
3219 my $previndex = index($preferred_order, $prev);
3220 if ($curindex < 0) {
3221 WARN("MAINTAINERS_STYLE",
3222 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3224 if ($previndex >= 0 && $curindex < $previndex) {
3225 WARN("MAINTAINERS_STYLE",
3226 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3227 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3228 ($prev eq 'X' && $cur eq 'X')) &&
3229 ($prevval cmp $curval) > 0) {
3230 WARN("MAINTAINERS_STYLE",
3231 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3237 # discourage the use of boolean for type definition attributes of Kconfig options
3238 if ($realfile =~ /Kconfig/ &&
3239 $line =~ /^\+\s*\bboolean\b/) {
3240 WARN("CONFIG_TYPE_BOOLEAN",
3241 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3244 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3245 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3248 'EXTRA_AFLAGS' => 'asflags-y',
3249 'EXTRA_CFLAGS' => 'ccflags-y',
3250 'EXTRA_CPPFLAGS' => 'cppflags-y',
3251 'EXTRA_LDFLAGS' => 'ldflags-y',
3254 WARN("DEPRECATED_VARIABLE",
3255 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3258 # check for DT compatible documentation
3259 if (defined $root &&
3260 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3261 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3263 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3265 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3266 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3268 foreach my $compat (@compats) {
3269 my $compat2 = $compat;
3270 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3271 my $compat3 = $compat;
3272 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3273 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3275 WARN("UNDOCUMENTED_DT_STRING",
3276 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3279 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3281 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3283 WARN("UNDOCUMENTED_DT_STRING",
3284 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3289 # check for using SPDX license tag at beginning of files
3290 if ($realline == $checklicenseline) {
3291 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3292 $checklicenseline = 2;
3293 } elsif ($rawline =~ /^\+/) {
3295 if ($realfile =~ /\.(h|s|S)$/) {
3297 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3299 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3301 } elsif ($realfile =~ /\.rst$/) {
3305 # check SPDX comment style for .[chsS] files
3306 if ($realfile =~ /\.[chsS]$/ &&
3307 $rawline =~ /SPDX-License-Identifier:/ &&
3308 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3309 WARN("SPDX_LICENSE_TAG",
3310 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3313 if ($comment !~ /^$/ &&
3314 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3315 WARN("SPDX_LICENSE_TAG",
3316 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3317 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3318 my $spdx_license = $1;
3319 if (!is_SPDX_License_valid($spdx_license)) {
3320 WARN("SPDX_LICENSE_TAG",
3321 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3323 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3324 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3325 my $msg_level = \&WARN;
3326 $msg_level = \&CHK if ($file);
3327 if (&{$msg_level}("SPDX_LICENSE_TAG",
3329 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3331 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3338 # check for embedded filenames
3339 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3340 WARN("EMBEDDED_FILENAME",
3341 "It's generally not useful to have the filename in the file\n" . $herecurr);
3344 # check we are in a valid source file if not then ignore this hunk
3345 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3347 # check for using SPDX-License-Identifier on the wrong line number
3348 if ($realline != $checklicenseline &&
3349 $rawline =~ /\bSPDX-License-Identifier:/ &&
3350 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3351 WARN("SPDX_LICENSE_TAG",
3352 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3355 # line length limit (with some exclusions)
3357 # There are a few types of lines that may extend beyond $max_line_length:
3358 # logging functions like pr_info that end in a string
3359 # lines with a single string
3360 # #defines that are a single string
3361 # lines with an RFC3986 like URL
3363 # There are 3 different line length message types:
3364 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3365 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3366 # LONG_LINE all other lines longer than $max_line_length
3368 # if LONG_LINE is ignored, the other 2 types are also ignored
3371 if ($line =~ /^\+/ && $length > $max_line_length) {
3372 my $msg_type = "LONG_LINE";
3374 # Check the allowed long line types first
3376 # logging functions that end in a string that starts
3377 # before $max_line_length
3378 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3379 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3382 # lines with only strings (w/ possible termination)
3383 # #defines with only strings
3384 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3385 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3388 # More special cases
3389 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3390 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3393 # URL ($rawline is used in case the URL is in a comment)
3394 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3397 # Otherwise set the alternate message types
3399 # a comment starts before $max_line_length
3400 } elsif ($line =~ /($;[\s$;]*)$/ &&
3401 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3402 $msg_type = "LONG_LINE_COMMENT"
3404 # a quoted string starts before $max_line_length
3405 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3406 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3407 $msg_type = "LONG_LINE_STRING"
3410 if ($msg_type ne "" &&
3411 (show_type("LONG_LINE") || show_type($msg_type))) {
3412 my $msg_level = \&WARN;
3413 $msg_level = \&CHK if ($file);
3414 &{$msg_level}($msg_type,
3415 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3419 # check for adding lines without a newline.
3420 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3421 if (WARN("MISSING_EOF_NEWLINE",
3422 "adding a line without newline at end of file\n" . $herecurr) &&
3424 fix_delete_line($fixlinenr+1, "No newline at end of file");
3428 # check we are in a valid source file C or perl if not then ignore this hunk
3429 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3431 # at the beginning of a line any tabs must come first and anything
3432 # more than $tabsize must use tabs.
3433 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3434 $rawline =~ /^\+\s* \s*/) {
3435 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3437 if (ERROR("CODE_INDENT",
3438 "code indent should use tabs where possible\n" . $herevet) &&
3440 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3444 # check for space before tabs.
3445 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3446 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3447 if (WARN("SPACE_BEFORE_TAB",
3448 "please, no space before tabs\n" . $herevet) &&
3450 while ($fixed[$fixlinenr] =~
3451 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3452 while ($fixed[$fixlinenr] =~
3453 s/(^\+.*) +\t/$1\t/) {}
3457 # check for assignments on the start of a line
3458 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3459 CHK("ASSIGNMENT_CONTINUATIONS",
3460 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3463 # check for && or || at the start of a line
3464 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3465 CHK("LOGICAL_CONTINUATIONS",
3466 "Logical continuations should be on the previous line\n" . $hereprev);
3469 # check indentation starts on a tab stop
3470 if ($perl_version_ok &&
3471 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3472 my $indent = length($1);
3473 if ($indent % $tabsize) {
3475 "Statements should start on a tabstop\n" . $herecurr) &&
3477 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3482 # check multi-line statement indentation matches previous line
3483 if ($perl_version_ok &&
3484 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3485 $prevline =~ /^\+(\t*)(.*)$/;
3489 my $pos = pos_last_openparen($rest);
3491 $line =~ /^(\+| )([ \t]*)/;
3494 my $goodtabindent = $oldindent .
3495 "\t" x ($pos / $tabsize) .
3496 " " x ($pos % $tabsize);
3497 my $goodspaceindent = $oldindent . " " x $pos;
3499 if ($newindent ne $goodtabindent &&
3500 $newindent ne $goodspaceindent) {
3502 if (CHK("PARENTHESIS_ALIGNMENT",
3503 "Alignment should match open parenthesis\n" . $hereprev) &&
3504 $fix && $line =~ /^\+/) {
3505 $fixed[$fixlinenr] =~
3506 s/^\+[ \t]*/\+$goodtabindent/;
3512 # check for space after cast like "(int) foo" or "(struct foo) bar"
3513 # avoid checking a few false positives:
3514 # "sizeof(<type>)" or "__alignof__(<type>)"
3515 # function pointer declarations like "(*foo)(int) = bar;"
3516 # structure definitions like "(struct foo) { 0 };"
3517 # multiline macros that define functions
3518 # known attributes or the __attribute__ keyword
3519 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3520 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3522 "No space is necessary after a cast\n" . $herecurr) &&
3524 $fixed[$fixlinenr] =~
3525 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3529 # Block comment styles
3530 # Networking with an initial /*
3531 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3532 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3533 $rawline =~ /^\+[ \t]*\*/ &&
3534 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3535 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3536 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3539 # Block comments use * on subsequent lines
3540 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3541 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3542 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3543 $rawline =~ /^\+/ && #line is new
3544 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3545 WARN("BLOCK_COMMENT_STYLE",
3546 "Block comments use * on subsequent lines\n" . $hereprev);
3549 # Block comments use */ on trailing lines
3550 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3551 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3552 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3553 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3554 WARN("BLOCK_COMMENT_STYLE",
3555 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3558 # Block comment * alignment
3559 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3560 $line =~ /^\+[ \t]*$;/ && #leading comment
3561 $rawline =~ /^\+[ \t]*\*/ && #leading *
3562 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3563 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3564 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3566 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3568 $oldindent = expand_tabs($1);
3570 $prevrawline =~ m@^\+(.*/?)\*@;
3571 $oldindent = expand_tabs($1);
3573 $rawline =~ m@^\+([ \t]*)\*@;
3575 $newindent = expand_tabs($newindent);
3576 if (length($oldindent) ne length($newindent)) {
3577 WARN("BLOCK_COMMENT_STYLE",
3578 "Block comments should align the * on each line\n" . $hereprev);
3582 # check for missing blank lines after struct/union declarations
3583 # with exceptions for various attributes and macros
3584 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3586 !($line =~ /^\+\s*$/ ||
3587 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3588 $line =~ /^\+\s*MODULE_/i ||
3589 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3590 $line =~ /^\+[a-z_]*init/ ||
3591 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3592 $line =~ /^\+\s*DECLARE/ ||
3593 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3594 $line =~ /^\+\s*__setup/)) {
3595 if (CHK("LINE_SPACING",
3596 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3598 fix_insert_line($fixlinenr, "\+");
3602 # check for multiple consecutive blank lines
3603 if ($prevline =~ /^[\+ ]\s*$/ &&
3604 $line =~ /^\+\s*$/ &&
3605 $last_blank_line != ($linenr - 1)) {
3606 if (CHK("LINE_SPACING",
3607 "Please don't use multiple blank lines\n" . $hereprev) &&
3609 fix_delete_line($fixlinenr, $rawline);
3612 $last_blank_line = $linenr;
3615 # check for missing blank lines after declarations
3616 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3617 # actual declarations
3618 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3619 # function pointer declarations
3620 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3621 # foo bar; where foo is some local typedef or #define
3622 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3623 # known declaration macros
3624 $prevline =~ /^\+\s+$declaration_macros/) &&
3625 # for "else if" which can look like "$Ident $Ident"
3626 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3627 # other possible extensions of declaration lines
3628 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3629 # not starting a section or a macro "\" extended line
3630 $prevline =~ /(?:\{\s*|\\)$/) &&
3631 # looks like a declaration
3632 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3633 # function pointer declarations
3634 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3635 # foo bar; where foo is some local typedef or #define
3636 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3637 # known declaration macros
3638 $sline =~ /^\+\s+$declaration_macros/ ||
3639 # start of struct or union or enum
3640 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3641 # start or end of block or continuation of declaration
3642 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3643 # bitfield continuation
3644 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3645 # other possible extensions of declaration lines
3646 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3647 # indentation of previous and current line are the same
3648 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3649 if (WARN("LINE_SPACING",
3650 "Missing a blank line after declarations\n" . $hereprev) &&
3652 fix_insert_line($fixlinenr, "\+");
3656 # check for spaces at the beginning of a line.
3658 # 1) within comments
3659 # 2) indented preprocessor commands
3661 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3662 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3663 if (WARN("LEADING_SPACE",
3664 "please, no spaces at the start of a line\n" . $herevet) &&
3666 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3670 # check we are in a valid C source file if not then ignore this hunk
3671 next if ($realfile !~ /\.(h|c)$/);
3673 # check for unusual line ending [ or (
3674 if ($line =~ /^\+.*([\[\(])\s*$/) {
3675 CHK("OPEN_ENDED_LINE",
3676 "Lines should not end with a '$1'\n" . $herecurr);
3679 # check if this appears to be the start function declaration, save the name
3680 if ($sline =~ /^\+\{\s*$/ &&
3681 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3682 $context_function = $1;
3685 # check if this appears to be the end of function declaration
3686 if ($sline =~ /^\+\}\s*$/) {
3687 undef $context_function;
3690 # check indentation of any line with a bare else
3691 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3692 # if the previous line is a break or return and is indented 1 tab more...
3693 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3694 my $tabs = length($1) + 1;
3695 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3696 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3697 defined $lines[$linenr] &&
3698 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3699 WARN("UNNECESSARY_ELSE",
3700 "else is not generally useful after a break or return\n" . $hereprev);
3704 # check indentation of a line with a break;
3705 # if the previous line is a goto, return or break
3706 # and is indented the same # of tabs
3707 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3709 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
3710 if (WARN("UNNECESSARY_BREAK",
3711 "break is not useful after a $1\n" . $hereprev) &&
3713 fix_delete_line($fixlinenr, $rawline);
3718 # check for RCS/CVS revision markers
3719 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3721 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3724 # check for old HOTPLUG __dev<foo> section markings
3725 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3726 WARN("HOTPLUG_SECTION",
3727 "Using $1 is unnecessary\n" . $herecurr);
3730 # Check for potential 'bare' types
3731 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3733 #print "LINE<$line>\n";
3734 if ($linenr > $suppress_statement &&
3735 $realcnt && $sline =~ /.\s*\S/) {
3736 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3737 ctx_statement_block($linenr, $realcnt, 0);
3738 $stat =~ s/\n./\n /g;
3739 $cond =~ s/\n./\n /g;
3741 #print "linenr<$linenr> <$stat>\n";
3742 # If this statement has no statement boundaries within
3743 # it there is no point in retrying a statement scan
3744 # until we hit end of it.
3745 my $frag = $stat; $frag =~ s/;+\s*$//;
3746 if ($frag !~ /(?:{|;)/) {
3747 #print "skip<$line_nr_next>\n";
3748 $suppress_statement = $line_nr_next;
3751 # Find the real next line.
3752 $realline_next = $line_nr_next;
3753 if (defined $realline_next &&
3754 (!defined $lines[$realline_next - 1] ||
3755 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3762 # Ignore goto labels.
3763 if ($s =~ /$Ident:\*$/s) {
3765 # Ignore functions being called
3766 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3768 } elsif ($s =~ /^.\s*else\b/s) {
3770 # declarations always start with types
3771 } 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) {
3774 possible($type, "A:" . $s);
3776 # definitions in global scope can only start with types
3777 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3778 possible($1, "B:" . $s);
3781 # any (foo ... *) is a pointer cast, and foo is a type
3782 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3783 possible($1, "C:" . $s);
3786 # Check for any sort of function declaration.
3787 # int foo(something bar, other baz);
3788 # void (*store_gdt)(x86_descr_ptr *);
3789 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3790 my ($name_len) = length($1);
3793 substr($ctx, 0, $name_len + 1, '');
3794 $ctx =~ s/\)[^\)]*$//;
3796 for my $arg (split(/\s*,\s*/, $ctx)) {
3797 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3799 possible($1, "D:" . $s);
3807 # Checks which may be anchored in the context.
3810 # Check for switch () and associated case and default
3811 # statements should be at the same indent.
3812 if ($line=~/\bswitch\s*\(.*\)/) {
3815 my @ctx = ctx_block_outer($linenr, $realcnt);
3817 for my $ctx (@ctx) {
3818 my ($clen, $cindent) = line_stats($ctx);
3819 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3820 $indent != $cindent) {
3821 $err .= "$sep$ctx\n";
3828 ERROR("SWITCH_CASE_INDENT_LEVEL",
3829 "switch and case should be at the same indent\n$hereline$err");
3833 # if/while/etc brace do not go on next line, unless defining a do while loop,
3834 # or if that brace on the next line is for something else
3835 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3836 my $pre_ctx = "$1$2";
3838 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3840 if ($line =~ /^\+\t{6,}/) {
3841 WARN("DEEP_INDENTATION",
3842 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3845 my $ctx_cnt = $realcnt - $#ctx - 1;
3846 my $ctx = join("\n", @ctx);
3848 my $ctx_ln = $linenr;
3849 my $ctx_skip = $realcnt;
3851 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3852 defined $lines[$ctx_ln - 1] &&
3853 $lines[$ctx_ln - 1] =~ /^-/)) {
3854 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3855 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3859 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3860 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3862 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3864 "that open brace { should be on the previous line\n" .
3865 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3867 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3868 $ctx =~ /\)\s*\;\s*$/ &&
3869 defined $lines[$ctx_ln - 1])
3871 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3872 if ($nindent > $indent) {
3873 WARN("TRAILING_SEMICOLON",
3874 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3875 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3880 # Check relative indent for conditionals and blocks.
3881 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3882 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3883 ctx_statement_block($linenr, $realcnt, 0)
3884 if (!defined $stat);
3885 my ($s, $c) = ($stat, $cond);
3887 substr($s, 0, length($c), '');
3889 # remove inline comments
3893 # Find out how long the conditional actually is.
3894 my @newlines = ($c =~ /\n/gs);
3895 my $cond_lines = 1 + $#newlines;
3897 # Make sure we remove the line prefixes as we have
3898 # none on the first line, and are going to readd them
3901 while ($s =~ /\n\s+\\\n/) {
3902 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3905 # We want to check the first line inside the block
3906 # starting at the end of the conditional, so remove:
3907 # 1) any blank line termination
3908 # 2) any opening brace { on end of the line
3910 my $continuation = 0;
3912 $s =~ s/^.*\bdo\b//;
3914 if ($s =~ s/^\s*\\//) {
3917 if ($s =~ s/^\s*?\n//) {
3922 # Also ignore a loop construct at the end of a
3923 # preprocessor statement.
3924 if (($prevline =~ /^.\s*#\s*define\s/ ||
3925 $prevline =~ /\\\s*$/) && $continuation == 0) {
3931 while ($cond_ptr != $cond_lines) {
3932 $cond_ptr = $cond_lines;
3934 # If we see an #else/#elif then the code
3936 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3941 # 1) blank lines, they should be at 0,
3942 # 2) preprocessor lines, and
3944 if ($continuation ||
3946 $s =~ /^\s*#\s*?/ ||
3947 $s =~ /^\s*$Ident\s*:/) {
3948 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3949 if ($s =~ s/^.*?\n//) {
3955 my (undef, $sindent) = line_stats("+" . $s);
3956 my $stat_real = raw_line($linenr, $cond_lines);
3958 # Check if either of these lines are modified, else
3959 # this is not this patch's fault.
3960 if (!defined($stat_real) ||
3961 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3964 if (defined($stat_real) && $cond_lines > 1) {
3965 $stat_real = "[...]\n$stat_real";
3968 #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";
3970 if ($check && $s ne '' &&
3971 (($sindent % $tabsize) != 0 ||
3972 ($sindent < $indent) ||
3973 ($sindent == $indent &&
3974 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3975 ($sindent > $indent + $tabsize))) {
3976 WARN("SUSPECT_CODE_INDENT",
3977 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3981 # Track the 'values' across context and added lines.
3982 my $opline = $line; $opline =~ s/^./ /;
3983 my ($curr_values, $curr_vars) =
3984 annotate_values($opline . "\n", $prev_values);
3985 $curr_values = $prev_values . $curr_values;
3987 my $outline = $opline; $outline =~ s/\t/ /g;
3988 print "$linenr > .$outline\n";
3989 print "$linenr > $curr_values\n";
3990 print "$linenr > $curr_vars\n";
3992 $prev_values = substr($curr_values, -1);
3994 #ignore lines not being added
3995 next if ($line =~ /^[^\+]/);
3997 # check for self assignments used to avoid compiler warnings
3998 # e.g.: int foo = foo, *bar = NULL;
3999 # struct foo bar = *(&(bar));
4000 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4002 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4003 WARN("SELF_ASSIGNMENT",
4004 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4008 # check for dereferences that span multiple lines
4009 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4010 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4011 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4013 $line =~ /^.\s*($Lval)/;
4016 WARN("MULTILINE_DEREFERENCE",
4017 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4020 # check for declarations of signed or unsigned without int
4021 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4024 $var = "" if (!defined $var);
4025 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4029 $pointer = "" if (!defined $pointer);
4031 if (WARN("UNSPECIFIED_INT",
4032 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4034 my $decl = trim($sign) . " int ";
4035 my $comp_pointer = $pointer;
4036 $comp_pointer =~ s/\s//g;
4037 $decl .= $comp_pointer;
4038 $decl = rtrim($decl) if ($var eq "");
4039 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4044 # TEST: allow direct testing of the type matcher.
4046 if ($line =~ /^.\s*$Declare\s*$/) {
4048 "TEST: is type\n" . $herecurr);
4049 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4050 ERROR("TEST_NOT_TYPE",
4051 "TEST: is not type ($1 is)\n". $herecurr);
4055 # TEST: allow direct testing of the attribute matcher.
4057 if ($line =~ /^.\s*$Modifier\s*$/) {
4059 "TEST: is attr\n" . $herecurr);
4060 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4061 ERROR("TEST_NOT_ATTR",
4062 "TEST: is not attr ($1 is)\n". $herecurr);
4067 # check for initialisation to aggregates open brace on the next line
4068 if ($line =~ /^.\s*{/ &&
4069 $prevline =~ /(?:^|[^=])=\s*$/) {
4070 if (ERROR("OPEN_BRACE",
4071 "that open brace { should be on the previous line\n" . $hereprev) &&
4072 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4073 fix_delete_line($fixlinenr - 1, $prevrawline);
4074 fix_delete_line($fixlinenr, $rawline);
4075 my $fixedline = $prevrawline;
4076 $fixedline =~ s/\s*=\s*$/ = {/;
4077 fix_insert_line($fixlinenr, $fixedline);
4079 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4080 fix_insert_line($fixlinenr, $fixedline);
4085 # Checks which are anchored on the added line.
4088 # check for malformed paths in #include statements (uses RAW line)
4089 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4091 if ($path =~ m{//}) {
4092 ERROR("MALFORMED_INCLUDE",
4093 "malformed #include filename\n" . $herecurr);
4095 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4096 ERROR("UAPI_INCLUDE",
4097 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4101 # no C99 // comments
4102 if ($line =~ m{//}) {
4103 if (ERROR("C99_COMMENTS",
4104 "do not use C99 // comments\n" . $herecurr) &&
4106 my $line = $fixed[$fixlinenr];
4107 if ($line =~ /\/\/(.*)$/) {
4108 my $comment = trim($1);
4109 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4113 # Remove C99 comments.
4115 $opline =~ s@//.*@@;
4117 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4118 # the whole statement.
4119 #print "APW <$lines[$realline_next - 1]>\n";
4120 if (defined $realline_next &&
4121 exists $lines[$realline_next - 1] &&
4122 !defined $suppress_export{$realline_next} &&
4123 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4124 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4125 # Handle definitions which produce identifiers with
4128 # EXPORT_SYMBOL(something_foo);
4130 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4131 $name =~ /^${Ident}_$2/) {
4132 #print "FOO C name<$name>\n";
4133 $suppress_export{$realline_next} = 1;
4135 } elsif ($stat !~ /(?:
4137 ^.DEFINE_$Ident\(\Q$name\E\)|
4138 ^.DECLARE_$Ident\(\Q$name\E\)|
4139 ^.LIST_HEAD\(\Q$name\E\)|
4140 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4141 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4143 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4144 $suppress_export{$realline_next} = 2;
4146 $suppress_export{$realline_next} = 1;
4149 if (!defined $suppress_export{$linenr} &&
4150 $prevline =~ /^.\s*$/ &&
4151 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4152 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4153 #print "FOO B <$lines[$linenr - 1]>\n";
4154 $suppress_export{$linenr} = 2;
4156 if (defined $suppress_export{$linenr} &&
4157 $suppress_export{$linenr} == 2) {
4158 WARN("EXPORT_SYMBOL",
4159 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4162 # check for global initialisers.
4163 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4164 if (ERROR("GLOBAL_INITIALISERS",
4165 "do not initialise globals to $1\n" . $herecurr) &&
4167 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4170 # check for static initialisers.
4171 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4172 if (ERROR("INITIALISED_STATIC",
4173 "do not initialise statics to $1\n" .
4176 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4180 # check for misordered declarations of char/short/int/long with signed/unsigned
4181 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4183 WARN("MISORDERED_TYPE",
4184 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4187 # check for unnecessary <signed> int declarations of short/long/long long
4188 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4189 my $type = trim($1);
4190 next if ($type !~ /\bint\b/);
4191 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4192 my $new_type = $type;
4193 $new_type =~ s/\b\s*int\s*\b/ /;
4194 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4195 $new_type =~ s/^const\s+//;
4196 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4197 $new_type = "const $new_type" if ($type =~ /^const\b/);
4198 $new_type =~ s/\s+/ /g;
4199 $new_type = trim($new_type);
4200 if (WARN("UNNECESSARY_INT",
4201 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4203 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4207 # check for static const char * arrays.
4208 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4209 WARN("STATIC_CONST_CHAR_ARRAY",
4210 "static const char * array should probably be static const char * const\n" .
4214 # check for initialized const char arrays that should be static const
4215 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4216 if (WARN("STATIC_CONST_CHAR_ARRAY",
4217 "const array should probably be static const\n" . $herecurr) &&
4219 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4223 # check for static char foo[] = "bar" declarations.
4224 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4225 WARN("STATIC_CONST_CHAR_ARRAY",
4226 "static char array declaration should probably be static const char\n" .
4230 # check for const <foo> const where <foo> is not a pointer or array type
4231 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4233 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4235 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4236 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4238 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4242 # check for const static or static <non ptr type> const declarations
4243 # prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4244 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4245 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4246 if (WARN("STATIC_CONST",
4247 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4249 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4250 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4254 # check for non-global char *foo[] = {"bar", ...} declarations.
4255 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4256 WARN("STATIC_CONST_CHAR_ARRAY",
4257 "char * array declaration might be better as static const\n" .
4261 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4262 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4264 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4266 if (WARN("ARRAY_SIZE",
4267 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4269 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4274 # check for function declarations without arguments like "int foo()"
4275 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4276 if (ERROR("FUNCTION_WITHOUT_ARGS",
4277 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4279 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4283 # check for new typedefs, only function parameters and sparse annotations
4285 if ($line =~ /\btypedef\s/ &&
4286 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4287 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4288 $line !~ /\b$typeTypedefs\b/ &&
4289 $line !~ /\b__bitwise\b/) {
4290 WARN("NEW_TYPEDEFS",
4291 "do not add new typedefs\n" . $herecurr);
4294 # * goes on variable not on type
4296 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4298 my ($ident, $from, $to) = ($1, $2, $2);
4300 # Should start with a space.
4301 $to =~ s/^(\S)/ $1/;
4302 # Should not end with a space.
4304 # '*'s should not have spaces between.
4305 while ($to =~ s/\*\s+\*/\*\*/) {
4308 ## print "1: from<$from> to<$to> ident<$ident>\n";
4310 if (ERROR("POINTER_LOCATION",
4311 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4313 my $sub_from = $ident;
4314 my $sub_to = $ident;
4315 $sub_to =~ s/\Q$from\E/$to/;
4316 $fixed[$fixlinenr] =~
4317 s@\Q$sub_from\E@$sub_to@;
4321 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4323 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4325 # Should start with a space.
4326 $to =~ s/^(\S)/ $1/;
4327 # Should not end with a space.
4329 # '*'s should not have spaces between.
4330 while ($to =~ s/\*\s+\*/\*\*/) {
4332 # Modifiers should have spaces.
4333 $to =~ s/(\b$Modifier$)/$1 /;
4335 ## print "2: from<$from> to<$to> ident<$ident>\n";
4336 if ($from ne $to && $ident !~ /^$Modifier$/) {
4337 if (ERROR("POINTER_LOCATION",
4338 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4341 my $sub_from = $match;
4342 my $sub_to = $match;
4343 $sub_to =~ s/\Q$from\E/$to/;
4344 $fixed[$fixlinenr] =~
4345 s@\Q$sub_from\E@$sub_to@;
4350 # avoid BUG() or BUG_ON()
4351 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4352 my $msg_level = \&WARN;
4353 $msg_level = \&CHK if ($file);
4354 &{$msg_level}("AVOID_BUG",
4355 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4358 # avoid LINUX_VERSION_CODE
4359 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4360 WARN("LINUX_VERSION_CODE",
4361 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4364 # check for uses of printk_ratelimit
4365 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4366 WARN("PRINTK_RATELIMITED",
4367 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4370 # printk should use KERN_* levels
4371 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4372 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4373 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4376 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4378 my $level = lc($orig);
4379 $level = "warn" if ($level eq "warning");
4380 my $level2 = $level;
4381 $level2 = "dbg" if ($level eq "debug");
4382 WARN("PREFER_PR_LEVEL",
4383 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4386 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4388 my $level = lc($orig);
4389 $level = "warn" if ($level eq "warning");
4390 $level = "dbg" if ($level eq "debug");
4391 WARN("PREFER_DEV_LEVEL",
4392 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4395 # trace_printk should not be used in production code.
4396 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4397 WARN("TRACE_PRINTK",
4398 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4401 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4402 # number of false positives, but assembly files are not checked, so at
4403 # least the arch entry code will not trigger this warning.
4404 if ($line =~ /\bENOSYS\b/) {
4406 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4409 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4410 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4411 # Similarly to ENOSYS warning a small number of false positives is expected.
4412 if (!$file && $line =~ /\bENOTSUPP\b/) {
4413 if (WARN("ENOTSUPP",
4414 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4416 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4420 # function brace can't be on same line, except for #defines of do while,
4421 # or if closed on same line
4422 if ($perl_version_ok &&
4423 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4424 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4426 if (ERROR("OPEN_BRACE",
4427 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4429 fix_delete_line($fixlinenr, $rawline);
4430 my $fixed_line = $rawline;
4431 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4434 fix_insert_line($fixlinenr, ltrim($line1));
4435 fix_insert_line($fixlinenr, "\+{");
4436 if ($line2 !~ /^\s*$/) {
4437 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4442 # open braces for enum, union and struct go on the same line.
4443 if ($line =~ /^.\s*{/ &&
4444 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4445 if (ERROR("OPEN_BRACE",
4446 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4447 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4448 fix_delete_line($fixlinenr - 1, $prevrawline);
4449 fix_delete_line($fixlinenr, $rawline);
4450 my $fixedline = rtrim($prevrawline) . " {";
4451 fix_insert_line($fixlinenr, $fixedline);
4452 $fixedline = $rawline;
4453 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4454 if ($fixedline !~ /^\+\s*$/) {
4455 fix_insert_line($fixlinenr, $fixedline);
4460 # missing space after union, struct or enum definition
4461 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4463 "missing space after $1 definition\n" . $herecurr) &&
4465 $fixed[$fixlinenr] =~
4466 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4470 # Function pointer declarations
4471 # check spacing between type, funcptr, and args
4472 # canonical declaration is "type (*funcptr)(args...)"
4473 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4475 my $pre_pointer_space = $2;
4476 my $post_pointer_space = $3;
4478 my $post_funcname_space = $5;
4479 my $pre_args_space = $6;
4481 # the $Declare variable will capture all spaces after the type
4482 # so check it for a missing trailing missing space but pointer return types
4483 # don't need a space so don't warn for those.
4484 my $post_declare_space = "";
4485 if ($declare =~ /(\s+)$/) {
4486 $post_declare_space = $1;
4487 $declare = rtrim($declare);
4489 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4491 "missing space after return type\n" . $herecurr);
4492 $post_declare_space = " ";
4495 # unnecessary space "type (*funcptr)(args...)"
4496 # This test is not currently implemented because these declarations are
4498 # int foo(int bar, ...)
4499 # and this is form shouldn't/doesn't generate a checkpatch warning.
4501 # elsif ($declare =~ /\s{2,}$/) {
4503 # "Multiple spaces after return type\n" . $herecurr);
4506 # unnecessary space "type ( *funcptr)(args...)"
4507 if (defined $pre_pointer_space &&
4508 $pre_pointer_space =~ /^\s/) {
4510 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4513 # unnecessary space "type (* funcptr)(args...)"
4514 if (defined $post_pointer_space &&
4515 $post_pointer_space =~ /^\s/) {
4517 "Unnecessary space before function pointer name\n" . $herecurr);
4520 # unnecessary space "type (*funcptr )(args...)"
4521 if (defined $post_funcname_space &&
4522 $post_funcname_space =~ /^\s/) {
4524 "Unnecessary space after function pointer name\n" . $herecurr);
4527 # unnecessary space "type (*funcptr) (args...)"
4528 if (defined $pre_args_space &&
4529 $pre_args_space =~ /^\s/) {
4531 "Unnecessary space before function pointer arguments\n" . $herecurr);
4534 if (show_type("SPACING") && $fix) {
4535 $fixed[$fixlinenr] =~
4536 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4540 # check for spacing round square brackets; allowed:
4541 # 1. with a type on the left -- int [] a;
4542 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4543 # 3. inside a curly brace -- = { [0...10] = 5 }
4544 while ($line =~ /(.*?\s)\[/g) {
4545 my ($where, $prefix) = ($-[1], $1);
4546 if ($prefix !~ /$Type\s+$/ &&
4547 ($where != 0 || $prefix !~ /^.\s+$/) &&
4548 $prefix !~ /[{,:]\s+$/) {
4549 if (ERROR("BRACKET_SPACE",
4550 "space prohibited before open square bracket '['\n" . $herecurr) &&
4552 $fixed[$fixlinenr] =~
4553 s/^(\+.*?)\s+\[/$1\[/;
4558 # check for spaces between functions and their parentheses.
4559 while ($line =~ /($Ident)\s+\(/g) {
4561 my $ctx_before = substr($line, 0, $-[1]);
4562 my $ctx = "$ctx_before$name";
4564 # Ignore those directives where spaces _are_ permitted.
4566 if|for|while|switch|return|case|
4567 volatile|__volatile__|
4568 __attribute__|format|__extension__|
4571 # cpp #define statements have non-optional spaces, ie
4572 # if there is a space between the name and the open
4573 # parenthesis it is simply not a parameter group.
4574 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4576 # cpp #elif statement condition may start with a (
4577 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4579 # If this whole things ends with a type its most
4580 # likely a typedef for a function.
4581 } elsif ($ctx =~ /$Type$/) {
4585 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4587 $fixed[$fixlinenr] =~
4588 s/\b$name\s+\(/$name\(/;
4593 # Check operator spacing.
4594 if (!($line=~/\#\s*include/)) {
4595 my $fixed_line = "";
4599 <<=|>>=|<=|>=|==|!=|
4600 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4601 =>|->|<<|>>|<|>|=|!|~|
4602 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4605 my @elements = split(/($ops|;)/, $opline);
4607 ## print("element count: <" . $#elements . ">\n");
4608 ## foreach my $el (@elements) {
4609 ## print("el: <$el>\n");
4612 my @fix_elements = ();
4615 foreach my $el (@elements) {
4616 push(@fix_elements, substr($rawline, $off, length($el)));
4617 $off += length($el);
4622 my $blank = copy_spacing($opline);
4623 my $last_after = -1;
4625 for (my $n = 0; $n < $#elements; $n += 2) {
4627 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4629 ## print("n: <$n> good: <$good>\n");
4631 $off += length($elements[$n]);
4633 # Pick up the preceding and succeeding characters.
4634 my $ca = substr($opline, 0, $off);
4636 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4637 $cc = substr($opline, $off + length($elements[$n + 1]));
4639 my $cb = "$ca$;$cc";
4642 $a = 'V' if ($elements[$n] ne '');
4643 $a = 'W' if ($elements[$n] =~ /\s$/);
4644 $a = 'C' if ($elements[$n] =~ /$;$/);
4645 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4646 $a = 'O' if ($elements[$n] eq '');
4647 $a = 'E' if ($ca =~ /^\s*$/);
4649 my $op = $elements[$n + 1];
4652 if (defined $elements[$n + 2]) {
4653 $c = 'V' if ($elements[$n + 2] ne '');
4654 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4655 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4656 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4657 $c = 'O' if ($elements[$n + 2] eq '');
4658 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4663 my $ctx = "${a}x${c}";
4665 my $at = "(ctx:$ctx)";
4667 my $ptr = substr($blank, 0, $off) . "^";
4668 my $hereptr = "$hereline$ptr\n";
4670 # Pull out the value of this operator.
4671 my $op_type = substr($curr_values, $off + 1, 1);
4673 # Get the full operator variant.
4674 my $opv = $op . substr($curr_vars, $off, 1);
4676 # Ignore operators passed as parameters.
4677 if ($op_type ne 'V' &&
4678 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4681 # } elsif ($op =~ /^$;+$/) {
4683 # ; should have either the end of line or a space or \ after it
4684 } elsif ($op eq ';') {
4685 if ($ctx !~ /.x[WEBC]/ &&
4686 $cc !~ /^\\/ && $cc !~ /^;/) {
4687 if (ERROR("SPACING",
4688 "space required after that '$op' $at\n" . $hereptr)) {
4689 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4695 } elsif ($op eq '//') {
4697 # : when part of a bitfield
4698 } elsif ($opv eq ':B') {
4699 # skip the bitfield test for now
4703 } elsif ($op eq '->') {
4704 if ($ctx =~ /Wx.|.xW/) {
4705 if (ERROR("SPACING",
4706 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4707 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4708 if (defined $fix_elements[$n + 2]) {
4709 $fix_elements[$n + 2] =~ s/^\s+//;
4715 # , must not have a space before and must have a space on the right.
4716 } elsif ($op eq ',') {
4717 my $rtrim_before = 0;
4718 my $space_after = 0;
4719 if ($ctx =~ /Wx./) {
4720 if (ERROR("SPACING",
4721 "space prohibited before that '$op' $at\n" . $hereptr)) {
4726 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4727 if (ERROR("SPACING",
4728 "space required after that '$op' $at\n" . $hereptr)) {
4734 if ($rtrim_before || $space_after) {
4735 if ($rtrim_before) {
4736 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4738 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4745 # '*' as part of a type definition -- reported already.
4746 } elsif ($opv eq '*_') {
4747 #warn "'*' is part of type\n";
4749 # unary operators should have a space before and
4750 # none after. May be left adjacent to another
4751 # unary operator, or a cast
4752 } elsif ($op eq '!' || $op eq '~' ||
4753 $opv eq '*U' || $opv eq '-U' ||
4754 $opv eq '&U' || $opv eq '&&U') {
4755 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4756 if (ERROR("SPACING",
4757 "space required before that '$op' $at\n" . $hereptr)) {
4758 if ($n != $last_after + 2) {
4759 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4764 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4765 # A unary '*' may be const
4767 } elsif ($ctx =~ /.xW/) {
4768 if (ERROR("SPACING",
4769 "space prohibited after that '$op' $at\n" . $hereptr)) {
4770 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4771 if (defined $fix_elements[$n + 2]) {
4772 $fix_elements[$n + 2] =~ s/^\s+//;
4778 # unary ++ and unary -- are allowed no space on one side.
4779 } elsif ($op eq '++' or $op eq '--') {
4780 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4781 if (ERROR("SPACING",
4782 "space required one side of that '$op' $at\n" . $hereptr)) {
4783 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4787 if ($ctx =~ /Wx[BE]/ ||
4788 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4789 if (ERROR("SPACING",
4790 "space prohibited before that '$op' $at\n" . $hereptr)) {
4791 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4795 if ($ctx =~ /ExW/) {
4796 if (ERROR("SPACING",
4797 "space prohibited after that '$op' $at\n" . $hereptr)) {
4798 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4799 if (defined $fix_elements[$n + 2]) {
4800 $fix_elements[$n + 2] =~ s/^\s+//;
4806 # << and >> may either have or not have spaces both sides
4807 } elsif ($op eq '<<' or $op eq '>>' or
4808 $op eq '&' or $op eq '^' or $op eq '|' or
4809 $op eq '+' or $op eq '-' or
4810 $op eq '*' or $op eq '/' or
4814 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4816 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4817 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4818 $fix_elements[$n + 2] =~ s/^\s+//;
4821 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4823 "space preferred before that '$op' $at\n" . $hereptr)) {
4824 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4828 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4829 if (ERROR("SPACING",
4830 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4831 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4832 if (defined $fix_elements[$n + 2]) {
4833 $fix_elements[$n + 2] =~ s/^\s+//;
4839 # A colon needs no spaces before when it is
4840 # terminating a case value or a label.
4841 } elsif ($opv eq ':C' || $opv eq ':L') {
4842 if ($ctx =~ /Wx./) {
4843 if (ERROR("SPACING",
4844 "space prohibited before that '$op' $at\n" . $hereptr)) {
4845 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4850 # All the others need spaces both sides.
4851 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4854 # Ignore email addresses <foo@bar>
4856 $cc =~ /^\S+\@\S+>/) ||
4858 $ca =~ /<\S+\@\S+$/))
4863 # for asm volatile statements
4864 # ignore a colon with another
4865 # colon immediately before or after
4867 ($ca =~ /:$/ || $cc =~ /^:/)) {
4871 # messages are ERROR, but ?: are CHK
4873 my $msg_level = \&ERROR;
4874 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4876 if (&{$msg_level}("SPACING",
4877 "spaces required around that '$op' $at\n" . $hereptr)) {
4878 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4879 if (defined $fix_elements[$n + 2]) {
4880 $fix_elements[$n + 2] =~ s/^\s+//;
4886 $off += length($elements[$n + 1]);
4888 ## print("n: <$n> GOOD: <$good>\n");
4890 $fixed_line = $fixed_line . $good;
4893 if (($#elements % 2) == 0) {
4894 $fixed_line = $fixed_line . $fix_elements[$#elements];
4897 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4898 $fixed[$fixlinenr] = $fixed_line;
4904 # check for whitespace before a non-naked semicolon
4905 if ($line =~ /^\+.*\S\s+;\s*$/) {
4907 "space prohibited before semicolon\n" . $herecurr) &&
4909 1 while $fixed[$fixlinenr] =~
4910 s/^(\+.*\S)\s+;/$1;/;
4914 # check for multiple assignments
4915 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4916 CHK("MULTIPLE_ASSIGNMENTS",
4917 "multiple assignments should be avoided\n" . $herecurr);
4920 ## # check for multiple declarations, allowing for a function declaration
4922 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4923 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4925 ## # Remove any bracketed sections to ensure we do not
4926 ## # falsly report the parameters of functions.
4928 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4930 ## if ($ln =~ /,/) {
4931 ## WARN("MULTIPLE_DECLARATION",
4932 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4936 #need space before brace following if, while, etc
4937 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4938 $line =~ /\b(?:else|do)\{/) {
4939 if (ERROR("SPACING",
4940 "space required before the open brace '{'\n" . $herecurr) &&
4942 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4946 ## # check for blank lines before declarations
4947 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4948 ## $prevrawline =~ /^.\s*$/) {
4950 ## "No blank lines before declarations\n" . $hereprev);
4954 # closing brace should have a space following it when it has anything
4956 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4957 if (ERROR("SPACING",
4958 "space required after that close brace '}'\n" . $herecurr) &&
4960 $fixed[$fixlinenr] =~
4961 s/}((?!(?:,|;|\)))\S)/} $1/;
4965 # check spacing on square brackets
4966 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4967 if (ERROR("SPACING",
4968 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4970 $fixed[$fixlinenr] =~
4974 if ($line =~ /\s\]/) {
4975 if (ERROR("SPACING",
4976 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4978 $fixed[$fixlinenr] =~
4983 # check spacing on parentheses
4984 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4985 $line !~ /for\s*\(\s+;/) {
4986 if (ERROR("SPACING",
4987 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4989 $fixed[$fixlinenr] =~
4993 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4994 $line !~ /for\s*\(.*;\s+\)/ &&
4995 $line !~ /:\s+\)/) {
4996 if (ERROR("SPACING",
4997 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4999 $fixed[$fixlinenr] =~
5004 # check unnecessary parentheses around addressof/dereference single $Lvals
5005 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5007 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5009 if (CHK("UNNECESSARY_PARENTHESES",
5010 "Unnecessary parentheses around $var\n" . $herecurr) &&
5012 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5016 # check for unnecessary parentheses around function pointer uses
5017 # ie: (foo->bar)(); should be foo->bar();
5018 # but not "if (foo->bar) (" to avoid some false positives
5019 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5021 if (CHK("UNNECESSARY_PARENTHESES",
5022 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5024 my $var2 = deparenthesize($var);
5026 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5030 # check for unnecessary parentheses around comparisons in if uses
5031 # when !drivers/staging or command-line uses --strict
5032 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
5033 $perl_version_ok && defined($stat) &&
5034 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5036 my $test = substr($2, 1, -1);
5038 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5040 # avoid parentheses around potential macro args
5041 next if ($match =~ /^\s*\w+\s*$/);
5042 if (!defined($herectx)) {
5043 $herectx = $here . "\n";
5044 my $cnt = statement_rawlines($if_stat);
5045 for (my $n = 0; $n < $cnt; $n++) {
5046 my $rl = raw_line($linenr, $n);
5047 $herectx .= $rl . "\n";
5048 last if $rl =~ /^[ \+].*\{/;
5051 CHK("UNNECESSARY_PARENTHESES",
5052 "Unnecessary parentheses around '$match'\n" . $herectx);
5056 #goto labels aren't indented, allow a single space however
5057 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
5058 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
5059 if (WARN("INDENTED_LABEL",
5060 "labels should not be indented\n" . $herecurr) &&
5062 $fixed[$fixlinenr] =~
5067 # check if a statement with a comma should be two statements like:
5068 # foo = bar(), /* comma should be semicolon */
5070 if (defined($stat) &&
5071 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5072 my $cnt = statement_rawlines($stat);
5073 my $herectx = get_stat_here($linenr, $cnt, $here);
5074 WARN("SUSPECT_COMMA_SEMICOLON",
5075 "Possible comma where semicolon could be used\n" . $herectx);
5078 # return is not a function
5079 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5081 if ($perl_version_ok &&
5082 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5084 $value = deparenthesize($value);
5085 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5086 ERROR("RETURN_PARENTHESES",
5087 "return is not a function, parentheses are not required\n" . $herecurr);
5089 } elsif ($spacing !~ /\s+/) {
5091 "space required before the open parenthesis '('\n" . $herecurr);
5095 # unnecessary return in a void function
5096 # at end-of-function, with the previous line a single leading tab, then return;
5097 # and the line before that not a goto label target like "out:"
5098 if ($sline =~ /^[ \+]}\s*$/ &&
5099 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5101 $lines[$linenr - 3] =~ /^[ +]/ &&
5102 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5104 "void function return statements are not generally useful\n" . $hereprev);
5107 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5108 if ($perl_version_ok &&
5109 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5110 my $openparens = $1;
5111 my $count = $openparens =~ tr@\(@\(@;
5113 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5114 my $comp = $4; #Not $1 because of $LvalOrFunc
5115 $msg = " - maybe == should be = ?" if ($comp eq "==");
5116 WARN("UNNECESSARY_PARENTHESES",
5117 "Unnecessary parentheses$msg\n" . $herecurr);
5121 # comparisons with a constant or upper case identifier on the left
5122 # avoid cases like "foo + BAR < baz"
5123 # only fix matches surrounded by parentheses to avoid incorrect
5124 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5125 if ($perl_version_ok &&
5126 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5131 my $newcomp = $comp;
5132 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5133 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5134 WARN("CONSTANT_COMPARISON",
5135 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5139 } elsif ($comp eq "<=") {
5141 } elsif ($comp eq ">") {
5143 } elsif ($comp eq ">=") {
5146 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5150 # Return of what appears to be an errno should normally be negative
5151 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5153 if ($name ne 'EOF' && $name ne 'ERROR') {
5154 WARN("USE_NEGATIVE_ERRNO",
5155 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5159 # Need a space before open parenthesis after if, while etc
5160 if ($line =~ /\b(if|while|for|switch)\(/) {
5161 if (ERROR("SPACING",
5162 "space required before the open parenthesis '('\n" . $herecurr) &&
5164 $fixed[$fixlinenr] =~
5165 s/\b(if|while|for|switch)\(/$1 \(/;
5169 # Check for illegal assignment in if conditional -- and check for trailing
5170 # statements after the conditional.
5171 if ($line =~ /do\s*(?!{)/) {
5172 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5173 ctx_statement_block($linenr, $realcnt, 0)
5174 if (!defined $stat);
5175 my ($stat_next) = ctx_statement_block($line_nr_next,
5176 $remain_next, $off_next);
5177 $stat_next =~ s/\n./\n /g;
5178 ##print "stat<$stat> stat_next<$stat_next>\n";
5180 if ($stat_next =~ /^\s*while\b/) {
5181 # If the statement carries leading newlines,
5182 # then count those as offsets.
5184 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5186 statement_rawlines($whitespace) - 1;
5188 $suppress_whiletrailers{$line_nr_next +
5192 if (!defined $suppress_whiletrailers{$linenr} &&
5193 defined($stat) && defined($cond) &&
5194 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5195 my ($s, $c) = ($stat, $cond);
5197 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5198 if (ERROR("ASSIGN_IN_IF",
5199 "do not use assignment in if condition\n" . $herecurr) &&
5200 $fix && $perl_version_ok) {
5201 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5209 fix_delete_line($fixlinenr, $rawline);
5210 fix_insert_line($fixlinenr, "$space$statement;");
5211 my $newline = "${space}if (";
5212 $newline .= '!' if defined($not);
5213 $newline .= '(' if (defined $not && defined($test) && defined($against));
5214 $newline .= "$assigned";
5215 $newline .= " $test $against" if (defined($test) && defined($against));
5216 $newline .= ')' if (defined $not && defined($test) && defined($against));
5218 $newline .= " {" if (defined($brace));
5219 fix_insert_line($fixlinenr + 1, $newline);
5224 # Find out what is on the end of the line after the
5226 substr($s, 0, length($c), '');
5228 $s =~ s/$;//g; # Remove any comments
5229 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5230 $c !~ /}\s*while\s*/)
5232 # Find out how long the conditional actually is.
5233 my @newlines = ($c =~ /\n/gs);
5234 my $cond_lines = 1 + $#newlines;
5237 $stat_real = raw_line($linenr, $cond_lines)
5238 . "\n" if ($cond_lines);
5239 if (defined($stat_real) && $cond_lines > 1) {
5240 $stat_real = "[...]\n$stat_real";
5243 ERROR("TRAILING_STATEMENTS",
5244 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5248 # Check for bitwise tests written as boolean
5260 WARN("HEXADECIMAL_BOOLEAN_TEST",
5261 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5264 # if and else should not have general statements after it
5265 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5267 $s =~ s/$;//g; # Remove any comments
5268 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5269 ERROR("TRAILING_STATEMENTS",
5270 "trailing statements should be on next line\n" . $herecurr);
5273 # if should not continue a brace
5274 if ($line =~ /}\s*if\b/) {
5275 ERROR("TRAILING_STATEMENTS",
5276 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5279 # case and default should not have general statements after them
5280 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5282 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5286 ERROR("TRAILING_STATEMENTS",
5287 "trailing statements should be on next line\n" . $herecurr);
5290 # Check for }<nl>else {, these must be at the same
5291 # indent level to be relevant to each other.
5292 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5293 $previndent == $indent) {
5294 if (ERROR("ELSE_AFTER_BRACE",
5295 "else should follow close brace '}'\n" . $hereprev) &&
5296 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5297 fix_delete_line($fixlinenr - 1, $prevrawline);
5298 fix_delete_line($fixlinenr, $rawline);
5299 my $fixedline = $prevrawline;
5300 $fixedline =~ s/}\s*$//;
5301 if ($fixedline !~ /^\+\s*$/) {
5302 fix_insert_line($fixlinenr, $fixedline);
5304 $fixedline = $rawline;
5305 $fixedline =~ s/^(.\s*)else/$1} else/;
5306 fix_insert_line($fixlinenr, $fixedline);
5310 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5311 $previndent == $indent) {
5312 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5314 # Find out what is on the end of the line after the
5316 substr($s, 0, length($c), '');
5319 if ($s =~ /^\s*;/) {
5320 if (ERROR("WHILE_AFTER_BRACE",
5321 "while should follow close brace '}'\n" . $hereprev) &&
5322 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5323 fix_delete_line($fixlinenr - 1, $prevrawline);
5324 fix_delete_line($fixlinenr, $rawline);
5325 my $fixedline = $prevrawline;
5326 my $trailing = $rawline;
5327 $trailing =~ s/^\+//;
5328 $trailing = trim($trailing);
5329 $fixedline =~ s/}\s*$/} $trailing/;
5330 fix_insert_line($fixlinenr, $fixedline);
5335 #Specific variable tests
5336 while ($line =~ m{($Constant|$Lval)}g) {
5340 if ($var !~ /^$Constant$/ &&
5341 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5342 #Ignore some autogenerated defines and enum values
5343 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5344 #Ignore Page<foo> variants
5345 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5346 #Ignore SI style variants like nS, mV and dB
5347 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5348 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5349 #Ignore some three character SI units explicitly, like MiB and KHz
5350 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5351 while ($var =~ m{($Ident)}g) {
5353 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5355 seed_camelcase_includes();
5356 if (!$file && !$camelcase_file_seeded) {
5357 seed_camelcase_file($realfile);
5358 $camelcase_file_seeded = 1;
5361 if (!defined $camelcase{$word}) {
5362 $camelcase{$word} = 1;
5364 "Avoid CamelCase: <$word>\n" . $herecurr);
5370 #no spaces allowed after \ in define
5371 if ($line =~ /\#\s*define.*\\\s+$/) {
5372 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5373 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5375 $fixed[$fixlinenr] =~ s/\s+$//;
5379 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5380 # itself <asm/foo.h> (uses RAW line)
5381 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5383 my $checkfile = "include/linux/$file";
5384 if (-f "$root/$checkfile" &&
5385 $realfile ne $checkfile &&
5386 $1 !~ /$allowed_asm_includes/)
5388 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5389 if ($asminclude > 0) {
5390 if ($realfile =~ m{^arch/}) {
5391 CHK("ARCH_INCLUDE_LINUX",
5392 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5394 WARN("INCLUDE_LINUX",
5395 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5401 # multi-statement macros should be enclosed in a do while loop, grab the
5402 # first statement and ensure its the whole macro if its not enclosed
5403 # in a known good container
5404 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5405 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5408 my ($off, $dstat, $dcond, $rest);
5410 my $has_flow_statement = 0;
5411 my $has_arg_concat = 0;
5412 ($dstat, $dcond, $ln, $cnt, $off) =
5413 ctx_statement_block($linenr, $realcnt, 0);
5415 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5416 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5418 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5419 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5421 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5422 my $define_args = $1;
5423 my $define_stmt = $dstat;
5426 if (defined $define_args && $define_args ne "") {
5427 $define_args = substr($define_args, 1, length($define_args) - 2);
5428 $define_args =~ s/\s*//g;
5429 $define_args =~ s/\\\+?//g;
5430 @def_args = split(",", $define_args);
5434 $dstat =~ s/\\\n.//g;
5435 $dstat =~ s/^\s*//s;
5436 $dstat =~ s/\s*$//s;
5438 # Flatten any parentheses and braces
5439 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5440 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5441 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5445 # Flatten any obvious string concatenation.
5446 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5447 $dstat =~ s/$Ident\s*($String)/$1/)
5451 # Make asm volatile uses seem like a generic function
5452 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5454 my $exceptions = qr{
5467 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5470 my $stmt_cnt = statement_rawlines($ctx);
5471 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5474 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5475 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5476 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5477 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5478 $dstat !~ /$exceptions/ &&
5479 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5480 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5481 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5482 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5483 $dstat !~ /^for\s*$Constant$/ && # for (...)
5484 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5485 $dstat !~ /^do\s*{/ && # do {...
5486 $dstat !~ /^\(\{/ && # ({...
5487 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5489 if ($dstat =~ /^\s*if\b/) {
5490 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5491 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5492 } elsif ($dstat =~ /;/) {
5493 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5494 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5496 ERROR("COMPLEX_MACRO",
5497 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5502 # Make $define_stmt single line, comment-free, etc
5503 my @stmt_array = split('\n', $define_stmt);
5506 foreach my $l (@stmt_array) {
5511 } elsif ($l =~ /^[\+ ]/) {
5512 $define_stmt .= substr($l, 1);
5515 $define_stmt =~ s/$;//g;
5516 $define_stmt =~ s/\s+/ /g;
5517 $define_stmt = trim($define_stmt);
5519 # check if any macro arguments are reused (ignore '...' and 'type')
5520 foreach my $arg (@def_args) {
5521 next if ($arg =~ /\.\.\./);
5522 next if ($arg =~ /^type$/i);
5523 my $tmp_stmt = $define_stmt;
5524 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5525 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5526 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5527 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5529 CHK("MACRO_ARG_REUSE",
5530 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5532 # check if any macro arguments may have other precedence issues
5533 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5534 ((defined($1) && $1 ne ',') ||
5535 (defined($2) && $2 ne ','))) {
5536 CHK("MACRO_ARG_PRECEDENCE",
5537 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5541 # check for macros with flow control, but without ## concatenation
5542 # ## concatenation is commonly a macro that defines a function so ignore those
5543 if ($has_flow_statement && !$has_arg_concat) {
5544 my $cnt = statement_rawlines($ctx);
5545 my $herectx = get_stat_here($linenr, $cnt, $here);
5547 WARN("MACRO_WITH_FLOW_CONTROL",
5548 "Macros with flow control statements should be avoided\n" . "$herectx");
5551 # check for line continuations outside of #defines, preprocessor #, and asm
5554 if ($prevline !~ /^..*\\$/ &&
5555 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5556 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5557 $line =~ /^\+.*\\$/) {
5558 WARN("LINE_CONTINUATIONS",
5559 "Avoid unnecessary line continuations\n" . $herecurr);
5563 # do {} while (0) macro tests:
5564 # single-statement macros do not need to be enclosed in do while (0) loop,
5565 # macro should not end with a semicolon
5566 if ($perl_version_ok &&
5567 $realfile !~ m@/vmlinux.lds.h$@ &&
5568 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5571 my ($off, $dstat, $dcond, $rest);
5573 ($dstat, $dcond, $ln, $cnt, $off) =
5574 ctx_statement_block($linenr, $realcnt, 0);
5577 $dstat =~ s/\\\n.//g;
5580 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5585 my $cnt = statement_rawlines($ctx);
5586 my $herectx = get_stat_here($linenr, $cnt, $here);
5588 if (($stmts =~ tr/;/;/) == 1 &&
5589 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5590 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5591 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5593 if (defined $semis && $semis ne "") {
5594 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5595 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5597 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5599 my $cnt = statement_rawlines($ctx);
5600 my $herectx = get_stat_here($linenr, $cnt, $here);
5602 WARN("TRAILING_SEMICOLON",
5603 "macros should not use a trailing semicolon\n" . "$herectx");
5607 # check for redundant bracing round if etc
5608 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5609 my ($level, $endln, @chunks) =
5610 ctx_statement_full($linenr, $realcnt, 1);
5611 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5612 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5613 if ($#chunks > 0 && $level == 0) {
5617 my $herectx = $here . "\n";
5618 my $ln = $linenr - 1;
5619 for my $chunk (@chunks) {
5620 my ($cond, $block) = @{$chunk};
5622 # If the condition carries leading newlines, then count those as offsets.
5623 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5624 my $offset = statement_rawlines($whitespace) - 1;
5626 $allowed[$allow] = 0;
5627 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5629 # We have looked at and allowed this specific line.
5630 $suppress_ifbraces{$ln + $offset} = 1;
5632 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5633 $ln += statement_rawlines($block) - 1;
5635 substr($block, 0, length($cond), '');
5637 $seen++ if ($block =~ /^\s*{/);
5639 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5640 if (statement_lines($cond) > 1) {
5641 #print "APW: ALLOWED: cond<$cond>\n";
5642 $allowed[$allow] = 1;
5644 if ($block =~/\b(?:if|for|while)\b/) {
5645 #print "APW: ALLOWED: block<$block>\n";
5646 $allowed[$allow] = 1;
5648 if (statement_block_size($block) > 1) {
5649 #print "APW: ALLOWED: lines block<$block>\n";
5650 $allowed[$allow] = 1;
5655 my $sum_allowed = 0;
5656 foreach (@allowed) {
5659 if ($sum_allowed == 0) {
5661 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5662 } elsif ($sum_allowed != $allow &&
5665 "braces {} should be used on all arms of this statement\n" . $herectx);
5670 if (!defined $suppress_ifbraces{$linenr - 1} &&
5671 $line =~ /\b(if|while|for|else)\b/) {
5674 # Check the pre-context.
5675 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5676 #print "APW: ALLOWED: pre<$1>\n";
5680 my ($level, $endln, @chunks) =
5681 ctx_statement_full($linenr, $realcnt, $-[0]);
5683 # Check the condition.
5684 my ($cond, $block) = @{$chunks[0]};
5685 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5686 if (defined $cond) {
5687 substr($block, 0, length($cond), '');
5689 if (statement_lines($cond) > 1) {
5690 #print "APW: ALLOWED: cond<$cond>\n";
5693 if ($block =~/\b(?:if|for|while)\b/) {
5694 #print "APW: ALLOWED: block<$block>\n";
5697 if (statement_block_size($block) > 1) {
5698 #print "APW: ALLOWED: lines block<$block>\n";
5701 # Check the post-context.
5702 if (defined $chunks[1]) {
5703 my ($cond, $block) = @{$chunks[1]};
5704 if (defined $cond) {
5705 substr($block, 0, length($cond), '');
5707 if ($block =~ /^\s*\{/) {
5708 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5712 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5713 my $cnt = statement_rawlines($block);
5714 my $herectx = get_stat_here($linenr, $cnt, $here);
5717 "braces {} are not necessary for single statement blocks\n" . $herectx);
5721 # check for single line unbalanced braces
5722 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5723 $sline =~ /^.\s*else\s*\{\s*$/) {
5724 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5727 # check for unnecessary blank lines around braces
5728 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5730 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5731 $fix && $prevrawline =~ /^\+/) {
5732 fix_delete_line($fixlinenr - 1, $prevrawline);
5735 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5737 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5739 fix_delete_line($fixlinenr, $rawline);
5743 # no volatiles please
5744 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5745 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5747 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5750 # Check for user-visible strings broken across lines, which breaks the ability
5751 # to grep for the string. Make exceptions when the previous string ends in a
5752 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5753 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5754 if ($line =~ /^\+\s*$String/ &&
5755 $prevline =~ /"\s*$/ &&
5756 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5757 if (WARN("SPLIT_STRING",
5758 "quoted string split across lines\n" . $hereprev) &&
5760 $prevrawline =~ /^\+.*"\s*$/ &&
5761 $last_coalesced_string_linenr != $linenr - 1) {
5762 my $extracted_string = get_quoted_string($line, $rawline);
5763 my $comma_close = "";
5764 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5768 fix_delete_line($fixlinenr - 1, $prevrawline);
5769 fix_delete_line($fixlinenr, $rawline);
5770 my $fixedline = $prevrawline;
5771 $fixedline =~ s/"\s*$//;
5772 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5773 fix_insert_line($fixlinenr - 1, $fixedline);
5774 $fixedline = $rawline;
5775 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5776 if ($fixedline !~ /\+\s*$/) {
5777 fix_insert_line($fixlinenr, $fixedline);
5779 $last_coalesced_string_linenr = $linenr;
5783 # check for missing a space in a string concatenation
5784 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5785 WARN('MISSING_SPACE',
5786 "break quoted strings at a space character\n" . $hereprev);
5789 # check for an embedded function name in a string when the function is known
5790 # This does not work very well for -f --file checking as it depends on patch
5791 # context providing the function name or a single line form for in-file
5792 # function declarations
5793 if ($line =~ /^\+.*$String/ &&
5794 defined($context_function) &&
5795 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5796 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5797 WARN("EMBEDDED_FUNCTION_NAME",
5798 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5801 # check for spaces before a quoted newline
5802 if ($rawline =~ /^.*\".*\s\\n/) {
5803 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5804 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5806 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5811 # concatenated string without spaces between elements
5812 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5813 if (CHK("CONCATENATED_STRING",
5814 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5816 while ($line =~ /($String)/g) {
5817 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5818 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5819 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5824 # uncoalesced string fragments
5825 if ($line =~ /$String\s*"/) {
5826 if (WARN("STRING_FRAGMENTS",
5827 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5829 while ($line =~ /($String)(?=\s*")/g) {
5830 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5831 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5836 # check for non-standard and hex prefixed decimal printf formats
5837 my $show_L = 1; #don't show the same defect twice
5839 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5840 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5841 $string =~ s/%%/__/g;
5843 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5845 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5849 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5851 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5854 # check for 0x<decimal>
5855 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5856 ERROR("PRINTF_0XDECIMAL",
5857 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5861 # check for line continuations in quoted strings with odd counts of "
5862 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5863 WARN("LINE_CONTINUATIONS",
5864 "Avoid line continuations in quoted strings\n" . $herecurr);
5868 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5870 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5874 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5876 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5879 # check for needless "if (<foo>) fn(<foo>)" uses
5880 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5881 my $tested = quotemeta($1);
5882 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5883 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5885 if (WARN('NEEDLESS_IF',
5886 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5889 my $leading_tabs = "";
5890 my $new_leading_tabs = "";
5891 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5896 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5897 $new_leading_tabs = $1;
5898 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5905 fix_delete_line($fixlinenr - 1, $prevrawline);
5906 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5912 # check for unnecessary "Out of Memory" messages
5913 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5914 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5915 (defined $1 || defined $3) &&
5918 my $testline = $lines[$linenr - 3];
5920 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5921 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5923 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5924 $s !~ /\b__GFP_NOWARN\b/ ) {
5926 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5930 # check for logging functions with KERN_<LEVEL>
5931 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5932 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5934 if (WARN("UNNECESSARY_KERN_LEVEL",
5935 "Possible unnecessary $level\n" . $herecurr) &&
5937 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5941 # check for logging continuations
5942 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5943 WARN("LOGGING_CONTINUATION",
5944 "Avoid logging continuation uses where feasible\n" . $herecurr);
5947 # check for mask then right shift without a parentheses
5948 if ($perl_version_ok &&
5949 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5950 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5951 WARN("MASK_THEN_SHIFT",
5952 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5955 # check for pointer comparisons to NULL
5956 if ($perl_version_ok) {
5957 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5960 $equal = "" if ($4 eq "!=");
5961 if (CHK("COMPARISON_TO_NULL",
5962 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5964 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5969 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5970 if ($line =~ /(\b$InitAttribute\b)/) {
5972 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5975 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5976 ERROR("MISPLACED_INIT",
5977 "$attr should be placed after $var\n" . $herecurr)) ||
5978 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5979 WARN("MISPLACED_INIT",
5980 "$attr should be placed after $var\n" . $herecurr))) &&
5982 $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;
5987 # check for $InitAttributeData (ie: __initdata) with const
5988 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5990 $attr =~ /($InitAttributePrefix)(.*)/;
5991 my $attr_prefix = $1;
5993 if (ERROR("INIT_ATTRIBUTE",
5994 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5996 $fixed[$fixlinenr] =~
5997 s/$InitAttributeData/${attr_prefix}initconst/;
6001 # check for $InitAttributeConst (ie: __initconst) without const
6002 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6004 if (ERROR("INIT_ATTRIBUTE",
6005 "Use of $attr requires a separate use of const\n" . $herecurr) &&
6007 my $lead = $fixed[$fixlinenr] =~
6008 /(^\+\s*(?:static\s+))/;
6010 $lead = "$lead " if ($lead !~ /^\+$/);
6011 $lead = "${lead}const ";
6012 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6016 # check for __read_mostly with const non-pointer (should just be const)
6017 if ($line =~ /\b__read_mostly\b/ &&
6018 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6019 if (ERROR("CONST_READ_MOSTLY",
6020 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6022 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6026 # don't use __constant_<foo> functions outside of include/uapi/
6027 if ($realfile !~ m@^include/uapi/@ &&
6028 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6029 my $constant_func = $1;
6030 my $func = $constant_func;
6031 $func =~ s/^__constant_//;
6032 if (WARN("CONSTANT_CONVERSION",
6033 "$constant_func should be $func\n" . $herecurr) &&
6035 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6039 # prefer usleep_range over udelay
6040 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6042 # ignore udelay's < 10, however
6043 if (! ($delay < 10) ) {
6045 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6047 if ($delay > 2000) {
6049 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6053 # warn about unexpectedly long msleep's
6054 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6057 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6061 # check for comparisons of jiffies
6062 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6063 WARN("JIFFIES_COMPARISON",
6064 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6067 # check for comparisons of get_jiffies_64()
6068 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6069 WARN("JIFFIES_COMPARISON",
6070 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6073 # warn about #ifdefs in C files
6074 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6075 # print "#ifdef in C files should be avoided\n";
6076 # print "$herecurr";
6080 # warn about spacing in #ifdefs
6081 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6082 if (ERROR("SPACING",
6083 "exactly one space required after that #$1\n" . $herecurr) &&
6085 $fixed[$fixlinenr] =~
6086 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6091 # check for spinlock_t definitions without a comment.
6092 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6093 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6095 if (!ctx_has_comment($first_line, $linenr)) {
6096 CHK("UNCOMMENTED_DEFINITION",
6097 "$1 definition without comment\n" . $herecurr);
6100 # check for memory barriers without a comment.
6107 my $barrier_stems = qr{
6115 my $all_barriers = qr{
6117 smp_(?:$barrier_stems)|
6118 virt_(?:$barrier_stems)
6121 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6122 if (!ctx_has_comment($first_line, $linenr)) {
6123 WARN("MEMORY_BARRIER",
6124 "memory barrier without comment\n" . $herecurr);
6128 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6130 if ($realfile !~ m@^include/asm-generic/@ &&
6131 $realfile !~ m@/barrier\.h$@ &&
6132 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6133 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6134 WARN("MEMORY_BARRIER",
6135 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6138 # check for waitqueue_active without a comment.
6139 if ($line =~ /\bwaitqueue_active\s*\(/) {
6140 if (!ctx_has_comment($first_line, $linenr)) {
6141 WARN("WAITQUEUE_ACTIVE",
6142 "waitqueue_active without comment\n" . $herecurr);
6146 # check for data_race without a comment.
6147 if ($line =~ /\bdata_race\s*\(/) {
6148 if (!ctx_has_comment($first_line, $linenr)) {
6150 "data_race without comment\n" . $herecurr);
6154 # check of hardware specific defines
6155 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6157 "architecture specific defines should be avoided\n" . $herecurr);
6160 # check that the storage class is not after a type
6161 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6162 WARN("STORAGE_CLASS",
6163 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6165 # Check that the storage class is at the beginning of a declaration
6166 if ($line =~ /\b$Storage\b/ &&
6167 $line !~ /^.\s*$Storage/ &&
6168 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6169 $1 !~ /[\,\)]\s*$/) {
6170 WARN("STORAGE_CLASS",
6171 "storage class should be at the beginning of the declaration\n" . $herecurr);
6174 # check the location of the inline attribute, that it is between
6175 # storage class and type.
6176 if ($line =~ /\b$Type\s+$Inline\b/ ||
6177 $line =~ /\b$Inline\s+$Storage\b/) {
6178 ERROR("INLINE_LOCATION",
6179 "inline keyword should sit between storage class and type\n" . $herecurr);
6182 # Check for __inline__ and __inline, prefer inline
6183 if ($realfile !~ m@\binclude/uapi/@ &&
6184 $line =~ /\b(__inline__|__inline)\b/) {
6186 "plain inline is preferred over $1\n" . $herecurr) &&
6188 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6193 # Check for compiler attributes
6194 if ($realfile !~ m@\binclude/uapi/@ &&
6195 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6197 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6200 "aligned" => "__aligned",
6201 "always_inline" => "__always_inline",
6202 "assume_aligned" => "__assume_aligned",
6204 "const" => "__attribute_const__",
6206 "designated_init" => "__designated_init",
6207 "externally_visible" => "__visible",
6208 "format" => "printf|scanf",
6209 "gnu_inline" => "__gnu_inline",
6210 "malloc" => "__malloc",
6212 "no_caller_saved_registers" => "__no_caller_saved_registers",
6213 "noclone" => "__noclone",
6214 "noinline" => "noinline",
6215 "nonstring" => "__nonstring",
6216 "noreturn" => "__noreturn",
6217 "packed" => "__packed",
6219 "section" => "__section",
6223 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6226 $params = $2 if defined($2);
6227 my $curr_attr = $orig_attr;
6228 $curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6229 if (exists($attr_list{$curr_attr})) {
6230 my $new = $attr_list{$curr_attr};
6231 if ($curr_attr eq "format" && $params) {
6232 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6235 $new = "$new$params";
6237 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6238 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6240 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6241 $fixed[$fixlinenr] =~ s/$remove//;
6242 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6243 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6244 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6249 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6250 if ($attr =~ /^_*unused/) {
6251 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6252 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6256 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6257 if ($perl_version_ok &&
6258 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6259 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6260 $line =~ /\b__weak\b/)) {
6261 ERROR("WEAK_DECLARATION",
6262 "Using weak declarations can have unintended link defects\n" . $herecurr);
6265 # check for c99 types like uint8_t used outside of uapi/ and tools/
6266 if ($realfile !~ m@\binclude/uapi/@ &&
6267 $realfile !~ m@\btools/@ &&
6268 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6270 if ($type =~ /\b($typeC99Typedefs)\b/) {
6272 my $kernel_type = 'u';
6273 $kernel_type = 's' if ($type =~ /^_*[si]/);
6276 if (CHK("PREFER_KERNEL_TYPES",
6277 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6279 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6284 # check for cast of C90 native int or longer types constants
6285 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6288 if (WARN("TYPECAST_INT_CONSTANT",
6289 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6292 my $newconst = $const;
6293 $newconst =~ s/${Int_type}$//;
6294 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6295 if ($cast =~ /\blong\s+long\b/) {
6297 } elsif ($cast =~ /\blong\b/) {
6300 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6304 # check for sizeof(&)
6305 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6306 WARN("SIZEOF_ADDRESS",
6307 "sizeof(& should be avoided\n" . $herecurr);
6310 # check for sizeof without parenthesis
6311 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6312 if (WARN("SIZEOF_PARENTHESIS",
6313 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6315 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6319 # check for struct spinlock declarations
6320 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6321 WARN("USE_SPINLOCK_T",
6322 "struct spinlock should be spinlock_t\n" . $herecurr);
6325 # check for seq_printf uses that could be seq_puts
6326 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6327 my $fmt = get_quoted_string($line, $rawline);
6330 if (WARN("PREFER_SEQ_PUTS",
6331 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6333 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6338 # check for vsprintf extension %p<foo> misuses
6339 if ($perl_version_ok &&
6341 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6342 $1 !~ /^_*volatile_*$/) {
6345 my $lc = $stat =~ tr@\n@@;
6346 $lc = $lc + $linenr;
6347 for (my $count = $linenr; $count <= $lc; $count++) {
6351 my $bad_specifier = "";
6352 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6355 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6359 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6360 ($extension eq "f" &&
6361 defined $qualifier && $qualifier !~ /^w/)) {
6362 $bad_specifier = $specifier;
6365 if ($extension eq "x" && !defined($stat_real)) {
6366 if (!defined($stat_real)) {
6367 $stat_real = get_stat_real($linenr, $lc);
6369 WARN("VSPRINTF_SPECIFIER_PX",
6370 "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");
6373 if ($bad_specifier ne "") {
6374 my $stat_real = get_stat_real($linenr, $lc);
6375 my $ext_type = "Invalid";
6377 if ($bad_specifier =~ /p[Ff]/) {
6378 $use = " - use %pS instead";
6379 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6382 WARN("VSPRINTF_POINTER_EXTENSION",
6383 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6388 # Check for misused memsets
6389 if ($perl_version_ok &&
6391 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6397 if ($ms_size =~ /^(0x|)0$/i) {
6399 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6400 } elsif ($ms_size =~ /^(0x|)1$/i) {
6402 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6406 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6407 # if ($perl_version_ok &&
6409 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6410 # if (WARN("PREFER_ETHER_ADDR_COPY",
6411 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6413 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6417 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6418 # if ($perl_version_ok &&
6420 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6421 # WARN("PREFER_ETHER_ADDR_EQUAL",
6422 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6425 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6426 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6427 # if ($perl_version_ok &&
6429 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6433 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6434 # if (WARN("PREFER_ETH_ZERO_ADDR",
6435 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6437 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6439 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6440 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6441 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6443 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6448 # typecasts on min/max could be min_t/max_t
6449 if ($perl_version_ok &&
6451 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6452 if (defined $2 || defined $7) {
6454 my $cast1 = deparenthesize($2);
6456 my $cast2 = deparenthesize($7);
6460 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6461 $cast = "$cast1 or $cast2";
6462 } elsif ($cast1 ne "") {
6468 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6472 # check usleep_range arguments
6473 if ($perl_version_ok &&
6475 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6479 WARN("USLEEP_RANGE",
6480 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6481 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6483 WARN("USLEEP_RANGE",
6484 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6488 # check for naked sscanf
6489 if ($perl_version_ok &&
6491 $line =~ /\bsscanf\b/ &&
6492 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6493 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6494 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6495 my $lc = $stat =~ tr@\n@@;
6496 $lc = $lc + $linenr;
6497 my $stat_real = get_stat_real($linenr, $lc);
6498 WARN("NAKED_SSCANF",
6499 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6502 # check for simple sscanf that should be kstrto<foo>
6503 if ($perl_version_ok &&
6505 $line =~ /\bsscanf\b/) {
6506 my $lc = $stat =~ tr@\n@@;
6507 $lc = $lc + $linenr;
6508 my $stat_real = get_stat_real($linenr, $lc);
6509 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6511 my $count = $format =~ tr@%@%@;
6513 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6514 WARN("SSCANF_TO_KSTRTO",
6515 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6520 # check for new externs in .h files.
6521 if ($realfile =~ /\.h$/ &&
6522 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6523 if (CHK("AVOID_EXTERNS",
6524 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6526 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6530 # check for new externs in .c files.
6531 if ($realfile =~ /\.c$/ && defined $stat &&
6532 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6534 my $function_name = $1;
6535 my $paren_space = $2;
6538 if (defined $cond) {
6539 substr($s, 0, length($cond), '');
6543 WARN("AVOID_EXTERNS",
6544 "externs should be avoided in .c files\n" . $herecurr);
6547 if ($paren_space =~ /\n/) {
6548 WARN("FUNCTION_ARGUMENTS",
6549 "arguments for function declarations should follow identifier\n" . $herecurr);
6552 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6553 $stat =~ /^.\s*extern\s+/)
6555 WARN("AVOID_EXTERNS",
6556 "externs should be avoided in .c files\n" . $herecurr);
6559 # check for function declarations that have arguments without identifier names
6560 if (defined $stat &&
6561 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6563 my $args = trim($1);
6564 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6566 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6567 WARN("FUNCTION_ARGUMENTS",
6568 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6573 # check for function definitions
6574 if ($perl_version_ok &&
6576 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6577 $context_function = $1;
6579 # check for multiline function definition with misplaced open brace
6581 my $cnt = statement_rawlines($stat);
6582 my $herectx = $here . "\n";
6583 for (my $n = 0; $n < $cnt; $n++) {
6584 my $rl = raw_line($linenr, $n);
6585 $herectx .= $rl . "\n";
6586 $ok = 1 if ($rl =~ /^[ \+]\{/);
6587 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6588 last if $rl =~ /^[ \+].*\{/;
6592 "open brace '{' following function definitions go on the next line\n" . $herectx);
6596 # checks for new __setup's
6597 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6600 if (!grep(/$name/, @setup_docs)) {
6601 CHK("UNDOCUMENTED_SETUP",
6602 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6606 # check for pointless casting of alloc functions
6607 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6608 WARN("UNNECESSARY_CASTS",
6609 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6613 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6614 if ($perl_version_ok &&
6615 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6616 CHK("ALLOC_SIZEOF_STRUCT",
6617 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6620 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6621 if ($perl_version_ok &&
6623 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6627 my $newfunc = "kmalloc_array";
6628 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6631 if ($a1 =~ /^sizeof\s*\S/) {
6635 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6636 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6637 my $cnt = statement_rawlines($stat);
6638 my $herectx = get_stat_here($linenr, $cnt, $here);
6640 if (WARN("ALLOC_WITH_MULTIPLY",
6641 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6644 $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;
6649 # check for krealloc arg reuse
6650 if ($perl_version_ok &&
6651 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6653 WARN("KREALLOC_ARG_REUSE",
6654 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6657 # check for alloc argument mismatch
6658 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6659 WARN("ALLOC_ARRAY_ARGS",
6660 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6663 # check for multiple semicolons
6664 if ($line =~ /;\s*;\s*$/) {
6665 if (WARN("ONE_SEMICOLON",
6666 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6668 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6672 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6673 if ($realfile !~ m@^include/uapi/@ &&
6674 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6676 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6677 if (CHK("BIT_MACRO",
6678 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6680 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6684 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6685 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6686 WARN("IS_ENABLED_CONFIG",
6687 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6690 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6691 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6693 if (WARN("PREFER_IS_ENABLED",
6694 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6696 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6700 # check for /* fallthrough */ like comment, prefer fallthrough;
6701 my @fallthroughs = (
6704 'lint -fallthrough[ \t]*',
6705 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6706 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6707 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6708 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6710 if ($raw_comment ne '') {
6711 foreach my $ft (@fallthroughs) {
6712 if ($raw_comment =~ /$ft/) {
6713 my $msg_level = \&WARN;
6714 $msg_level = \&CHK if ($file);
6715 &{$msg_level}("PREFER_FALLTHROUGH",
6716 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6722 # check for switch/default statements without a break;
6723 if ($perl_version_ok &&
6725 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6726 my $cnt = statement_rawlines($stat);
6727 my $herectx = get_stat_here($linenr, $cnt, $here);
6729 WARN("DEFAULT_NO_BREAK",
6730 "switch default: should use break\n" . $herectx);
6733 # check for gcc specific __FUNCTION__
6734 if ($line =~ /\b__FUNCTION__\b/) {
6735 if (WARN("USE_FUNC",
6736 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6738 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6742 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6743 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6745 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6748 # check for use of yield()
6749 if ($line =~ /\byield\s*\(\s*\)/) {
6751 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6754 # check for comparisons against true and false
6755 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6763 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6765 my $type = lc($otype);
6766 if ($type =~ /^(?:true|false)$/) {
6767 if (("$test" eq "==" && "$type" eq "true") ||
6768 ("$test" eq "!=" && "$type" eq "false")) {
6772 CHK("BOOL_COMPARISON",
6773 "Using comparison to $otype is error prone\n" . $herecurr);
6775 ## maybe suggesting a correct construct would better
6776 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6781 # check for semaphores initialized locked
6782 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6783 WARN("CONSIDER_COMPLETION",
6784 "consider using a completion\n" . $herecurr);
6787 # recommend kstrto* over simple_strto* and strict_strto*
6788 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6789 WARN("CONSIDER_KSTRTO",
6790 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6793 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6794 if ($line =~ /^.\s*__initcall\s*\(/) {
6795 WARN("USE_DEVICE_INITCALL",
6796 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6799 # check for spin_is_locked(), suggest lockdep instead
6800 if ($line =~ /\bspin_is_locked\(/) {
6802 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6805 # check for deprecated apis
6806 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6807 my $deprecated_api = $1;
6808 my $new_api = $deprecated_apis{$deprecated_api};
6809 WARN("DEPRECATED_API",
6810 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6813 # check for various structs that are normally const (ops, kgdb, device_tree)
6814 # and avoid what seem like struct definitions 'struct foo {'
6815 if (defined($const_structs) &&
6816 $line !~ /\bconst\b/ &&
6817 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6818 WARN("CONST_STRUCT",
6819 "struct $1 should normally be const\n" . $herecurr);
6822 # use of NR_CPUS is usually wrong
6823 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6824 if ($line =~ /\bNR_CPUS\b/ &&
6825 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6826 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6827 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6828 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6829 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6832 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6835 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6836 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6837 ERROR("DEFINE_ARCH_HAS",
6838 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6841 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6842 if ($perl_version_ok &&
6843 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6844 WARN("LIKELY_MISUSE",
6845 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6848 # nested likely/unlikely calls
6849 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6850 WARN("LIKELY_MISUSE",
6851 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6854 # whine mightly about in_atomic
6855 if ($line =~ /\bin_atomic\s*\(/) {
6856 if ($realfile =~ m@^drivers/@) {
6858 "do not use in_atomic in drivers\n" . $herecurr);
6859 } elsif ($realfile !~ m@^kernel/@) {
6861 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6865 # check for mutex_trylock_recursive usage
6866 if ($line =~ /mutex_trylock_recursive/) {
6868 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6871 # check for lockdep_set_novalidate_class
6872 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6873 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6874 if ($realfile !~ m@^kernel/lockdep@ &&
6875 $realfile !~ m@^include/linux/lockdep@ &&
6876 $realfile !~ m@^drivers/base/core@) {
6878 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6882 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6883 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6884 WARN("EXPORTED_WORLD_WRITABLE",
6885 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6888 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6889 # and whether or not function naming is typical and if
6890 # DEVICE_ATTR permissions uses are unusual too
6891 if ($perl_version_ok &&
6893 $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*\)/) {
6898 my $octal_perms = perms_to_octal($perms);
6899 if ($show =~ /^${var}_show$/ &&
6900 $store =~ /^${var}_store$/ &&
6901 $octal_perms eq "0644") {
6902 if (WARN("DEVICE_ATTR_RW",
6903 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6905 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6907 } elsif ($show =~ /^${var}_show$/ &&
6908 $store =~ /^NULL$/ &&
6909 $octal_perms eq "0444") {
6910 if (WARN("DEVICE_ATTR_RO",
6911 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6913 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6915 } elsif ($show =~ /^NULL$/ &&
6916 $store =~ /^${var}_store$/ &&
6917 $octal_perms eq "0200") {
6918 if (WARN("DEVICE_ATTR_WO",
6919 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6921 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6923 } elsif ($octal_perms eq "0644" ||
6924 $octal_perms eq "0444" ||
6925 $octal_perms eq "0200") {
6926 my $newshow = "$show";
6927 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6928 my $newstore = $store;
6929 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6931 if ($show ne $newshow) {
6932 $rename .= " '$show' to '$newshow'";
6934 if ($store ne $newstore) {
6935 $rename .= " '$store' to '$newstore'";
6937 WARN("DEVICE_ATTR_FUNCTIONS",
6938 "Consider renaming function(s)$rename\n" . $herecurr);
6940 WARN("DEVICE_ATTR_PERMS",
6941 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6945 # Mode permission misuses where it seems decimal should be octal
6946 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6947 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6948 # specific definition of not visible in sysfs.
6949 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6950 # use the default permissions
6951 if ($perl_version_ok &&
6953 $line =~ /$mode_perms_search/) {
6954 foreach my $entry (@mode_permission_funcs) {
6955 my $func = $entry->[0];
6956 my $arg_pos = $entry->[1];
6958 my $lc = $stat =~ tr@\n@@;
6959 $lc = $lc + $linenr;
6960 my $stat_real = get_stat_real($linenr, $lc);
6965 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6967 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6968 if ($stat =~ /$test/) {
6970 $val = $6 if ($skip_args ne "");
6971 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6972 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6973 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6974 ERROR("NON_OCTAL_PERMISSIONS",
6975 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6977 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6978 ERROR("EXPORTED_WORLD_WRITABLE",
6979 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6985 # check for uses of S_<PERMS> that could be octal for readability
6986 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6988 my $octal = perms_to_octal($oval);
6989 if (WARN("SYMBOLIC_PERMS",
6990 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6992 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6996 # validate content of MODULE_LICENSE against list from include/linux/module.h
6997 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6998 my $extracted_string = get_quoted_string($line, $rawline);
6999 my $valid_licenses = qr{
7002 GPL\ and\ additional\ rights|
7008 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7009 WARN("MODULE_LICENSE",
7010 "unknown module license " . $extracted_string . "\n" . $herecurr);
7014 # check for sysctl duplicate constants
7015 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7016 WARN("DUPLICATED_SYSCTL_CONST",
7017 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7021 # If we have no input at all, then there is nothing to report on
7022 # so just keep quiet.
7023 if ($#rawlines == -1) {
7027 # In mailback mode only produce a report in the negative, for
7028 # things that appear to be patches.
7029 if ($mailback && ($clean == 1 || !$is_patch)) {
7033 # This is not a patch, and we are are in 'no-patch' mode so
7035 if (!$chk_patch && !$is_patch) {
7039 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7040 ERROR("NOT_UNIFIED_DIFF",
7041 "Does not appear to be a unified-diff format patch\n");
7043 if ($is_patch && $has_commit_log && $chk_signoff) {
7044 if ($signoff == 0) {
7045 ERROR("MISSING_SIGN_OFF",
7046 "Missing Signed-off-by: line(s)\n");
7047 } elsif ($authorsignoff != 1) {
7048 # authorsignoff values:
7049 # 0 -> missing sign off
7050 # 1 -> sign off identical
7051 # 2 -> names and addresses match, comments mismatch
7052 # 3 -> addresses match, names different
7053 # 4 -> names match, addresses different
7054 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7056 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7058 if ($authorsignoff == 0) {
7059 ERROR("NO_AUTHOR_SIGN_OFF",
7060 "Missing Signed-off-by: line by nominal patch author '$author'\n");
7061 } elsif ($authorsignoff == 2) {
7062 CHK("FROM_SIGN_OFF_MISMATCH",
7063 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7064 } elsif ($authorsignoff == 3) {
7065 WARN("FROM_SIGN_OFF_MISMATCH",
7066 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7067 } elsif ($authorsignoff == 4) {
7068 WARN("FROM_SIGN_OFF_MISMATCH",
7069 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7070 } elsif ($authorsignoff == 5) {
7071 WARN("FROM_SIGN_OFF_MISMATCH",
7072 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7077 print report_dump();
7078 if ($summary && !($clean == 1 && $quiet == 1)) {
7079 print "$filename " if ($summary_file);
7080 print "total: $cnt_error errors, $cnt_warn warnings, " .
7081 (($check)? "$cnt_chk checks, " : "") .
7082 "$cnt_lines lines checked\n";
7086 # If there were any defects found and not already fixing them
7087 if (!$clean and !$fix) {
7090 NOTE: For some of the reported defects, checkpatch may be able to
7091 mechanically convert to the typical style using --fix or --fix-inplace.
7094 # If there were whitespace errors which cleanpatch can fix
7095 # then suggest that.
7096 if ($rpt_cleaners) {
7100 NOTE: Whitespace errors detected.
7101 You may wish to use scripts/cleanpatch or scripts/cleanfile
7106 if ($clean == 0 && $fix &&
7107 ("@rawlines" ne "@fixed" ||
7108 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7109 my $newfile = $filename;
7110 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7114 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7116 open($f, '>', $newfile)
7117 or die "$P: Can't open $newfile for write\n";
7118 foreach my $fixed_line (@fixed) {
7121 if ($linecount > 3) {
7122 $fixed_line =~ s/^\+//;
7123 print $f $fixed_line . "\n";
7126 print $f $fixed_line . "\n";
7134 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7136 Do _NOT_ trust the results written to this file.
7137 Do _NOT_ submit these changes without inspecting them for correctness.
7139 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7140 No warranties, expressed or implied...
7148 print "$vname has no obvious style problems and is ready for submission.\n";
7150 print "$vname has style problems, please review.\n";