2 # SPDX-License-Identifier: GPL-2.0
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
19 my $D = dirname(abs_path($P));
23 use Getopt::Long qw(:config no_auto_abbrev);
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 100;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
64 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
65 # git output parsing needs US English output, so first set backtick child process LANGUAGE
66 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
68 my ${CONFIG_} = "CONFIG_";
74 Usage: $P [OPTION]... [FILE]...
79 --no-tree run without a kernel tree
80 --no-signoff do not check for 'Signed-off-by' line
81 --patch treat FILE as patchfile (default)
82 --emacs emacs compile window format
83 --terse one line per report
84 --showfile emit diffed file position, not input file position
85 -g, --git treat FILE as a single commit or git revision range
86 single git commit with:
90 multiple git commits with:
94 git merges are ignored
95 -f, --file treat FILE as regular source file
96 --subjective, --strict enable more subjective tests
97 --list-types list the possible message types
98 --types TYPE(,TYPE2...) show only these comma separated message types
99 --ignore TYPE(,TYPE2...) ignore various comma separated message types
100 --show-types show the specific message type in the output
101 --max-line-length=n set the maximum line length, (default $max_line_length)
102 if exceeded, warn on patches
103 requires --strict for use with --file
104 --min-conf-desc-length=n set the min description length, if shorter, warn
105 --tab-size=n set the number of spaces for tab (default $tabsize)
106 --root=PATH PATH to the kernel tree root
107 --no-summary suppress the per-file summary
108 --mailback only produce a report in case of warnings/errors
109 --summary-file include the filename in summary
110 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
111 'values', 'possible', 'type', and 'attr' (default
113 --test-only=WORD report only warnings/errors containing WORD
115 --fix EXPERIMENTAL - may create horrible results
116 If correctable single-line errors exist, create
117 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
118 with potential errors corrected to the preferred
120 --fix-inplace EXPERIMENTAL - may create horrible results
121 Is the same as --fix, but overwrites the input
122 file. It's your fault if there's no backup or git
123 --ignore-perl-version override checking of perl version. expect
125 --codespell Use the codespell dictionary for spelling/typos
126 (default:/usr/share/codespell/dictionary.txt)
127 --codespellfile Use this codespell dictionary
128 --typedefsfile Read additional types from this file
129 --color[=WHEN] Use colors 'always', 'never', or only when output
130 is a terminal ('auto'). Default is 'auto'.
131 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default
133 -h, --help, --version display this help and exit
135 When FILE is - read standard input.
143 return grep { !$seen{$_}++ } @_;
153 open(my $script, '<', abs_path($P)) or
154 die "$P: Can't read '$P' $!\n";
156 my $text = <$script>;
160 # Also catch when type or level is passed through a variable
161 for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
164 @types = sort(uniq(@types));
165 print("#\tMessage type\n\n");
166 foreach my $type (@types) {
167 print(++$count . "\t" . $type . "\n");
173 my $conf = which_conf($configuration_file);
176 open(my $conffile, '<', "$conf")
177 or warn "$P: Can't find a readable $configuration_file file $!\n";
179 while (<$conffile>) {
182 $line =~ s/\s*\n?$//g;
186 next if ($line =~ m/^\s*#/);
187 next if ($line =~ m/^\s*$/);
189 my @words = split(" ", $line);
190 foreach my $word (@words) {
191 last if ($word =~ m/^#/);
192 push (@conf_args, $word);
196 unshift(@ARGV, @conf_args) if @conf_args;
199 # Perl's Getopt::Long allows options to take optional arguments after a space.
200 # Prevent --color by itself from consuming other arguments
202 if ($_ eq "--color" || $_ eq "-color") {
203 $_ = "--color=$color";
208 'q|quiet+' => \$quiet,
210 'signoff!' => \$chk_signoff,
211 'patch!' => \$chk_patch,
214 'showfile!' => \$showfile,
217 'subjective!' => \$check,
218 'strict!' => \$check,
219 'ignore=s' => \@ignore,
221 'show-types!' => \$show_types,
222 'list-types!' => \$list_types,
223 'max-line-length=i' => \$max_line_length,
224 'min-conf-desc-length=i' => \$min_conf_desc_length,
225 'tab-size=i' => \$tabsize,
227 'summary!' => \$summary,
228 'mailback!' => \$mailback,
229 'summary-file!' => \$summary_file,
231 'fix-inplace!' => \$fix_inplace,
232 'ignore-perl-version!' => \$ignore_perl_version,
233 'debug=s' => \%debug,
234 'test-only=s' => \$tst_only,
235 'codespell!' => \$codespell,
236 'codespellfile=s' => \$codespellfile,
237 'typedefsfile=s' => \$typedefsfile,
238 'color=s' => \$color,
239 'no-color' => \$color, #keep old behaviors of -nocolor
240 'nocolor' => \$color, #keep old behaviors of -nocolor
241 'kconfig-prefix=s' => \${CONFIG_},
248 list_types(0) if ($list_types);
250 $fix = 1 if ($fix_inplace);
251 $check_orig = $check;
253 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
257 my $perl_version_ok = 1;
258 if ($^V && $^V lt $minimum_perl_version) {
259 $perl_version_ok = 0;
260 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
261 exit(1) if (!$ignore_perl_version);
264 #if no filenames are given, push '-' to read patch from stdin
269 if ($color =~ /^[01]$/) {
271 } elsif ($color =~ /^always$/i) {
273 } elsif ($color =~ /^never$/i) {
275 } elsif ($color =~ /^auto$/i) {
276 $color = (-t STDOUT);
278 die "$P: Invalid color mode: $color\n";
281 # skip TAB size 1 to avoid additional checks on $tabsize - 1
282 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
284 sub hash_save_array_words {
285 my ($hashRef, $arrayRef) = @_;
287 my @array = split(/,/, join(',', @$arrayRef));
288 foreach my $word (@array) {
289 $word =~ s/\s*\n?$//g;
292 $word =~ tr/[a-z]/[A-Z]/;
294 next if ($word =~ m/^\s*#/);
295 next if ($word =~ m/^\s*$/);
301 sub hash_show_words {
302 my ($hashRef, $prefix) = @_;
304 if (keys %$hashRef) {
305 print "\nNOTE: $prefix message types:";
306 foreach my $word (sort keys %$hashRef) {
313 hash_save_array_words(\%ignore_type, \@ignore);
314 hash_save_array_words(\%use_type, \@use);
317 my $dbg_possible = 0;
320 for my $key (keys %debug) {
322 eval "\${dbg_$key} = '$debug{$key}';";
326 my $rpt_cleaners = 0;
335 if (!top_of_kernel_tree($root)) {
336 die "$P: $root: --root does not point at a valid tree\n";
339 if (top_of_kernel_tree('.')) {
341 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
342 top_of_kernel_tree($1)) {
347 if (!defined $root) {
348 print "Must be run from the top-level dir. of a kernel tree\n";
353 my $emitted_corrupt = 0;
356 [A-Za-z_][A-Za-z\d_]*
357 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
359 our $Storage = qr{extern|static|asmlinkage};
373 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
374 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
375 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
376 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
377 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
379 # Notes to $Attribute:
380 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
402 ____cacheline_aligned|
403 ____cacheline_aligned_in_smp|
404 ____cacheline_internodealigned_in_smp|
408 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
409 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
410 our $Lval = qr{$Ident(?:$Member)*};
412 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
413 our $Binary = qr{(?i)0b[01]+$Int_type?};
414 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
415 our $Int = qr{[0-9]+$Int_type?};
416 our $Octal = qr{0[0-7]+$Int_type?};
417 our $String = qr{"[X\t]*"};
418 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
419 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
420 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
421 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
422 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
423 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
424 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
425 our $Arithmetic = qr{\+|-|\*|\/|%};
429 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
432 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
436 our $NonptrTypeMisordered;
437 our $NonptrTypeWithAttr;
441 our $DeclareMisordered;
443 our $NON_ASCII_UTF8 = qr{
444 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
445 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
446 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
447 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
448 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
449 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
450 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
454 [\x09\x0A\x0D\x20-\x7E] # ASCII
458 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
459 our $typeOtherOSTypedefs = qr{(?x:
460 u_(?:char|short|int|long) | # bsd
461 u(?:nchar|short|int|long) # sysv
463 our $typeKernelTypedefs = qr{(?x:
464 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
467 our $typeTypedefs = qr{(?x:
469 $typeOtherOSTypedefs\b|
470 $typeKernelTypedefs\b
473 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
475 our $logFunctions = qr{(?x:
476 printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
477 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
479 WARN(?:_RATELIMIT|_ONCE|)|
482 seq_vprintf|seq_printf|seq_puts
485 our $allocFunctions = qr{(?x:
487 (?:kv|k|v)[czm]alloc(?:_node|_array)? |
490 (?:\w+)?alloc_skb(?:_ip_align)? |
491 # dev_alloc_skb/netdev_alloc_skb, et al
495 our $signature_tags = qr{(?xi:
507 our @typeListMisordered = (
508 qr{char\s+(?:un)?signed},
509 qr{int\s+(?:(?:un)?signed\s+)?short\s},
510 qr{int\s+short(?:\s+(?:un)?signed)},
511 qr{short\s+int(?:\s+(?:un)?signed)},
512 qr{(?:un)?signed\s+int\s+short},
513 qr{short\s+(?:un)?signed},
514 qr{long\s+int\s+(?:un)?signed},
515 qr{int\s+long\s+(?:un)?signed},
516 qr{long\s+(?:un)?signed\s+int},
517 qr{int\s+(?:un)?signed\s+long},
518 qr{int\s+(?:un)?signed},
519 qr{int\s+long\s+long\s+(?:un)?signed},
520 qr{long\s+long\s+int\s+(?:un)?signed},
521 qr{long\s+long\s+(?:un)?signed\s+int},
522 qr{long\s+long\s+(?:un)?signed},
523 qr{long\s+(?:un)?signed},
528 qr{(?:(?:un)?signed\s+)?char},
529 qr{(?:(?:un)?signed\s+)?short\s+int},
530 qr{(?:(?:un)?signed\s+)?short},
531 qr{(?:(?:un)?signed\s+)?int},
532 qr{(?:(?:un)?signed\s+)?long\s+int},
533 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
534 qr{(?:(?:un)?signed\s+)?long\s+long},
535 qr{(?:(?:un)?signed\s+)?long},
544 qr{${Ident}_handler},
545 qr{${Ident}_handler_fn},
549 our $C90_int_types = qr{(?x:
550 long\s+long\s+int\s+(?:un)?signed|
551 long\s+long\s+(?:un)?signed\s+int|
552 long\s+long\s+(?:un)?signed|
553 (?:(?:un)?signed\s+)?long\s+long\s+int|
554 (?:(?:un)?signed\s+)?long\s+long|
555 int\s+long\s+long\s+(?:un)?signed|
556 int\s+(?:(?:un)?signed\s+)?long\s+long|
558 long\s+int\s+(?:un)?signed|
559 long\s+(?:un)?signed\s+int|
560 long\s+(?:un)?signed|
561 (?:(?:un)?signed\s+)?long\s+int|
562 (?:(?:un)?signed\s+)?long|
563 int\s+long\s+(?:un)?signed|
564 int\s+(?:(?:un)?signed\s+)?long|
567 (?:(?:un)?signed\s+)?int
570 our @typeListFile = ();
571 our @typeListWithAttr = (
573 qr{struct\s+$InitAttribute\s+$Ident},
574 qr{union\s+$InitAttribute\s+$Ident},
577 our @modifierList = (
580 our @modifierListFile = ();
582 our @mode_permission_funcs = (
584 ["module_param_(?:array|named|string)", 4],
585 ["module_param_array_named", 5],
586 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
587 ["proc_create(?:_data|)", 2],
588 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
589 ["IIO_DEV_ATTR_[A-Z_]+", 1],
590 ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
591 ["SENSOR_TEMPLATE(?:_2|)", 3],
595 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
597 #Create a search pattern for all these functions to speed up a loop below
598 our $mode_perms_search = "";
599 foreach my $entry (@mode_permission_funcs) {
600 $mode_perms_search .= '|' if ($mode_perms_search ne "");
601 $mode_perms_search .= $entry->[0];
603 $mode_perms_search = "(?:${mode_perms_search})";
605 our %deprecated_apis = (
606 "synchronize_rcu_bh" => "synchronize_rcu",
607 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited",
608 "call_rcu_bh" => "call_rcu",
609 "rcu_barrier_bh" => "rcu_barrier",
610 "synchronize_sched" => "synchronize_rcu",
611 "synchronize_sched_expedited" => "synchronize_rcu_expedited",
612 "call_rcu_sched" => "call_rcu",
613 "rcu_barrier_sched" => "rcu_barrier",
614 "get_state_synchronize_sched" => "get_state_synchronize_rcu",
615 "cond_synchronize_sched" => "cond_synchronize_rcu",
618 #Create a search pattern for all these strings to speed up a loop below
619 our $deprecated_apis_search = "";
620 foreach my $entry (keys %deprecated_apis) {
621 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
622 $deprecated_apis_search .= $entry;
624 $deprecated_apis_search = "(?:${deprecated_apis_search})";
626 our $mode_perms_world_writable = qr{
634 our %mode_permission_string_types = (
653 #Create a search pattern for all these strings to speed up a loop below
654 our $mode_perms_string_search = "";
655 foreach my $entry (keys %mode_permission_string_types) {
656 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
657 $mode_perms_string_search .= $entry;
659 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
660 our $multi_mode_perms_string_search = qr{
661 ${single_mode_perms_string_search}
662 (?:\s*\|\s*${single_mode_perms_string_search})*
668 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
675 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
676 $curpos = pos($string);
679 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
681 $to |= $mode_permission_string_types{$match};
682 $val .= '\s*\|\s*' if ($val ne "");
686 $oval =~ s/^\s*\|\s*//;
687 $oval =~ s/\s*\|\s*$//;
688 return sprintf("%04o", $to);
691 our $allowed_asm_includes = qr{(?x:
697 # memory.h: ARM has a custom one
699 # Load common spelling mistakes and build regular expression list.
703 if (open(my $spelling, '<', $spelling_file)) {
704 while (<$spelling>) {
707 $line =~ s/\s*\n?$//g;
710 next if ($line =~ m/^\s*#/);
711 next if ($line =~ m/^\s*$/);
713 my ($suspect, $fix) = split(/\|\|/, $line);
715 $spelling_fix{$suspect} = $fix;
719 warn "No typos will be found - file '$spelling_file': $!\n";
723 if (open(my $spelling, '<', $codespellfile)) {
724 while (<$spelling>) {
727 $line =~ s/\s*\n?$//g;
730 next if ($line =~ m/^\s*#/);
731 next if ($line =~ m/^\s*$/);
732 next if ($line =~ m/, disabled/i);
736 my ($suspect, $fix) = split(/->/, $line);
738 $spelling_fix{$suspect} = $fix;
742 warn "No codespell typos will be found - file '$codespellfile': $!\n";
746 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
749 my ($wordsRef, $file) = @_;
751 if (open(my $words, '<', $file)) {
755 $line =~ s/\s*\n?$//g;
758 next if ($line =~ m/^\s*#/);
759 next if ($line =~ m/^\s*$/);
761 print("$file: '$line' invalid - ignored\n");
765 $$wordsRef .= '|' if (defined $$wordsRef);
776 if (show_type("CONST_STRUCT")) {
777 read_words(\$const_structs, $conststructsfile)
778 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
781 if (defined($typedefsfile)) {
782 my $typeOtherTypedefs;
783 read_words(\$typeOtherTypedefs, $typedefsfile)
784 or warn "No additional types will be considered - file '$typedefsfile': $!\n";
785 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
789 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
790 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
791 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
792 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
793 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
799 (?:$Modifier\s+|const\s+)*
801 (?:typeof|__typeof__)\s*\([^\)]*\)|
805 (?:\s+$Modifier|\s+const)*
807 $NonptrTypeMisordered = qr{
808 (?:$Modifier\s+|const\s+)*
812 (?:\s+$Modifier|\s+const)*
814 $NonptrTypeWithAttr = qr{
815 (?:$Modifier\s+|const\s+)*
817 (?:typeof|__typeof__)\s*\([^\)]*\)|
821 (?:\s+$Modifier|\s+const)*
825 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
826 (?:\s+$Inline|\s+$Modifier)*
828 $TypeMisordered = qr{
829 $NonptrTypeMisordered
830 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
831 (?:\s+$Inline|\s+$Modifier)*
833 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
834 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
838 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
840 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
841 # requires at least perl version v5.10.0
842 # Any use must be runtime checked with $^V
844 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
845 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
846 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
848 our $declaration_macros = qr{(?x:
849 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
850 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
851 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
856 return "" if (!defined($string));
858 while ($string =~ /^\s*\(.*\)\s*$/) {
859 $string =~ s@^\s*\(\s*@@;
860 $string =~ s@\s*\)\s*$@@;
863 $string =~ s@\s+@ @g;
868 sub seed_camelcase_file {
871 return if (!(-f $file));
875 open(my $include_file, '<', "$file")
876 or warn "$P: Can't read '$file' $!\n";
877 my $text = <$include_file>;
878 close($include_file);
880 my @lines = split('\n', $text);
882 foreach my $line (@lines) {
883 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
884 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
886 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
888 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
894 our %maintained_status = ();
896 sub is_maintained_obsolete {
899 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
901 if (!exists($maintained_status{$filename})) {
902 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
905 return $maintained_status{$filename} =~ /obsolete/i;
908 sub is_SPDX_License_valid {
911 return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
913 my $root_path = abs_path($root);
914 my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
915 return 0 if ($status ne "");
919 my $camelcase_seeded = 0;
920 sub seed_camelcase_includes {
921 return if ($camelcase_seeded);
924 my $camelcase_cache = "";
925 my @include_files = ();
927 $camelcase_seeded = 1;
930 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
931 chomp $git_last_include_commit;
932 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
934 my $last_mod_date = 0;
935 $files = `find $root/include -name "*.h"`;
936 @include_files = split('\n', $files);
937 foreach my $file (@include_files) {
938 my $date = POSIX::strftime("%Y%m%d%H%M",
939 localtime((stat $file)[9]));
940 $last_mod_date = $date if ($last_mod_date < $date);
942 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
945 if ($camelcase_cache ne "" && -f $camelcase_cache) {
946 open(my $camelcase_file, '<', "$camelcase_cache")
947 or warn "$P: Can't read '$camelcase_cache' $!\n";
948 while (<$camelcase_file>) {
952 close($camelcase_file);
958 $files = `${git_command} ls-files "include/*.h"`;
959 @include_files = split('\n', $files);
962 foreach my $file (@include_files) {
963 seed_camelcase_file($file);
966 if ($camelcase_cache ne "") {
967 unlink glob ".checkpatch-camelcase.*";
968 open(my $camelcase_file, '>', "$camelcase_cache")
969 or warn "$P: Can't write '$camelcase_cache' $!\n";
970 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
971 print $camelcase_file ("$_\n");
973 close($camelcase_file);
977 sub git_is_single_file {
980 return 0 if ((which("git") eq "") || !(-e "$gitroot"));
982 my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
983 my $count = $output =~ tr/\n//;
984 return $count eq 1 && $output =~ m{^${filename}$};
987 sub git_commit_info {
988 my ($commit, $id, $desc) = @_;
990 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
992 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
993 $output =~ s/^\s*//gm;
994 my @lines = split("\n", $output);
996 return ($id, $desc) if ($#lines < 0);
998 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
999 # Maybe one day convert this block of bash into something that returns
1000 # all matching commit ids, but it's very slow...
1002 # echo "checking commits $1..."
1003 # git rev-list --remotes | grep -i "^$1" |
1004 # while read line ; do
1005 # git log --format='%H %s' -1 $line |
1006 # echo "commit $(cut -c 1-12,41-)"
1008 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1011 $id = substr($lines[0], 0, 12);
1012 $desc = substr($lines[0], 41);
1015 return ($id, $desc);
1018 $chk_signoff = 0 if ($file);
1023 my @fixed_inserted = ();
1024 my @fixed_deleted = ();
1027 # If input is git commits, extract all commits from the commit expressions.
1028 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1029 die "$P: No git repository found\n" if ($git && !-e ".git");
1033 foreach my $commit_expr (@ARGV) {
1035 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1036 $git_range = "-$2 $1";
1037 } elsif ($commit_expr =~ m/\.\./) {
1038 $git_range = "$commit_expr";
1040 $git_range = "-1 $commit_expr";
1042 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1043 foreach my $line (split(/\n/, $lines)) {
1044 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1045 next if (!defined($1) || !defined($2));
1048 unshift(@commits, $sha1);
1049 $git_commits{$sha1} = $subject;
1052 die "$P: no git commits after extraction!\n" if (@commits == 0);
1057 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1058 for my $filename (@ARGV) {
1060 my $is_git_file = git_is_single_file($filename);
1061 my $oldfile = $file;
1062 $file = 1 if ($is_git_file);
1064 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1065 die "$P: $filename: git format-patch failed - $!\n";
1067 open($FILE, '-|', "diff -u /dev/null $filename") ||
1068 die "$P: $filename: diff failed - $!\n";
1069 } elsif ($filename eq '-') {
1070 open($FILE, '<&STDIN');
1072 open($FILE, '<', "$filename") ||
1073 die "$P: $filename: open failed - $!\n";
1075 if ($filename eq '-') {
1076 $vname = 'Your patch';
1078 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1084 push(@rawlines, $_);
1085 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1089 if ($#ARGV > 0 && $quiet == 0) {
1090 print '-' x length($vname) . "\n";
1092 print '-' x length($vname) . "\n";
1095 if (!process($filename)) {
1101 @fixed_inserted = ();
1102 @fixed_deleted = ();
1104 @modifierListFile = ();
1107 $file = $oldfile if ($is_git_file);
1111 hash_show_words(\%use_type, "Used");
1112 hash_show_words(\%ignore_type, "Ignored");
1114 if (!$perl_version_ok) {
1117 NOTE: perl $^V is not modern enough to detect all possible issues.
1118 An upgrade to at least perl $minimum_perl_version is suggested.
1124 NOTE: If any of the errors are false positives, please report
1125 them to the maintainer, see CHECKPATCH in MAINTAINERS.
1132 sub top_of_kernel_tree {
1136 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1137 "README", "Documentation", "arch", "include", "drivers",
1138 "fs", "init", "ipc", "kernel", "lib", "scripts",
1141 foreach my $check (@tree_check) {
1142 if (! -e $root . '/' . $check) {
1150 my ($formatted_email) = @_;
1153 my $name_comment = "";
1157 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1160 $comment = $3 if defined $3;
1161 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1163 $comment = $2 if defined $2;
1164 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1166 $comment = $2 if defined $2;
1167 $formatted_email =~ s/\Q$address\E.*$//;
1168 $name = $formatted_email;
1169 $name = trim($name);
1170 $name =~ s/^\"|\"$//g;
1171 # If there's a name left after stripping spaces and
1172 # leading quotes, and the address doesn't have both
1173 # leading and trailing angle brackets, the address
1175 # "joe smith joe@smith.com" bad
1176 # "joe smith <joe@smith.com" bad
1177 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1184 $comment = trim($comment);
1185 $name = trim($name);
1186 $name =~ s/^\"|\"$//g;
1187 if ($name =~ s/(\s*\([^\)]+\))\s*//) {
1188 $name_comment = trim($1);
1190 $address = trim($address);
1191 $address =~ s/^\<|\>$//g;
1193 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1194 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1195 $name = "\"$name\"";
1198 return ($name, $name_comment, $address, $comment);
1202 my ($name, $name_comment, $address, $comment) = @_;
1204 my $formatted_email;
1206 $name_comment = trim($name_comment);
1207 $comment = trim($comment);
1208 $name = trim($name);
1209 $name =~ s/^\"|\"$//g;
1210 $address = trim($address);
1212 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1213 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1214 $name = "\"$name\"";
1217 if ("$name" eq "") {
1218 $formatted_email = "$address";
1220 $formatted_email = "$name$name_comment <$address>";
1222 $formatted_email .= "$comment";
1223 return $formatted_email;
1226 sub reformat_email {
1229 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1230 return format_email($email_name, $name_comment, $email_address, $comment);
1233 sub same_email_addresses {
1234 my ($email1, $email2, $match_comment) = @_;
1236 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1237 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1239 if ($match_comment != 1) {
1240 return $email1_name eq $email2_name &&
1241 $email1_address eq $email2_address;
1243 return $email1_name eq $email2_name &&
1244 $email1_address eq $email2_address &&
1245 $name1_comment eq $name2_comment &&
1246 $comment1 eq $comment2;
1252 foreach my $path (split(/:/, $ENV{PATH})) {
1253 if (-e "$path/$bin") {
1254 return "$path/$bin";
1264 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1265 if (-e "$path/$conf") {
1266 return "$path/$conf";
1278 for my $c (split(//, $str)) {
1282 for (; ($n % $tabsize) != 0; $n++) {
1294 (my $res = shift) =~ tr/\t/ /c;
1301 # Drop the diff line leader and expand tabs
1303 $line = expand_tabs($line);
1305 # Pick the indent from the front of the line.
1306 my ($white) = ($line =~ /^(\s*)/);
1308 return (length($line), length($white));
1311 my $sanitise_quote = '';
1313 sub sanitise_line_reset {
1314 my ($in_comment) = @_;
1317 $sanitise_quote = '*/';
1319 $sanitise_quote = '';
1332 # Always copy over the diff marker.
1333 $res = substr($line, 0, 1);
1335 for ($off = 1; $off < length($line); $off++) {
1336 $c = substr($line, $off, 1);
1338 # Comments we are whacking completely including the begin
1339 # and end, all to $;.
1340 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1341 $sanitise_quote = '*/';
1343 substr($res, $off, 2, "$;$;");
1347 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1348 $sanitise_quote = '';
1349 substr($res, $off, 2, "$;$;");
1353 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1354 $sanitise_quote = '//';
1356 substr($res, $off, 2, $sanitise_quote);
1361 # A \ in a string means ignore the next character.
1362 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1364 substr($res, $off, 2, 'XX');
1369 if ($c eq "'" || $c eq '"') {
1370 if ($sanitise_quote eq '') {
1371 $sanitise_quote = $c;
1373 substr($res, $off, 1, $c);
1375 } elsif ($sanitise_quote eq $c) {
1376 $sanitise_quote = '';
1380 #print "c<$c> SQ<$sanitise_quote>\n";
1381 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1382 substr($res, $off, 1, $;);
1383 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1384 substr($res, $off, 1, $;);
1385 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1386 substr($res, $off, 1, 'X');
1388 substr($res, $off, 1, $c);
1392 if ($sanitise_quote eq '//') {
1393 $sanitise_quote = '';
1396 # The pathname on a #include may be surrounded by '<' and '>'.
1397 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1398 my $clean = 'X' x length($1);
1399 $res =~ s@\<.*\>@<$clean>@;
1401 # The whole of a #error is a string.
1402 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1403 my $clean = 'X' x length($1);
1404 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1407 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1409 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1415 sub get_quoted_string {
1416 my ($line, $rawline) = @_;
1418 return "" if (!defined($line) || !defined($rawline));
1419 return "" if ($line !~ m/($String)/g);
1420 return substr($rawline, $-[0], $+[0] - $-[0]);
1423 sub ctx_statement_block {
1424 my ($linenr, $remain, $off) = @_;
1425 my $line = $linenr - 1;
1428 my $coff = $off - 1;
1442 @stack = (['', 0]) if ($#stack == -1);
1444 #warn "CSB: blk<$blk> remain<$remain>\n";
1445 # If we are about to drop off the end, pull in more
1448 for (; $remain > 0; $line++) {
1449 last if (!defined $lines[$line]);
1450 next if ($lines[$line] =~ /^-/);
1453 $blk .= $lines[$line] . "\n";
1454 $len = length($blk);
1458 # Bail if there is no further context.
1459 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1463 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1469 $c = substr($blk, $off, 1);
1470 $remainder = substr($blk, $off);
1472 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1474 # Handle nested #if/#else.
1475 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1476 push(@stack, [ $type, $level ]);
1477 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1478 ($type, $level) = @{$stack[$#stack - 1]};
1479 } elsif ($remainder =~ /^#\s*endif\b/) {
1480 ($type, $level) = @{pop(@stack)};
1483 # Statement ends at the ';' or a close '}' at the
1485 if ($level == 0 && $c eq ';') {
1489 # An else is really a conditional as long as its not else if
1490 if ($level == 0 && $coff_set == 0 &&
1491 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1492 $remainder =~ /^(else)(?:\s|{)/ &&
1493 $remainder !~ /^else\s+if\b/) {
1494 $coff = $off + length($1) - 1;
1496 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1497 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1500 if (($type eq '' || $type eq '(') && $c eq '(') {
1504 if ($type eq '(' && $c eq ')') {
1506 $type = ($level != 0)? '(' : '';
1508 if ($level == 0 && $coff < $soff) {
1511 #warn "CSB: mark coff<$coff>\n";
1514 if (($type eq '' || $type eq '{') && $c eq '{') {
1518 if ($type eq '{' && $c eq '}') {
1520 $type = ($level != 0)? '{' : '';
1523 if (substr($blk, $off + 1, 1) eq ';') {
1529 # Preprocessor commands end at the newline unless escaped.
1530 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1538 # We are truly at the end, so shuffle to the next line.
1545 my $statement = substr($blk, $soff, $off - $soff + 1);
1546 my $condition = substr($blk, $soff, $coff - $soff + 1);
1548 #warn "STATEMENT<$statement>\n";
1549 #warn "CONDITION<$condition>\n";
1551 #print "coff<$coff> soff<$off> loff<$loff>\n";
1553 return ($statement, $condition,
1554 $line, $remain + 1, $off - $loff + 1, $level);
1557 sub statement_lines {
1560 # Strip the diff line prefixes and rip blank lines at start and end.
1561 $stmt =~ s/(^|\n)./$1/g;
1565 my @stmt_lines = ($stmt =~ /\n/g);
1567 return $#stmt_lines + 2;
1570 sub statement_rawlines {
1573 my @stmt_lines = ($stmt =~ /\n/g);
1575 return $#stmt_lines + 2;
1578 sub statement_block_size {
1581 $stmt =~ s/(^|\n)./$1/g;
1587 my @stmt_lines = ($stmt =~ /\n/g);
1588 my @stmt_statements = ($stmt =~ /;/g);
1590 my $stmt_lines = $#stmt_lines + 2;
1591 my $stmt_statements = $#stmt_statements + 1;
1593 if ($stmt_lines > $stmt_statements) {
1596 return $stmt_statements;
1600 sub ctx_statement_full {
1601 my ($linenr, $remain, $off) = @_;
1602 my ($statement, $condition, $level);
1606 # Grab the first conditional/block pair.
1607 ($statement, $condition, $linenr, $remain, $off, $level) =
1608 ctx_statement_block($linenr, $remain, $off);
1609 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1610 push(@chunks, [ $condition, $statement ]);
1611 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1612 return ($level, $linenr, @chunks);
1615 # Pull in the following conditional/block pairs and see if they
1616 # could continue the statement.
1618 ($statement, $condition, $linenr, $remain, $off, $level) =
1619 ctx_statement_block($linenr, $remain, $off);
1620 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1621 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1623 push(@chunks, [ $condition, $statement ]);
1626 return ($level, $linenr, @chunks);
1630 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1632 my $start = $linenr - 1;
1639 my @stack = ($level);
1640 for ($line = $start; $remain > 0; $line++) {
1641 next if ($rawlines[$line] =~ /^-/);
1644 $blk .= $rawlines[$line];
1646 # Handle nested #if/#else.
1647 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1648 push(@stack, $level);
1649 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1650 $level = $stack[$#stack - 1];
1651 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1652 $level = pop(@stack);
1655 foreach my $c (split(//, $lines[$line])) {
1656 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1662 if ($c eq $close && $level > 0) {
1664 last if ($level == 0);
1665 } elsif ($c eq $open) {
1670 if (!$outer || $level <= 1) {
1671 push(@res, $rawlines[$line]);
1674 last if ($level == 0);
1677 return ($level, @res);
1679 sub ctx_block_outer {
1680 my ($linenr, $remain) = @_;
1682 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1686 my ($linenr, $remain) = @_;
1688 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1692 my ($linenr, $remain, $off) = @_;
1694 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1697 sub ctx_block_level {
1698 my ($linenr, $remain) = @_;
1700 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1702 sub ctx_statement_level {
1703 my ($linenr, $remain, $off) = @_;
1705 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1708 sub ctx_locate_comment {
1709 my ($first_line, $end_line) = @_;
1711 # If c99 comment on the current line, or the line before or after
1712 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1713 return $current_comment if (defined $current_comment);
1714 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1715 return $current_comment if (defined $current_comment);
1716 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1717 return $current_comment if (defined $current_comment);
1719 # Catch a comment on the end of the line itself.
1720 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1721 return $current_comment if (defined $current_comment);
1723 # Look through the context and try and figure out if there is a
1726 $current_comment = '';
1727 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1728 my $line = $rawlines[$linenr - 1];
1730 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1733 if ($line =~ m@/\*@) {
1736 if (!$in_comment && $current_comment ne '') {
1737 $current_comment = '';
1739 $current_comment .= $line . "\n" if ($in_comment);
1740 if ($line =~ m@\*/@) {
1745 chomp($current_comment);
1746 return($current_comment);
1748 sub ctx_has_comment {
1749 my ($first_line, $end_line) = @_;
1750 my $cmt = ctx_locate_comment($first_line, $end_line);
1752 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1753 ##print "CMMT: $cmt\n";
1755 return ($cmt ne '');
1759 my ($linenr, $cnt) = @_;
1761 my $offset = $linenr - 1;
1766 $line = $rawlines[$offset++];
1767 next if (defined($line) && $line =~ /^-/);
1775 my ($linenr, $lc) = @_;
1777 my $stat_real = raw_line($linenr, 0);
1778 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1779 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1786 my ($linenr, $cnt, $here) = @_;
1788 my $herectx = $here . "\n";
1789 for (my $n = 0; $n < $cnt; $n++) {
1790 $herectx .= raw_line($linenr, $n) . "\n";
1801 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1804 $coded = sprintf("^%c", unpack('C', $2) + 64);
1813 my $av_preprocessor = 0;
1818 sub annotate_reset {
1819 $av_preprocessor = 0;
1821 @av_paren_type = ('E');
1822 $av_pend_colon = 'O';
1825 sub annotate_values {
1826 my ($stream, $type) = @_;
1829 my $var = '_' x length($stream);
1832 print "$stream\n" if ($dbg_values > 1);
1834 while (length($cur)) {
1835 @av_paren_type = ('E') if ($#av_paren_type < 0);
1836 print " <" . join('', @av_paren_type) .
1837 "> <$type> <$av_pending>" if ($dbg_values > 1);
1838 if ($cur =~ /^(\s+)/o) {
1839 print "WS($1)\n" if ($dbg_values > 1);
1840 if ($1 =~ /\n/ && $av_preprocessor) {
1841 $type = pop(@av_paren_type);
1842 $av_preprocessor = 0;
1845 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1846 print "CAST($1)\n" if ($dbg_values > 1);
1847 push(@av_paren_type, $type);
1850 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1851 print "DECLARE($1)\n" if ($dbg_values > 1);
1854 } elsif ($cur =~ /^($Modifier)\s*/) {
1855 print "MODIFIER($1)\n" if ($dbg_values > 1);
1858 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1859 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1860 $av_preprocessor = 1;
1861 push(@av_paren_type, $type);
1867 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1868 print "UNDEF($1)\n" if ($dbg_values > 1);
1869 $av_preprocessor = 1;
1870 push(@av_paren_type, $type);
1872 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1873 print "PRE_START($1)\n" if ($dbg_values > 1);
1874 $av_preprocessor = 1;
1876 push(@av_paren_type, $type);
1877 push(@av_paren_type, $type);
1880 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1881 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1882 $av_preprocessor = 1;
1884 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1888 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1889 print "PRE_END($1)\n" if ($dbg_values > 1);
1891 $av_preprocessor = 1;
1893 # Assume all arms of the conditional end as this
1894 # one does, and continue as if the #endif was not here.
1895 pop(@av_paren_type);
1896 push(@av_paren_type, $type);
1899 } elsif ($cur =~ /^(\\\n)/o) {
1900 print "PRECONT($1)\n" if ($dbg_values > 1);
1902 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1903 print "ATTR($1)\n" if ($dbg_values > 1);
1904 $av_pending = $type;
1907 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1908 print "SIZEOF($1)\n" if ($dbg_values > 1);
1914 } elsif ($cur =~ /^(if|while|for)\b/o) {
1915 print "COND($1)\n" if ($dbg_values > 1);
1919 } elsif ($cur =~/^(case)/o) {
1920 print "CASE($1)\n" if ($dbg_values > 1);
1921 $av_pend_colon = 'C';
1924 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1925 print "KEYWORD($1)\n" if ($dbg_values > 1);
1928 } elsif ($cur =~ /^(\()/o) {
1929 print "PAREN('$1')\n" if ($dbg_values > 1);
1930 push(@av_paren_type, $av_pending);
1934 } elsif ($cur =~ /^(\))/o) {
1935 my $new_type = pop(@av_paren_type);
1936 if ($new_type ne '_') {
1938 print "PAREN('$1') -> $type\n"
1939 if ($dbg_values > 1);
1941 print "PAREN('$1')\n" if ($dbg_values > 1);
1944 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1945 print "FUNC($1)\n" if ($dbg_values > 1);
1949 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1950 if (defined $2 && $type eq 'C' || $type eq 'T') {
1951 $av_pend_colon = 'B';
1952 } elsif ($type eq 'E') {
1953 $av_pend_colon = 'L';
1955 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1958 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1959 print "IDENT($1)\n" if ($dbg_values > 1);
1962 } elsif ($cur =~ /^($Assignment)/o) {
1963 print "ASSIGN($1)\n" if ($dbg_values > 1);
1966 } elsif ($cur =~/^(;|{|})/) {
1967 print "END($1)\n" if ($dbg_values > 1);
1969 $av_pend_colon = 'O';
1971 } elsif ($cur =~/^(,)/) {
1972 print "COMMA($1)\n" if ($dbg_values > 1);
1975 } elsif ($cur =~ /^(\?)/o) {
1976 print "QUESTION($1)\n" if ($dbg_values > 1);
1979 } elsif ($cur =~ /^(:)/o) {
1980 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1982 substr($var, length($res), 1, $av_pend_colon);
1983 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1988 $av_pend_colon = 'O';
1990 } elsif ($cur =~ /^(\[)/o) {
1991 print "CLOSE($1)\n" if ($dbg_values > 1);
1994 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1997 print "OPV($1)\n" if ($dbg_values > 1);
2004 substr($var, length($res), 1, $variant);
2007 } elsif ($cur =~ /^($Operators)/o) {
2008 print "OP($1)\n" if ($dbg_values > 1);
2009 if ($1 ne '++' && $1 ne '--') {
2013 } elsif ($cur =~ /(^.)/o) {
2014 print "C($1)\n" if ($dbg_values > 1);
2017 $cur = substr($cur, length($1));
2018 $res .= $type x length($1);
2022 return ($res, $var);
2026 my ($possible, $line) = @_;
2027 my $notPermitted = qr{(?:
2044 ^(?:typedef|struct|enum)\b
2046 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2047 if ($possible !~ $notPermitted) {
2048 # Check for modifiers.
2049 $possible =~ s/\s*$Storage\s*//g;
2050 $possible =~ s/\s*$Sparse\s*//g;
2051 if ($possible =~ /^\s*$/) {
2053 } elsif ($possible =~ /\s/) {
2054 $possible =~ s/\s*$Type\s*//g;
2055 for my $modifier (split(' ', $possible)) {
2056 if ($modifier !~ $notPermitted) {
2057 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2058 push(@modifierListFile, $modifier);
2063 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2064 push(@typeListFile, $possible);
2068 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2077 $type =~ tr/[a-z]/[A-Z]/;
2079 return defined $use_type{$type} if (scalar keys %use_type > 0);
2081 return !defined $ignore_type{$type};
2085 my ($level, $type, $msg) = @_;
2087 if (!show_type($type) ||
2088 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2093 if ($level eq 'ERROR') {
2095 } elsif ($level eq 'WARNING') {
2101 $output .= $prefix . $level . ':';
2103 $output .= BLUE if ($color);
2104 $output .= "$type:";
2106 $output .= RESET if ($color);
2107 $output .= ' ' . $msg . "\n";
2110 my @lines = split("\n", $output, -1);
2111 splice(@lines, 1, 1);
2112 $output = join("\n", @lines);
2114 $output = (split('\n', $output))[0] . "\n" if ($terse);
2116 push(our @report, $output);
2125 sub fixup_current_range {
2126 my ($lineRef, $offset, $length) = @_;
2128 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2131 my $no = $o + $offset;
2132 my $nl = $l + $length;
2133 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2137 sub fix_inserted_deleted_lines {
2138 my ($linesRef, $insertedRef, $deletedRef) = @_;
2140 my $range_last_linenr = 0;
2141 my $delta_offset = 0;
2146 my $next_insert = 0;
2147 my $next_delete = 0;
2151 my $inserted = @{$insertedRef}[$next_insert++];
2152 my $deleted = @{$deletedRef}[$next_delete++];
2154 foreach my $old_line (@{$linesRef}) {
2156 my $line = $old_line; #don't modify the array
2157 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2159 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2160 $range_last_linenr = $new_linenr;
2161 fixup_current_range(\$line, $delta_offset, 0);
2164 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2165 $deleted = @{$deletedRef}[$next_delete++];
2167 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2170 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2171 push(@lines, ${$inserted}{'LINE'});
2172 $inserted = @{$insertedRef}[$next_insert++];
2174 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2178 push(@lines, $line);
2188 sub fix_insert_line {
2189 my ($linenr, $line) = @_;
2195 push(@fixed_inserted, $inserted);
2198 sub fix_delete_line {
2199 my ($linenr, $line) = @_;
2206 push(@fixed_deleted, $deleted);
2210 my ($type, $msg) = @_;
2212 if (report("ERROR", $type, $msg)) {
2220 my ($type, $msg) = @_;
2222 if (report("WARNING", $type, $msg)) {
2230 my ($type, $msg) = @_;
2232 if ($check && report("CHECK", $type, $msg)) {
2240 sub check_absolute_file {
2241 my ($absolute, $herecurr) = @_;
2242 my $file = $absolute;
2244 ##print "absolute<$absolute>\n";
2246 # See if any suffix of this path is a path within the tree.
2247 while ($file =~ s@^[^/]*/@@) {
2248 if (-f "$root/$file") {
2249 ##print "file<$file>\n";
2257 # It is, so see if the prefix is acceptable.
2258 my $prefix = $absolute;
2259 substr($prefix, -length($file)) = '';
2261 ##print "prefix<$prefix>\n";
2262 if ($prefix ne ".../") {
2263 WARN("USE_RELATIVE_PATH",
2264 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2271 $string =~ s/^\s+|\s+$//g;
2279 $string =~ s/^\s+//;
2287 $string =~ s/\s+$//;
2292 sub string_find_replace {
2293 my ($string, $find, $replace) = @_;
2295 $string =~ s/$find/$replace/g;
2303 my $source_indent = $tabsize;
2304 my $max_spaces_before_tab = $source_indent - 1;
2305 my $spaces_to_tab = " " x $source_indent;
2307 #convert leading spaces to tabs
2308 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2309 #Remove spaces before a tab
2310 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2315 sub pos_last_openparen {
2320 my $opens = $line =~ tr/\(/\(/;
2321 my $closes = $line =~ tr/\)/\)/;
2323 my $last_openparen = 0;
2325 if (($opens == 0) || ($closes >= $opens)) {
2329 my $len = length($line);
2331 for ($pos = 0; $pos < $len; $pos++) {
2332 my $string = substr($line, $pos);
2333 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2334 $pos += length($1) - 1;
2335 } elsif (substr($line, $pos, 1) eq '(') {
2336 $last_openparen = $pos;
2337 } elsif (index($string, '(') == -1) {
2342 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2345 sub get_raw_comment {
2346 my ($line, $rawline) = @_;
2349 for my $i (0 .. (length($line) - 1)) {
2350 if (substr($line, $i, 1) eq "$;") {
2351 $comment .= substr($rawline, $i, 1);
2359 my $filename = shift;
2365 my $stashrawline="";
2375 my $authorsignoff = 0;
2376 my $author_sob = '';
2378 my $is_binding_patch = -1;
2379 my $in_header_lines = $file ? 0 : 1;
2380 my $in_commit_log = 0; #Scanning lines before patch
2381 my $has_patch_separator = 0; #Found a --- line
2382 my $has_commit_log = 0; #Encountered lines before patch
2383 my $commit_log_lines = 0; #Number of commit log lines
2384 my $commit_log_possible_stack_dump = 0;
2385 my $commit_log_long_line = 0;
2386 my $commit_log_has_diff = 0;
2387 my $reported_maintainer_file = 0;
2388 my $non_utf8_charset = 0;
2390 my $last_blank_line = 0;
2391 my $last_coalesced_string_linenr = -1;
2399 # Trace the real file/line as we go.
2404 my $context_function; #undef'd unless there's a known function
2406 my $comment_edge = 0;
2410 my $prev_values = 'E';
2413 my %suppress_ifbraces;
2414 my %suppress_whiletrailers;
2415 my %suppress_export;
2416 my $suppress_statement = 0;
2418 my %signatures = ();
2420 # Pre-scan the patch sanitizing the lines.
2421 # Pre-scan the patch looking for any __setup documentation.
2423 my @setup_docs = ();
2426 my $camelcase_file_seeded = 0;
2428 my $checklicenseline = 1;
2430 sanitise_line_reset();
2432 foreach my $rawline (@rawlines) {
2436 push(@fixed, $rawline) if ($fix);
2438 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2440 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2445 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2454 # Guestimate if this is a continuing comment. Run
2455 # the context looking for a comment "edge". If this
2456 # edge is a close comment then we must be in a comment
2460 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2461 next if (defined $rawlines[$ln - 1] &&
2462 $rawlines[$ln - 1] =~ /^-/);
2464 #print "RAW<$rawlines[$ln - 1]>\n";
2465 last if (!defined $rawlines[$ln - 1]);
2466 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2467 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2472 if (defined $edge && $edge eq '*/') {
2476 # Guestimate if this is a continuing comment. If this
2477 # is the start of a diff block and this line starts
2478 # ' *' then it is very likely a comment.
2479 if (!defined $edge &&
2480 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2485 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2486 sanitise_line_reset($in_comment);
2488 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2489 # Standardise the strings and chars within the input to
2490 # simplify matching -- only bother with positive lines.
2491 $line = sanitise_line($rawline);
2493 push(@lines, $line);
2496 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2501 #print "==>$rawline\n";
2502 #print "-->$line\n";
2504 if ($setup_docs && $line =~ /^\+/) {
2505 push(@setup_docs, $line);
2514 foreach my $line (@lines) {
2517 my $sline = $line; #copy of $line
2518 $sline =~ s/$;/ /g; #with comments as spaces
2520 my $rawline = $rawlines[$linenr - 1];
2521 my $raw_comment = get_raw_comment($line, $rawline);
2523 # check if it's a mode change, rename or start of a patch
2524 if (!$in_commit_log &&
2525 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2526 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2527 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2531 #extract the line range in the file after the patch is applied
2532 if (!$in_commit_log &&
2533 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2536 $first_line = $linenr + 1;
2546 %suppress_ifbraces = ();
2547 %suppress_whiletrailers = ();
2548 %suppress_export = ();
2549 $suppress_statement = 0;
2550 if ($context =~ /\b(\w+)\s*\(/) {
2551 $context_function = $1;
2553 undef $context_function;
2557 # track the line number as we move through the hunk, note that
2558 # new versions of GNU diff omit the leading space on completely
2559 # blank context lines so we need to count that too.
2560 } elsif ($line =~ /^( |\+|$)/) {
2562 $realcnt-- if ($realcnt != 0);
2564 # Measure the line length and indent.
2565 ($length, $indent) = line_stats($rawline);
2567 # Track the previous line.
2568 ($prevline, $stashline) = ($stashline, $line);
2569 ($previndent, $stashindent) = ($stashindent, $indent);
2570 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2572 #warn "line<$line>\n";
2574 } elsif ($realcnt == 1) {
2578 my $hunk_line = ($realcnt != 0);
2580 $here = "#$linenr: " if (!$file);
2581 $here = "#$realline: " if ($file);
2584 # extract the filename as it passes
2585 if ($line =~ /^diff --git.*?(\S+)$/) {
2587 $realfile =~ s@^([^/]*)/@@ if (!$file);
2590 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2592 $realfile =~ s@^([^/]*)/@@ if (!$file);
2596 if (!$file && $tree && $p1_prefix ne '' &&
2597 -e "$root/$p1_prefix") {
2598 WARN("PATCH_PREFIX",
2599 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2602 if ($realfile =~ m@^include/asm/@) {
2603 ERROR("MODIFIED_INCLUDE_ASM",
2604 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2609 #make up the handle for any error we report on this line
2611 $prefix = "$realfile:$realline: "
2614 $prefix = "$filename:$realline: ";
2616 $prefix = "$filename:$linenr: ";
2621 if (is_maintained_obsolete($realfile)) {
2623 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2625 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2628 $check = $check_orig;
2630 $checklicenseline = 1;
2632 if ($realfile !~ /^MAINTAINERS/) {
2633 my $last_binding_patch = $is_binding_patch;
2635 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2637 if (($last_binding_patch != -1) &&
2638 ($last_binding_patch ^ $is_binding_patch)) {
2639 WARN("DT_SPLIT_BINDING_PATCH",
2640 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2647 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2649 my $hereline = "$here\n$rawline\n";
2650 my $herecurr = "$here\n$rawline\n";
2651 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2653 $cnt_lines++ if ($realcnt != 0);
2655 # Verify the existence of a commit log if appropriate
2656 # 2 is used because a $signature is counted in $commit_log_lines
2657 if ($in_commit_log) {
2658 if ($line !~ /^\s*$/) {
2659 $commit_log_lines++; #could be a $signature
2661 } elsif ($has_commit_log && $commit_log_lines < 2) {
2662 WARN("COMMIT_MESSAGE",
2663 "Missing commit description - Add an appropriate one\n");
2664 $commit_log_lines = 2; #warn only once
2667 # Check if the commit log has what seems like a diff which can confuse patch
2668 if ($in_commit_log && !$commit_log_has_diff &&
2669 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2670 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2671 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2672 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2673 ERROR("DIFF_IN_COMMIT_MSG",
2674 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2675 $commit_log_has_diff = 1;
2678 # Check for incorrect file permissions
2679 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2680 my $permhere = $here . "FILE: $realfile\n";
2681 if ($realfile !~ m@scripts/@ &&
2682 $realfile !~ /\.(py|pl|awk|sh)$/) {
2683 ERROR("EXECUTE_PERMISSIONS",
2684 "do not set execute permissions for source files\n" . $permhere);
2688 # Check the patch for a From:
2689 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2691 my $curline = $linenr;
2692 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2695 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2697 $author = reformat_email($author);
2700 # Check the patch for a signoff:
2701 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2704 if ($author ne '' && $authorsignoff != 1) {
2705 if (same_email_addresses($1, $author, 1)) {
2709 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
2710 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
2712 if ($email_address eq $author_address && $email_name eq $author_name) {
2715 } elsif ($email_address eq $author_address) {
2718 } elsif ($email_name eq $author_name) {
2722 my $address1 = $email_address;
2723 my $address2 = $author_address;
2725 if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
2728 if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
2731 if ($address1 eq $address2) {
2739 # Check for patch separator
2740 if ($line =~ /^---$/) {
2741 $has_patch_separator = 1;
2745 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2746 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2747 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2748 $reported_maintainer_file = 1;
2751 # Check signature styles
2752 if (!$in_header_lines &&
2753 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2754 my $space_before = $1;
2756 my $space_after = $3;
2758 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2760 if ($sign_off !~ /$signature_tags/) {
2761 WARN("BAD_SIGN_OFF",
2762 "Non-standard signature: $sign_off\n" . $herecurr);
2764 if (defined $space_before && $space_before ne "") {
2765 if (WARN("BAD_SIGN_OFF",
2766 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2768 $fixed[$fixlinenr] =
2769 "$ucfirst_sign_off $email";
2772 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2773 if (WARN("BAD_SIGN_OFF",
2774 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2776 $fixed[$fixlinenr] =
2777 "$ucfirst_sign_off $email";
2781 if (!defined $space_after || $space_after ne " ") {
2782 if (WARN("BAD_SIGN_OFF",
2783 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2785 $fixed[$fixlinenr] =
2786 "$ucfirst_sign_off $email";
2790 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2791 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
2792 if ($suggested_email eq "") {
2793 ERROR("BAD_SIGN_OFF",
2794 "Unrecognized email address: '$email'\n" . $herecurr);
2796 my $dequoted = $suggested_email;
2797 $dequoted =~ s/^"//;
2798 $dequoted =~ s/" </ </;
2799 # Don't force email to have quotes
2800 # Allow just an angle bracketed address
2801 if (!same_email_addresses($email, $suggested_email, 0)) {
2802 WARN("BAD_SIGN_OFF",
2803 "email address '$email' might be better as '$suggested_email'\n" . $herecurr);
2807 # Check for duplicate signatures
2808 my $sig_nospace = $line;
2809 $sig_nospace =~ s/\s//g;
2810 $sig_nospace = lc($sig_nospace);
2811 if (defined $signatures{$sig_nospace}) {
2812 WARN("BAD_SIGN_OFF",
2813 "Duplicate signature\n" . $herecurr);
2815 $signatures{$sig_nospace} = 1;
2818 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2819 if ($sign_off =~ /^co-developed-by:$/i) {
2820 if ($email eq $author) {
2821 WARN("BAD_SIGN_OFF",
2822 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2824 if (!defined $lines[$linenr]) {
2825 WARN("BAD_SIGN_OFF",
2826 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2827 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2828 WARN("BAD_SIGN_OFF",
2829 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2830 } elsif ($1 ne $email) {
2831 WARN("BAD_SIGN_OFF",
2832 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2837 # Check email subject for common tools that don't need to be mentioned
2838 if ($in_header_lines &&
2839 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2840 WARN("EMAIL_SUBJECT",
2841 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2844 # Check for Gerrit Change-Ids not in any patch context
2845 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2846 ERROR("GERRIT_CHANGE_ID",
2847 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr);
2850 # Check if the commit log is in a possible stack dump
2851 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2852 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2853 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2855 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2856 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2857 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2858 # stack dump address styles
2859 $commit_log_possible_stack_dump = 1;
2862 # Check for line lengths > 75 in commit log, warn once
2863 if ($in_commit_log && !$commit_log_long_line &&
2864 length($line) > 75 &&
2865 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2866 # file delta changes
2867 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2869 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2870 # A Fixes: or Link: line
2871 $commit_log_possible_stack_dump)) {
2872 WARN("COMMIT_LOG_LONG_LINE",
2873 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2874 $commit_log_long_line = 1;
2877 # Reset possible stack dump if a blank line is found
2878 if ($in_commit_log && $commit_log_possible_stack_dump &&
2880 $commit_log_possible_stack_dump = 0;
2883 # Check for git id commit length and improperly formed commit descriptions
2884 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2885 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
2886 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2887 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2888 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2889 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2890 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2891 my $init_char = "c";
2892 my $orig_commit = "";
2899 my $id = '0123456789ab';
2900 my $orig_desc = "commit description";
2901 my $description = "";
2903 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2905 $orig_commit = lc($2);
2906 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2907 $orig_commit = lc($1);
2910 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2911 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2912 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2913 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2914 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2917 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2918 defined $rawlines[$linenr] &&
2919 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2922 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2923 defined $rawlines[$linenr] &&
2924 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2925 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2927 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2928 $orig_desc .= " " . $1;
2932 ($id, $description) = git_commit_info($orig_commit,
2936 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2937 ERROR("GIT_COMMIT_ID",
2938 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2942 # Check for added, moved or deleted files
2943 if (!$reported_maintainer_file && !$in_commit_log &&
2944 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2945 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2946 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2947 (defined($1) || defined($2))))) {
2949 $reported_maintainer_file = 1;
2950 WARN("FILE_PATH_CHANGES",
2951 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2954 # Check for adding new DT bindings not in schema format
2955 if (!$in_commit_log &&
2956 ($line =~ /^new file mode\s*\d+\s*$/) &&
2957 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
2958 WARN("DT_SCHEMA_BINDING_PATCH",
2959 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
2962 # Check for wrappage within a valid hunk of the file
2963 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2964 ERROR("CORRUPTED_PATCH",
2965 "patch seems to be corrupt (line wrapped?)\n" .
2966 $herecurr) if (!$emitted_corrupt++);
2969 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2970 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2971 $rawline !~ m/^$UTF8*$/) {
2972 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2974 my $blank = copy_spacing($rawline);
2975 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2976 my $hereptr = "$hereline$ptr\n";
2979 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2982 # Check if it's the start of a commit log
2983 # (not a header line and we haven't seen the patch filename)
2984 if ($in_header_lines && $realfile =~ /^$/ &&
2985 !($rawline =~ /^\s+(?:\S|$)/ ||
2986 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2987 $in_header_lines = 0;
2989 $has_commit_log = 1;
2992 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2993 # declined it, i.e defined some charset where it is missing.
2994 if ($in_header_lines &&
2995 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2997 $non_utf8_charset = 1;
3000 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3001 $rawline =~ /$NON_ASCII_UTF8/) {
3002 WARN("UTF8_BEFORE_PATCH",
3003 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3006 # Check for absolute kernel paths in commit message
3007 if ($tree && $in_commit_log) {
3008 while ($line =~ m{(?:^|\s)(/\S*)}g) {
3011 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3012 check_absolute_file($1, $herecurr)) {
3015 check_absolute_file($file, $herecurr);
3020 # Check for various typo / spelling mistakes
3021 if (defined($misspellings) &&
3022 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3023 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
3025 my $typo_fix = $spelling_fix{lc($typo)};
3026 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3027 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3028 my $msg_level = \&WARN;
3029 $msg_level = \&CHK if ($file);
3030 if (&{$msg_level}("TYPO_SPELLING",
3031 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
3033 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3038 # check for invalid commit id
3039 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3042 ($id, $description) = git_commit_info($2, undef, undef);
3043 if (!defined($id)) {
3044 WARN("UNKNOWN_COMMIT_ID",
3045 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3049 # check for repeated words separated by a single space
3050 if ($rawline =~ /^\+/ || $in_commit_log) {
3051 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3056 if ($first =~ /(?:struct|union|enum)/) {
3057 pos($rawline) += length($first) + length($second) + 1;
3061 next if ($first ne $second);
3062 next if ($first eq 'long');
3064 if (WARN("REPEATED_WORD",
3065 "Possible repeated word: '$first'\n" . $herecurr) &&
3067 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3071 # if it's a repeated word on consecutive lines in a comment block
3072 if ($prevline =~ /$;+\s*$/ &&
3073 $prevrawline =~ /($word_pattern)\s*$/) {
3075 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3076 if (WARN("REPEATED_WORD",
3077 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3079 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3085 # ignore non-hunk lines and lines being removed
3086 next if (!$hunk_line || $line =~ /^-/);
3088 #trailing whitespace
3089 if ($line =~ /^\+.*\015/) {
3090 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3091 if (ERROR("DOS_LINE_ENDINGS",
3092 "DOS line endings\n" . $herevet) &&
3094 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3096 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3097 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3098 if (ERROR("TRAILING_WHITESPACE",
3099 "trailing whitespace\n" . $herevet) &&
3101 $fixed[$fixlinenr] =~ s/\s+$//;
3107 # Check for FSF mailing addresses.
3108 if ($rawline =~ /\bwrite to the Free/i ||
3109 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3110 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3111 $rawline =~ /\b51\s+Franklin\s+St/i) {
3112 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3113 my $msg_level = \&ERROR;
3114 $msg_level = \&CHK if ($file);
3115 &{$msg_level}("FSF_MAILING_ADDRESS",
3116 "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)
3119 # check for Kconfig help text having a real description
3120 # Only applies when adding the entry originally, after that we do not have
3121 # sufficient context to determine whether it is indeed long enough.
3122 if ($realfile =~ /Kconfig/ &&
3123 # 'choice' is usually the last thing on the line (though
3124 # Kconfig supports named choices), so use a word boundary
3125 # (\b) rather than a whitespace character (\s)
3126 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3129 my $ln = $linenr + 1;
3133 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3134 $f = $lines[$ln - 1];
3135 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3136 $is_end = $lines[$ln - 1] =~ /^\+/;
3138 next if ($f =~ /^-/);
3139 last if (!$file && $f =~ /^\@\@/);
3141 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3143 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3150 next if ($f =~ /^$/);
3152 # This only checks context lines in the patch
3153 # and so hopefully shouldn't trigger false
3154 # positives, even though some of these are
3155 # common words in help texts
3156 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3157 if|endif|menu|endmenu|source)\b/x) {
3163 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3164 WARN("CONFIG_DESCRIPTION",
3165 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3167 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3170 # check MAINTAINERS entries
3171 if ($realfile =~ /^MAINTAINERS$/) {
3172 # check MAINTAINERS entries for the right form
3173 if ($rawline =~ /^\+[A-Z]:/ &&
3174 $rawline !~ /^\+[A-Z]:\t\S/) {
3175 if (WARN("MAINTAINERS_STYLE",
3176 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3178 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3181 # check MAINTAINERS entries for the right ordering too
3182 my $preferred_order = 'MRLSWQBCPTFXNK';
3183 if ($rawline =~ /^\+[A-Z]:/ &&
3184 $prevrawline =~ /^[\+ ][A-Z]:/) {
3185 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3188 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3191 my $curindex = index($preferred_order, $cur);
3192 my $previndex = index($preferred_order, $prev);
3193 if ($curindex < 0) {
3194 WARN("MAINTAINERS_STYLE",
3195 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3197 if ($previndex >= 0 && $curindex < $previndex) {
3198 WARN("MAINTAINERS_STYLE",
3199 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3200 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3201 ($prev eq 'X' && $cur eq 'X')) &&
3202 ($prevval cmp $curval) > 0) {
3203 WARN("MAINTAINERS_STYLE",
3204 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3210 # discourage the use of boolean for type definition attributes of Kconfig options
3211 if ($realfile =~ /Kconfig/ &&
3212 $line =~ /^\+\s*\bboolean\b/) {
3213 WARN("CONFIG_TYPE_BOOLEAN",
3214 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3217 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3218 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3221 'EXTRA_AFLAGS' => 'asflags-y',
3222 'EXTRA_CFLAGS' => 'ccflags-y',
3223 'EXTRA_CPPFLAGS' => 'cppflags-y',
3224 'EXTRA_LDFLAGS' => 'ldflags-y',
3227 WARN("DEPRECATED_VARIABLE",
3228 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3231 # check for DT compatible documentation
3232 if (defined $root &&
3233 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3234 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3236 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3238 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3239 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3241 foreach my $compat (@compats) {
3242 my $compat2 = $compat;
3243 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3244 my $compat3 = $compat;
3245 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3246 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3248 WARN("UNDOCUMENTED_DT_STRING",
3249 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3252 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3254 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3256 WARN("UNDOCUMENTED_DT_STRING",
3257 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3262 # check for using SPDX license tag at beginning of files
3263 if ($realline == $checklicenseline) {
3264 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3265 $checklicenseline = 2;
3266 } elsif ($rawline =~ /^\+/) {
3268 if ($realfile =~ /\.(h|s|S)$/) {
3270 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3272 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3274 } elsif ($realfile =~ /\.rst$/) {
3278 # check SPDX comment style for .[chsS] files
3279 if ($realfile =~ /\.[chsS]$/ &&
3280 $rawline =~ /SPDX-License-Identifier:/ &&
3281 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3282 WARN("SPDX_LICENSE_TAG",
3283 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3286 if ($comment !~ /^$/ &&
3287 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3288 WARN("SPDX_LICENSE_TAG",
3289 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3290 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3291 my $spdx_license = $1;
3292 if (!is_SPDX_License_valid($spdx_license)) {
3293 WARN("SPDX_LICENSE_TAG",
3294 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3296 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3297 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3298 my $msg_level = \&WARN;
3299 $msg_level = \&CHK if ($file);
3300 if (&{$msg_level}("SPDX_LICENSE_TAG",
3302 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3304 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3311 # check for embedded filenames
3312 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3313 WARN("EMBEDDED_FILENAME",
3314 "It's generally not useful to have the filename in the file\n" . $herecurr);
3317 # check we are in a valid source file if not then ignore this hunk
3318 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3320 # check for using SPDX-License-Identifier on the wrong line number
3321 if ($realline != $checklicenseline &&
3322 $rawline =~ /\bSPDX-License-Identifier:/ &&
3323 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3324 WARN("SPDX_LICENSE_TAG",
3325 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3328 # line length limit (with some exclusions)
3330 # There are a few types of lines that may extend beyond $max_line_length:
3331 # logging functions like pr_info that end in a string
3332 # lines with a single string
3333 # #defines that are a single string
3334 # lines with an RFC3986 like URL
3336 # There are 3 different line length message types:
3337 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3338 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3339 # LONG_LINE all other lines longer than $max_line_length
3341 # if LONG_LINE is ignored, the other 2 types are also ignored
3344 if ($line =~ /^\+/ && $length > $max_line_length) {
3345 my $msg_type = "LONG_LINE";
3347 # Check the allowed long line types first
3349 # logging functions that end in a string that starts
3350 # before $max_line_length
3351 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3352 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3355 # lines with only strings (w/ possible termination)
3356 # #defines with only strings
3357 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3358 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3361 # More special cases
3362 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3363 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3366 # URL ($rawline is used in case the URL is in a comment)
3367 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3370 # Otherwise set the alternate message types
3372 # a comment starts before $max_line_length
3373 } elsif ($line =~ /($;[\s$;]*)$/ &&
3374 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3375 $msg_type = "LONG_LINE_COMMENT"
3377 # a quoted string starts before $max_line_length
3378 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3379 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3380 $msg_type = "LONG_LINE_STRING"
3383 if ($msg_type ne "" &&
3384 (show_type("LONG_LINE") || show_type($msg_type))) {
3385 my $msg_level = \&WARN;
3386 $msg_level = \&CHK if ($file);
3387 &{$msg_level}($msg_type,
3388 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3392 # check for adding lines without a newline.
3393 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3394 WARN("MISSING_EOF_NEWLINE",
3395 "adding a line without newline at end of file\n" . $herecurr);
3398 # check we are in a valid source file C or perl if not then ignore this hunk
3399 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3401 # at the beginning of a line any tabs must come first and anything
3402 # more than $tabsize must use tabs.
3403 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3404 $rawline =~ /^\+\s* \s*/) {
3405 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3407 if (ERROR("CODE_INDENT",
3408 "code indent should use tabs where possible\n" . $herevet) &&
3410 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3414 # check for space before tabs.
3415 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3416 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3417 if (WARN("SPACE_BEFORE_TAB",
3418 "please, no space before tabs\n" . $herevet) &&
3420 while ($fixed[$fixlinenr] =~
3421 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3422 while ($fixed[$fixlinenr] =~
3423 s/(^\+.*) +\t/$1\t/) {}
3427 # check for assignments on the start of a line
3428 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3429 CHK("ASSIGNMENT_CONTINUATIONS",
3430 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3433 # check for && or || at the start of a line
3434 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3435 CHK("LOGICAL_CONTINUATIONS",
3436 "Logical continuations should be on the previous line\n" . $hereprev);
3439 # check indentation starts on a tab stop
3440 if ($perl_version_ok &&
3441 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3442 my $indent = length($1);
3443 if ($indent % $tabsize) {
3445 "Statements should start on a tabstop\n" . $herecurr) &&
3447 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3452 # check multi-line statement indentation matches previous line
3453 if ($perl_version_ok &&
3454 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3455 $prevline =~ /^\+(\t*)(.*)$/;
3459 my $pos = pos_last_openparen($rest);
3461 $line =~ /^(\+| )([ \t]*)/;
3464 my $goodtabindent = $oldindent .
3465 "\t" x ($pos / $tabsize) .
3466 " " x ($pos % $tabsize);
3467 my $goodspaceindent = $oldindent . " " x $pos;
3469 if ($newindent ne $goodtabindent &&
3470 $newindent ne $goodspaceindent) {
3472 if (CHK("PARENTHESIS_ALIGNMENT",
3473 "Alignment should match open parenthesis\n" . $hereprev) &&
3474 $fix && $line =~ /^\+/) {
3475 $fixed[$fixlinenr] =~
3476 s/^\+[ \t]*/\+$goodtabindent/;
3482 # check for space after cast like "(int) foo" or "(struct foo) bar"
3483 # avoid checking a few false positives:
3484 # "sizeof(<type>)" or "__alignof__(<type>)"
3485 # function pointer declarations like "(*foo)(int) = bar;"
3486 # structure definitions like "(struct foo) { 0 };"
3487 # multiline macros that define functions
3488 # known attributes or the __attribute__ keyword
3489 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3490 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3492 "No space is necessary after a cast\n" . $herecurr) &&
3494 $fixed[$fixlinenr] =~
3495 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3499 # Block comment styles
3500 # Networking with an initial /*
3501 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3502 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3503 $rawline =~ /^\+[ \t]*\*/ &&
3504 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3505 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3506 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3509 # Block comments use * on subsequent lines
3510 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3511 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3512 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3513 $rawline =~ /^\+/ && #line is new
3514 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3515 WARN("BLOCK_COMMENT_STYLE",
3516 "Block comments use * on subsequent lines\n" . $hereprev);
3519 # Block comments use */ on trailing lines
3520 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3521 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3522 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3523 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3524 WARN("BLOCK_COMMENT_STYLE",
3525 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3528 # Block comment * alignment
3529 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3530 $line =~ /^\+[ \t]*$;/ && #leading comment
3531 $rawline =~ /^\+[ \t]*\*/ && #leading *
3532 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3533 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3534 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3536 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3538 $oldindent = expand_tabs($1);
3540 $prevrawline =~ m@^\+(.*/?)\*@;
3541 $oldindent = expand_tabs($1);
3543 $rawline =~ m@^\+([ \t]*)\*@;
3545 $newindent = expand_tabs($newindent);
3546 if (length($oldindent) ne length($newindent)) {
3547 WARN("BLOCK_COMMENT_STYLE",
3548 "Block comments should align the * on each line\n" . $hereprev);
3552 # check for missing blank lines after struct/union declarations
3553 # with exceptions for various attributes and macros
3554 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3556 !($line =~ /^\+\s*$/ ||
3557 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3558 $line =~ /^\+\s*MODULE_/i ||
3559 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3560 $line =~ /^\+[a-z_]*init/ ||
3561 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3562 $line =~ /^\+\s*DECLARE/ ||
3563 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3564 $line =~ /^\+\s*__setup/)) {
3565 if (CHK("LINE_SPACING",
3566 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3568 fix_insert_line($fixlinenr, "\+");
3572 # check for multiple consecutive blank lines
3573 if ($prevline =~ /^[\+ ]\s*$/ &&
3574 $line =~ /^\+\s*$/ &&
3575 $last_blank_line != ($linenr - 1)) {
3576 if (CHK("LINE_SPACING",
3577 "Please don't use multiple blank lines\n" . $hereprev) &&
3579 fix_delete_line($fixlinenr, $rawline);
3582 $last_blank_line = $linenr;
3585 # check for missing blank lines after declarations
3586 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3587 # actual declarations
3588 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3589 # function pointer declarations
3590 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3591 # foo bar; where foo is some local typedef or #define
3592 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3593 # known declaration macros
3594 $prevline =~ /^\+\s+$declaration_macros/) &&
3595 # for "else if" which can look like "$Ident $Ident"
3596 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3597 # other possible extensions of declaration lines
3598 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3599 # not starting a section or a macro "\" extended line
3600 $prevline =~ /(?:\{\s*|\\)$/) &&
3601 # looks like a declaration
3602 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3603 # function pointer declarations
3604 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3605 # foo bar; where foo is some local typedef or #define
3606 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3607 # known declaration macros
3608 $sline =~ /^\+\s+$declaration_macros/ ||
3609 # start of struct or union or enum
3610 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3611 # start or end of block or continuation of declaration
3612 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3613 # bitfield continuation
3614 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3615 # other possible extensions of declaration lines
3616 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3617 # indentation of previous and current line are the same
3618 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3619 if (WARN("LINE_SPACING",
3620 "Missing a blank line after declarations\n" . $hereprev) &&
3622 fix_insert_line($fixlinenr, "\+");
3626 # check for spaces at the beginning of a line.
3628 # 1) within comments
3629 # 2) indented preprocessor commands
3631 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3632 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3633 if (WARN("LEADING_SPACE",
3634 "please, no spaces at the start of a line\n" . $herevet) &&
3636 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3640 # check we are in a valid C source file if not then ignore this hunk
3641 next if ($realfile !~ /\.(h|c)$/);
3643 # check for unusual line ending [ or (
3644 if ($line =~ /^\+.*([\[\(])\s*$/) {
3645 CHK("OPEN_ENDED_LINE",
3646 "Lines should not end with a '$1'\n" . $herecurr);
3649 # check if this appears to be the start function declaration, save the name
3650 if ($sline =~ /^\+\{\s*$/ &&
3651 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3652 $context_function = $1;
3655 # check if this appears to be the end of function declaration
3656 if ($sline =~ /^\+\}\s*$/) {
3657 undef $context_function;
3660 # check indentation of any line with a bare else
3661 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3662 # if the previous line is a break or return and is indented 1 tab more...
3663 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3664 my $tabs = length($1) + 1;
3665 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3666 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3667 defined $lines[$linenr] &&
3668 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3669 WARN("UNNECESSARY_ELSE",
3670 "else is not generally useful after a break or return\n" . $hereprev);
3674 # check indentation of a line with a break;
3675 # if the previous line is a goto or return and is indented the same # of tabs
3676 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3678 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3679 WARN("UNNECESSARY_BREAK",
3680 "break is not useful after a goto or return\n" . $hereprev);
3684 # check for RCS/CVS revision markers
3685 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3687 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3690 # check for old HOTPLUG __dev<foo> section markings
3691 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3692 WARN("HOTPLUG_SECTION",
3693 "Using $1 is unnecessary\n" . $herecurr);
3696 # Check for potential 'bare' types
3697 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3699 #print "LINE<$line>\n";
3700 if ($linenr > $suppress_statement &&
3701 $realcnt && $sline =~ /.\s*\S/) {
3702 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3703 ctx_statement_block($linenr, $realcnt, 0);
3704 $stat =~ s/\n./\n /g;
3705 $cond =~ s/\n./\n /g;
3707 #print "linenr<$linenr> <$stat>\n";
3708 # If this statement has no statement boundaries within
3709 # it there is no point in retrying a statement scan
3710 # until we hit end of it.
3711 my $frag = $stat; $frag =~ s/;+\s*$//;
3712 if ($frag !~ /(?:{|;)/) {
3713 #print "skip<$line_nr_next>\n";
3714 $suppress_statement = $line_nr_next;
3717 # Find the real next line.
3718 $realline_next = $line_nr_next;
3719 if (defined $realline_next &&
3720 (!defined $lines[$realline_next - 1] ||
3721 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3728 # Ignore goto labels.
3729 if ($s =~ /$Ident:\*$/s) {
3731 # Ignore functions being called
3732 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3734 } elsif ($s =~ /^.\s*else\b/s) {
3736 # declarations always start with types
3737 } 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) {
3740 possible($type, "A:" . $s);
3742 # definitions in global scope can only start with types
3743 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3744 possible($1, "B:" . $s);
3747 # any (foo ... *) is a pointer cast, and foo is a type
3748 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3749 possible($1, "C:" . $s);
3752 # Check for any sort of function declaration.
3753 # int foo(something bar, other baz);
3754 # void (*store_gdt)(x86_descr_ptr *);
3755 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3756 my ($name_len) = length($1);
3759 substr($ctx, 0, $name_len + 1, '');
3760 $ctx =~ s/\)[^\)]*$//;
3762 for my $arg (split(/\s*,\s*/, $ctx)) {
3763 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3765 possible($1, "D:" . $s);
3773 # Checks which may be anchored in the context.
3776 # Check for switch () and associated case and default
3777 # statements should be at the same indent.
3778 if ($line=~/\bswitch\s*\(.*\)/) {
3781 my @ctx = ctx_block_outer($linenr, $realcnt);
3783 for my $ctx (@ctx) {
3784 my ($clen, $cindent) = line_stats($ctx);
3785 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3786 $indent != $cindent) {
3787 $err .= "$sep$ctx\n";
3794 ERROR("SWITCH_CASE_INDENT_LEVEL",
3795 "switch and case should be at the same indent\n$hereline$err");
3799 # if/while/etc brace do not go on next line, unless defining a do while loop,
3800 # or if that brace on the next line is for something else
3801 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3802 my $pre_ctx = "$1$2";
3804 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3806 if ($line =~ /^\+\t{6,}/) {
3807 WARN("DEEP_INDENTATION",
3808 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3811 my $ctx_cnt = $realcnt - $#ctx - 1;
3812 my $ctx = join("\n", @ctx);
3814 my $ctx_ln = $linenr;
3815 my $ctx_skip = $realcnt;
3817 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3818 defined $lines[$ctx_ln - 1] &&
3819 $lines[$ctx_ln - 1] =~ /^-/)) {
3820 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3821 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3825 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3826 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3828 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3830 "that open brace { should be on the previous line\n" .
3831 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3833 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3834 $ctx =~ /\)\s*\;\s*$/ &&
3835 defined $lines[$ctx_ln - 1])
3837 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3838 if ($nindent > $indent) {
3839 WARN("TRAILING_SEMICOLON",
3840 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3841 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3846 # Check relative indent for conditionals and blocks.
3847 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3848 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3849 ctx_statement_block($linenr, $realcnt, 0)
3850 if (!defined $stat);
3851 my ($s, $c) = ($stat, $cond);
3853 substr($s, 0, length($c), '');
3855 # remove inline comments
3859 # Find out how long the conditional actually is.
3860 my @newlines = ($c =~ /\n/gs);
3861 my $cond_lines = 1 + $#newlines;
3863 # Make sure we remove the line prefixes as we have
3864 # none on the first line, and are going to readd them
3867 while ($s =~ /\n\s+\\\n/) {
3868 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3871 # We want to check the first line inside the block
3872 # starting at the end of the conditional, so remove:
3873 # 1) any blank line termination
3874 # 2) any opening brace { on end of the line
3876 my $continuation = 0;
3878 $s =~ s/^.*\bdo\b//;
3880 if ($s =~ s/^\s*\\//) {
3883 if ($s =~ s/^\s*?\n//) {
3888 # Also ignore a loop construct at the end of a
3889 # preprocessor statement.
3890 if (($prevline =~ /^.\s*#\s*define\s/ ||
3891 $prevline =~ /\\\s*$/) && $continuation == 0) {
3897 while ($cond_ptr != $cond_lines) {
3898 $cond_ptr = $cond_lines;
3900 # If we see an #else/#elif then the code
3902 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3907 # 1) blank lines, they should be at 0,
3908 # 2) preprocessor lines, and
3910 if ($continuation ||
3912 $s =~ /^\s*#\s*?/ ||
3913 $s =~ /^\s*$Ident\s*:/) {
3914 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3915 if ($s =~ s/^.*?\n//) {
3921 my (undef, $sindent) = line_stats("+" . $s);
3922 my $stat_real = raw_line($linenr, $cond_lines);
3924 # Check if either of these lines are modified, else
3925 # this is not this patch's fault.
3926 if (!defined($stat_real) ||
3927 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3930 if (defined($stat_real) && $cond_lines > 1) {
3931 $stat_real = "[...]\n$stat_real";
3934 #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";
3936 if ($check && $s ne '' &&
3937 (($sindent % $tabsize) != 0 ||
3938 ($sindent < $indent) ||
3939 ($sindent == $indent &&
3940 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3941 ($sindent > $indent + $tabsize))) {
3942 WARN("SUSPECT_CODE_INDENT",
3943 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3947 # Track the 'values' across context and added lines.
3948 my $opline = $line; $opline =~ s/^./ /;
3949 my ($curr_values, $curr_vars) =
3950 annotate_values($opline . "\n", $prev_values);
3951 $curr_values = $prev_values . $curr_values;
3953 my $outline = $opline; $outline =~ s/\t/ /g;
3954 print "$linenr > .$outline\n";
3955 print "$linenr > $curr_values\n";
3956 print "$linenr > $curr_vars\n";
3958 $prev_values = substr($curr_values, -1);
3960 #ignore lines not being added
3961 next if ($line =~ /^[^\+]/);
3963 # check for self assignments used to avoid compiler warnings
3964 # e.g.: int foo = foo, *bar = NULL;
3965 # struct foo bar = *(&(bar));
3966 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
3968 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
3969 WARN("SELF_ASSIGNMENT",
3970 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
3974 # check for dereferences that span multiple lines
3975 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3976 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3977 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3979 $line =~ /^.\s*($Lval)/;
3982 WARN("MULTILINE_DEREFERENCE",
3983 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3986 # check for declarations of signed or unsigned without int
3987 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3990 $var = "" if (!defined $var);
3991 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3995 $pointer = "" if (!defined $pointer);
3997 if (WARN("UNSPECIFIED_INT",
3998 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4000 my $decl = trim($sign) . " int ";
4001 my $comp_pointer = $pointer;
4002 $comp_pointer =~ s/\s//g;
4003 $decl .= $comp_pointer;
4004 $decl = rtrim($decl) if ($var eq "");
4005 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4010 # TEST: allow direct testing of the type matcher.
4012 if ($line =~ /^.\s*$Declare\s*$/) {
4014 "TEST: is type\n" . $herecurr);
4015 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4016 ERROR("TEST_NOT_TYPE",
4017 "TEST: is not type ($1 is)\n". $herecurr);
4021 # TEST: allow direct testing of the attribute matcher.
4023 if ($line =~ /^.\s*$Modifier\s*$/) {
4025 "TEST: is attr\n" . $herecurr);
4026 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4027 ERROR("TEST_NOT_ATTR",
4028 "TEST: is not attr ($1 is)\n". $herecurr);
4033 # check for initialisation to aggregates open brace on the next line
4034 if ($line =~ /^.\s*{/ &&
4035 $prevline =~ /(?:^|[^=])=\s*$/) {
4036 if (ERROR("OPEN_BRACE",
4037 "that open brace { should be on the previous line\n" . $hereprev) &&
4038 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4039 fix_delete_line($fixlinenr - 1, $prevrawline);
4040 fix_delete_line($fixlinenr, $rawline);
4041 my $fixedline = $prevrawline;
4042 $fixedline =~ s/\s*=\s*$/ = {/;
4043 fix_insert_line($fixlinenr, $fixedline);
4045 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4046 fix_insert_line($fixlinenr, $fixedline);
4051 # Checks which are anchored on the added line.
4054 # check for malformed paths in #include statements (uses RAW line)
4055 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4057 if ($path =~ m{//}) {
4058 ERROR("MALFORMED_INCLUDE",
4059 "malformed #include filename\n" . $herecurr);
4061 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4062 ERROR("UAPI_INCLUDE",
4063 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4067 # no C99 // comments
4068 if ($line =~ m{//}) {
4069 if (ERROR("C99_COMMENTS",
4070 "do not use C99 // comments\n" . $herecurr) &&
4072 my $line = $fixed[$fixlinenr];
4073 if ($line =~ /\/\/(.*)$/) {
4074 my $comment = trim($1);
4075 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4079 # Remove C99 comments.
4081 $opline =~ s@//.*@@;
4083 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4084 # the whole statement.
4085 #print "APW <$lines[$realline_next - 1]>\n";
4086 if (defined $realline_next &&
4087 exists $lines[$realline_next - 1] &&
4088 !defined $suppress_export{$realline_next} &&
4089 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4090 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4091 # Handle definitions which produce identifiers with
4094 # EXPORT_SYMBOL(something_foo);
4096 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4097 $name =~ /^${Ident}_$2/) {
4098 #print "FOO C name<$name>\n";
4099 $suppress_export{$realline_next} = 1;
4101 } elsif ($stat !~ /(?:
4103 ^.DEFINE_$Ident\(\Q$name\E\)|
4104 ^.DECLARE_$Ident\(\Q$name\E\)|
4105 ^.LIST_HEAD\(\Q$name\E\)|
4106 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4107 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4109 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4110 $suppress_export{$realline_next} = 2;
4112 $suppress_export{$realline_next} = 1;
4115 if (!defined $suppress_export{$linenr} &&
4116 $prevline =~ /^.\s*$/ &&
4117 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4118 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4119 #print "FOO B <$lines[$linenr - 1]>\n";
4120 $suppress_export{$linenr} = 2;
4122 if (defined $suppress_export{$linenr} &&
4123 $suppress_export{$linenr} == 2) {
4124 WARN("EXPORT_SYMBOL",
4125 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4128 # check for global initialisers.
4129 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4130 if (ERROR("GLOBAL_INITIALISERS",
4131 "do not initialise globals to $1\n" . $herecurr) &&
4133 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4136 # check for static initialisers.
4137 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4138 if (ERROR("INITIALISED_STATIC",
4139 "do not initialise statics to $1\n" .
4142 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4146 # check for misordered declarations of char/short/int/long with signed/unsigned
4147 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4149 WARN("MISORDERED_TYPE",
4150 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4153 # check for unnecessary <signed> int declarations of short/long/long long
4154 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4155 my $type = trim($1);
4156 next if ($type !~ /\bint\b/);
4157 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4158 my $new_type = $type;
4159 $new_type =~ s/\b\s*int\s*\b/ /;
4160 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4161 $new_type =~ s/^const\s+//;
4162 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4163 $new_type = "const $new_type" if ($type =~ /^const\b/);
4164 $new_type =~ s/\s+/ /g;
4165 $new_type = trim($new_type);
4166 if (WARN("UNNECESSARY_INT",
4167 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4169 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4173 # check for static const char * arrays.
4174 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4175 WARN("STATIC_CONST_CHAR_ARRAY",
4176 "static const char * array should probably be static const char * const\n" .
4180 # check for initialized const char arrays that should be static const
4181 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4182 if (WARN("STATIC_CONST_CHAR_ARRAY",
4183 "const array should probably be static const\n" . $herecurr) &&
4185 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4189 # check for static char foo[] = "bar" declarations.
4190 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4191 WARN("STATIC_CONST_CHAR_ARRAY",
4192 "static char array declaration should probably be static const char\n" .
4196 # check for const <foo> const where <foo> is not a pointer or array type
4197 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4199 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4201 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4202 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4204 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4208 # check for non-global char *foo[] = {"bar", ...} declarations.
4209 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4210 WARN("STATIC_CONST_CHAR_ARRAY",
4211 "char * array declaration might be better as static const\n" .
4215 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4216 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4218 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4220 if (WARN("ARRAY_SIZE",
4221 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4223 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4228 # check for function declarations without arguments like "int foo()"
4229 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4230 if (ERROR("FUNCTION_WITHOUT_ARGS",
4231 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4233 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4237 # check for new typedefs, only function parameters and sparse annotations
4239 if ($line =~ /\btypedef\s/ &&
4240 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4241 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4242 $line !~ /\b$typeTypedefs\b/ &&
4243 $line !~ /\b__bitwise\b/) {
4244 WARN("NEW_TYPEDEFS",
4245 "do not add new typedefs\n" . $herecurr);
4248 # * goes on variable not on type
4250 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4252 my ($ident, $from, $to) = ($1, $2, $2);
4254 # Should start with a space.
4255 $to =~ s/^(\S)/ $1/;
4256 # Should not end with a space.
4258 # '*'s should not have spaces between.
4259 while ($to =~ s/\*\s+\*/\*\*/) {
4262 ## print "1: from<$from> to<$to> ident<$ident>\n";
4264 if (ERROR("POINTER_LOCATION",
4265 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4267 my $sub_from = $ident;
4268 my $sub_to = $ident;
4269 $sub_to =~ s/\Q$from\E/$to/;
4270 $fixed[$fixlinenr] =~
4271 s@\Q$sub_from\E@$sub_to@;
4275 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4277 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4279 # Should start with a space.
4280 $to =~ s/^(\S)/ $1/;
4281 # Should not end with a space.
4283 # '*'s should not have spaces between.
4284 while ($to =~ s/\*\s+\*/\*\*/) {
4286 # Modifiers should have spaces.
4287 $to =~ s/(\b$Modifier$)/$1 /;
4289 ## print "2: from<$from> to<$to> ident<$ident>\n";
4290 if ($from ne $to && $ident !~ /^$Modifier$/) {
4291 if (ERROR("POINTER_LOCATION",
4292 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4295 my $sub_from = $match;
4296 my $sub_to = $match;
4297 $sub_to =~ s/\Q$from\E/$to/;
4298 $fixed[$fixlinenr] =~
4299 s@\Q$sub_from\E@$sub_to@;
4304 # avoid BUG() or BUG_ON()
4305 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4306 my $msg_level = \&WARN;
4307 $msg_level = \&CHK if ($file);
4308 &{$msg_level}("AVOID_BUG",
4309 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4312 # avoid LINUX_VERSION_CODE
4313 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4314 WARN("LINUX_VERSION_CODE",
4315 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4318 # check for uses of printk_ratelimit
4319 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4320 WARN("PRINTK_RATELIMITED",
4321 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4324 # printk should use KERN_* levels
4325 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4326 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4327 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4330 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4332 my $level = lc($orig);
4333 $level = "warn" if ($level eq "warning");
4334 my $level2 = $level;
4335 $level2 = "dbg" if ($level eq "debug");
4336 WARN("PREFER_PR_LEVEL",
4337 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4340 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4342 my $level = lc($orig);
4343 $level = "warn" if ($level eq "warning");
4344 $level = "dbg" if ($level eq "debug");
4345 WARN("PREFER_DEV_LEVEL",
4346 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4349 # trace_printk should not be used in production code.
4350 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4351 WARN("TRACE_PRINTK",
4352 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4355 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4356 # number of false positives, but assembly files are not checked, so at
4357 # least the arch entry code will not trigger this warning.
4358 if ($line =~ /\bENOSYS\b/) {
4360 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4363 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4364 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4365 # Similarly to ENOSYS warning a small number of false positives is expected.
4366 if (!$file && $line =~ /\bENOTSUPP\b/) {
4367 if (WARN("ENOTSUPP",
4368 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4370 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4374 # function brace can't be on same line, except for #defines of do while,
4375 # or if closed on same line
4376 if ($perl_version_ok &&
4377 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4378 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4380 if (ERROR("OPEN_BRACE",
4381 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4383 fix_delete_line($fixlinenr, $rawline);
4384 my $fixed_line = $rawline;
4385 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4388 fix_insert_line($fixlinenr, ltrim($line1));
4389 fix_insert_line($fixlinenr, "\+{");
4390 if ($line2 !~ /^\s*$/) {
4391 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4396 # open braces for enum, union and struct go on the same line.
4397 if ($line =~ /^.\s*{/ &&
4398 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4399 if (ERROR("OPEN_BRACE",
4400 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4401 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4402 fix_delete_line($fixlinenr - 1, $prevrawline);
4403 fix_delete_line($fixlinenr, $rawline);
4404 my $fixedline = rtrim($prevrawline) . " {";
4405 fix_insert_line($fixlinenr, $fixedline);
4406 $fixedline = $rawline;
4407 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4408 if ($fixedline !~ /^\+\s*$/) {
4409 fix_insert_line($fixlinenr, $fixedline);
4414 # missing space after union, struct or enum definition
4415 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4417 "missing space after $1 definition\n" . $herecurr) &&
4419 $fixed[$fixlinenr] =~
4420 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4424 # Function pointer declarations
4425 # check spacing between type, funcptr, and args
4426 # canonical declaration is "type (*funcptr)(args...)"
4427 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4429 my $pre_pointer_space = $2;
4430 my $post_pointer_space = $3;
4432 my $post_funcname_space = $5;
4433 my $pre_args_space = $6;
4435 # the $Declare variable will capture all spaces after the type
4436 # so check it for a missing trailing missing space but pointer return types
4437 # don't need a space so don't warn for those.
4438 my $post_declare_space = "";
4439 if ($declare =~ /(\s+)$/) {
4440 $post_declare_space = $1;
4441 $declare = rtrim($declare);
4443 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4445 "missing space after return type\n" . $herecurr);
4446 $post_declare_space = " ";
4449 # unnecessary space "type (*funcptr)(args...)"
4450 # This test is not currently implemented because these declarations are
4452 # int foo(int bar, ...)
4453 # and this is form shouldn't/doesn't generate a checkpatch warning.
4455 # elsif ($declare =~ /\s{2,}$/) {
4457 # "Multiple spaces after return type\n" . $herecurr);
4460 # unnecessary space "type ( *funcptr)(args...)"
4461 if (defined $pre_pointer_space &&
4462 $pre_pointer_space =~ /^\s/) {
4464 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4467 # unnecessary space "type (* funcptr)(args...)"
4468 if (defined $post_pointer_space &&
4469 $post_pointer_space =~ /^\s/) {
4471 "Unnecessary space before function pointer name\n" . $herecurr);
4474 # unnecessary space "type (*funcptr )(args...)"
4475 if (defined $post_funcname_space &&
4476 $post_funcname_space =~ /^\s/) {
4478 "Unnecessary space after function pointer name\n" . $herecurr);
4481 # unnecessary space "type (*funcptr) (args...)"
4482 if (defined $pre_args_space &&
4483 $pre_args_space =~ /^\s/) {
4485 "Unnecessary space before function pointer arguments\n" . $herecurr);
4488 if (show_type("SPACING") && $fix) {
4489 $fixed[$fixlinenr] =~
4490 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4494 # check for spacing round square brackets; allowed:
4495 # 1. with a type on the left -- int [] a;
4496 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4497 # 3. inside a curly brace -- = { [0...10] = 5 }
4498 while ($line =~ /(.*?\s)\[/g) {
4499 my ($where, $prefix) = ($-[1], $1);
4500 if ($prefix !~ /$Type\s+$/ &&
4501 ($where != 0 || $prefix !~ /^.\s+$/) &&
4502 $prefix !~ /[{,:]\s+$/) {
4503 if (ERROR("BRACKET_SPACE",
4504 "space prohibited before open square bracket '['\n" . $herecurr) &&
4506 $fixed[$fixlinenr] =~
4507 s/^(\+.*?)\s+\[/$1\[/;
4512 # check for spaces between functions and their parentheses.
4513 while ($line =~ /($Ident)\s+\(/g) {
4515 my $ctx_before = substr($line, 0, $-[1]);
4516 my $ctx = "$ctx_before$name";
4518 # Ignore those directives where spaces _are_ permitted.
4520 if|for|while|switch|return|case|
4521 volatile|__volatile__|
4522 __attribute__|format|__extension__|
4525 # cpp #define statements have non-optional spaces, ie
4526 # if there is a space between the name and the open
4527 # parenthesis it is simply not a parameter group.
4528 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4530 # cpp #elif statement condition may start with a (
4531 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4533 # If this whole things ends with a type its most
4534 # likely a typedef for a function.
4535 } elsif ($ctx =~ /$Type$/) {
4539 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4541 $fixed[$fixlinenr] =~
4542 s/\b$name\s+\(/$name\(/;
4547 # Check operator spacing.
4548 if (!($line=~/\#\s*include/)) {
4549 my $fixed_line = "";
4553 <<=|>>=|<=|>=|==|!=|
4554 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4555 =>|->|<<|>>|<|>|=|!|~|
4556 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4559 my @elements = split(/($ops|;)/, $opline);
4561 ## print("element count: <" . $#elements . ">\n");
4562 ## foreach my $el (@elements) {
4563 ## print("el: <$el>\n");
4566 my @fix_elements = ();
4569 foreach my $el (@elements) {
4570 push(@fix_elements, substr($rawline, $off, length($el)));
4571 $off += length($el);
4576 my $blank = copy_spacing($opline);
4577 my $last_after = -1;
4579 for (my $n = 0; $n < $#elements; $n += 2) {
4581 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4583 ## print("n: <$n> good: <$good>\n");
4585 $off += length($elements[$n]);
4587 # Pick up the preceding and succeeding characters.
4588 my $ca = substr($opline, 0, $off);
4590 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4591 $cc = substr($opline, $off + length($elements[$n + 1]));
4593 my $cb = "$ca$;$cc";
4596 $a = 'V' if ($elements[$n] ne '');
4597 $a = 'W' if ($elements[$n] =~ /\s$/);
4598 $a = 'C' if ($elements[$n] =~ /$;$/);
4599 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4600 $a = 'O' if ($elements[$n] eq '');
4601 $a = 'E' if ($ca =~ /^\s*$/);
4603 my $op = $elements[$n + 1];
4606 if (defined $elements[$n + 2]) {
4607 $c = 'V' if ($elements[$n + 2] ne '');
4608 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4609 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4610 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4611 $c = 'O' if ($elements[$n + 2] eq '');
4612 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4617 my $ctx = "${a}x${c}";
4619 my $at = "(ctx:$ctx)";
4621 my $ptr = substr($blank, 0, $off) . "^";
4622 my $hereptr = "$hereline$ptr\n";
4624 # Pull out the value of this operator.
4625 my $op_type = substr($curr_values, $off + 1, 1);
4627 # Get the full operator variant.
4628 my $opv = $op . substr($curr_vars, $off, 1);
4630 # Ignore operators passed as parameters.
4631 if ($op_type ne 'V' &&
4632 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4635 # } elsif ($op =~ /^$;+$/) {
4637 # ; should have either the end of line or a space or \ after it
4638 } elsif ($op eq ';') {
4639 if ($ctx !~ /.x[WEBC]/ &&
4640 $cc !~ /^\\/ && $cc !~ /^;/) {
4641 if (ERROR("SPACING",
4642 "space required after that '$op' $at\n" . $hereptr)) {
4643 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4649 } elsif ($op eq '//') {
4651 # : when part of a bitfield
4652 } elsif ($opv eq ':B') {
4653 # skip the bitfield test for now
4657 } elsif ($op eq '->') {
4658 if ($ctx =~ /Wx.|.xW/) {
4659 if (ERROR("SPACING",
4660 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4661 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4662 if (defined $fix_elements[$n + 2]) {
4663 $fix_elements[$n + 2] =~ s/^\s+//;
4669 # , must not have a space before and must have a space on the right.
4670 } elsif ($op eq ',') {
4671 my $rtrim_before = 0;
4672 my $space_after = 0;
4673 if ($ctx =~ /Wx./) {
4674 if (ERROR("SPACING",
4675 "space prohibited before that '$op' $at\n" . $hereptr)) {
4680 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4681 if (ERROR("SPACING",
4682 "space required after that '$op' $at\n" . $hereptr)) {
4688 if ($rtrim_before || $space_after) {
4689 if ($rtrim_before) {
4690 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4692 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4699 # '*' as part of a type definition -- reported already.
4700 } elsif ($opv eq '*_') {
4701 #warn "'*' is part of type\n";
4703 # unary operators should have a space before and
4704 # none after. May be left adjacent to another
4705 # unary operator, or a cast
4706 } elsif ($op eq '!' || $op eq '~' ||
4707 $opv eq '*U' || $opv eq '-U' ||
4708 $opv eq '&U' || $opv eq '&&U') {
4709 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4710 if (ERROR("SPACING",
4711 "space required before that '$op' $at\n" . $hereptr)) {
4712 if ($n != $last_after + 2) {
4713 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4718 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4719 # A unary '*' may be const
4721 } elsif ($ctx =~ /.xW/) {
4722 if (ERROR("SPACING",
4723 "space prohibited after that '$op' $at\n" . $hereptr)) {
4724 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4725 if (defined $fix_elements[$n + 2]) {
4726 $fix_elements[$n + 2] =~ s/^\s+//;
4732 # unary ++ and unary -- are allowed no space on one side.
4733 } elsif ($op eq '++' or $op eq '--') {
4734 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4735 if (ERROR("SPACING",
4736 "space required one side of that '$op' $at\n" . $hereptr)) {
4737 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4741 if ($ctx =~ /Wx[BE]/ ||
4742 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4743 if (ERROR("SPACING",
4744 "space prohibited before that '$op' $at\n" . $hereptr)) {
4745 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4749 if ($ctx =~ /ExW/) {
4750 if (ERROR("SPACING",
4751 "space prohibited after that '$op' $at\n" . $hereptr)) {
4752 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4753 if (defined $fix_elements[$n + 2]) {
4754 $fix_elements[$n + 2] =~ s/^\s+//;
4760 # << and >> may either have or not have spaces both sides
4761 } elsif ($op eq '<<' or $op eq '>>' or
4762 $op eq '&' or $op eq '^' or $op eq '|' or
4763 $op eq '+' or $op eq '-' or
4764 $op eq '*' or $op eq '/' or
4768 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4770 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4771 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4772 $fix_elements[$n + 2] =~ s/^\s+//;
4775 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4777 "space preferred before that '$op' $at\n" . $hereptr)) {
4778 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4782 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4783 if (ERROR("SPACING",
4784 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4785 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4786 if (defined $fix_elements[$n + 2]) {
4787 $fix_elements[$n + 2] =~ s/^\s+//;
4793 # A colon needs no spaces before when it is
4794 # terminating a case value or a label.
4795 } elsif ($opv eq ':C' || $opv eq ':L') {
4796 if ($ctx =~ /Wx./) {
4797 if (ERROR("SPACING",
4798 "space prohibited before that '$op' $at\n" . $hereptr)) {
4799 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4804 # All the others need spaces both sides.
4805 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4808 # Ignore email addresses <foo@bar>
4810 $cc =~ /^\S+\@\S+>/) ||
4812 $ca =~ /<\S+\@\S+$/))
4817 # for asm volatile statements
4818 # ignore a colon with another
4819 # colon immediately before or after
4821 ($ca =~ /:$/ || $cc =~ /^:/)) {
4825 # messages are ERROR, but ?: are CHK
4827 my $msg_level = \&ERROR;
4828 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4830 if (&{$msg_level}("SPACING",
4831 "spaces required around that '$op' $at\n" . $hereptr)) {
4832 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4833 if (defined $fix_elements[$n + 2]) {
4834 $fix_elements[$n + 2] =~ s/^\s+//;
4840 $off += length($elements[$n + 1]);
4842 ## print("n: <$n> GOOD: <$good>\n");
4844 $fixed_line = $fixed_line . $good;
4847 if (($#elements % 2) == 0) {
4848 $fixed_line = $fixed_line . $fix_elements[$#elements];
4851 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4852 $fixed[$fixlinenr] = $fixed_line;
4858 # check for whitespace before a non-naked semicolon
4859 if ($line =~ /^\+.*\S\s+;\s*$/) {
4861 "space prohibited before semicolon\n" . $herecurr) &&
4863 1 while $fixed[$fixlinenr] =~
4864 s/^(\+.*\S)\s+;/$1;/;
4868 # check for multiple assignments
4869 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4870 CHK("MULTIPLE_ASSIGNMENTS",
4871 "multiple assignments should be avoided\n" . $herecurr);
4874 ## # check for multiple declarations, allowing for a function declaration
4876 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4877 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4879 ## # Remove any bracketed sections to ensure we do not
4880 ## # falsly report the parameters of functions.
4882 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4884 ## if ($ln =~ /,/) {
4885 ## WARN("MULTIPLE_DECLARATION",
4886 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4890 #need space before brace following if, while, etc
4891 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4892 $line =~ /\b(?:else|do)\{/) {
4893 if (ERROR("SPACING",
4894 "space required before the open brace '{'\n" . $herecurr) &&
4896 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4900 ## # check for blank lines before declarations
4901 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4902 ## $prevrawline =~ /^.\s*$/) {
4904 ## "No blank lines before declarations\n" . $hereprev);
4908 # closing brace should have a space following it when it has anything
4910 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4911 if (ERROR("SPACING",
4912 "space required after that close brace '}'\n" . $herecurr) &&
4914 $fixed[$fixlinenr] =~
4915 s/}((?!(?:,|;|\)))\S)/} $1/;
4919 # check spacing on square brackets
4920 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4921 if (ERROR("SPACING",
4922 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4924 $fixed[$fixlinenr] =~
4928 if ($line =~ /\s\]/) {
4929 if (ERROR("SPACING",
4930 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4932 $fixed[$fixlinenr] =~
4937 # check spacing on parentheses
4938 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4939 $line !~ /for\s*\(\s+;/) {
4940 if (ERROR("SPACING",
4941 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4943 $fixed[$fixlinenr] =~
4947 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4948 $line !~ /for\s*\(.*;\s+\)/ &&
4949 $line !~ /:\s+\)/) {
4950 if (ERROR("SPACING",
4951 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4953 $fixed[$fixlinenr] =~
4958 # check unnecessary parentheses around addressof/dereference single $Lvals
4959 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4961 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4963 if (CHK("UNNECESSARY_PARENTHESES",
4964 "Unnecessary parentheses around $var\n" . $herecurr) &&
4966 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4970 # check for unnecessary parentheses around function pointer uses
4971 # ie: (foo->bar)(); should be foo->bar();
4972 # but not "if (foo->bar) (" to avoid some false positives
4973 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4975 if (CHK("UNNECESSARY_PARENTHESES",
4976 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4978 my $var2 = deparenthesize($var);
4980 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4984 # check for unnecessary parentheses around comparisons in if uses
4985 # when !drivers/staging or command-line uses --strict
4986 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4987 $perl_version_ok && defined($stat) &&
4988 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4990 my $test = substr($2, 1, -1);
4992 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4994 # avoid parentheses around potential macro args
4995 next if ($match =~ /^\s*\w+\s*$/);
4996 if (!defined($herectx)) {
4997 $herectx = $here . "\n";
4998 my $cnt = statement_rawlines($if_stat);
4999 for (my $n = 0; $n < $cnt; $n++) {
5000 my $rl = raw_line($linenr, $n);
5001 $herectx .= $rl . "\n";
5002 last if $rl =~ /^[ \+].*\{/;
5005 CHK("UNNECESSARY_PARENTHESES",
5006 "Unnecessary parentheses around '$match'\n" . $herectx);
5010 #goto labels aren't indented, allow a single space however
5011 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
5012 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
5013 if (WARN("INDENTED_LABEL",
5014 "labels should not be indented\n" . $herecurr) &&
5016 $fixed[$fixlinenr] =~
5021 # check if a statement with a comma should be two statements like:
5022 # foo = bar(), /* comma should be semicolon */
5024 if (defined($stat) &&
5025 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5026 my $cnt = statement_rawlines($stat);
5027 my $herectx = get_stat_here($linenr, $cnt, $here);
5028 WARN("SUSPECT_COMMA_SEMICOLON",
5029 "Possible comma where semicolon could be used\n" . $herectx);
5032 # return is not a function
5033 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5035 if ($perl_version_ok &&
5036 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5038 $value = deparenthesize($value);
5039 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5040 ERROR("RETURN_PARENTHESES",
5041 "return is not a function, parentheses are not required\n" . $herecurr);
5043 } elsif ($spacing !~ /\s+/) {
5045 "space required before the open parenthesis '('\n" . $herecurr);
5049 # unnecessary return in a void function
5050 # at end-of-function, with the previous line a single leading tab, then return;
5051 # and the line before that not a goto label target like "out:"
5052 if ($sline =~ /^[ \+]}\s*$/ &&
5053 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5055 $lines[$linenr - 3] =~ /^[ +]/ &&
5056 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5058 "void function return statements are not generally useful\n" . $hereprev);
5061 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5062 if ($perl_version_ok &&
5063 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5064 my $openparens = $1;
5065 my $count = $openparens =~ tr@\(@\(@;
5067 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5068 my $comp = $4; #Not $1 because of $LvalOrFunc
5069 $msg = " - maybe == should be = ?" if ($comp eq "==");
5070 WARN("UNNECESSARY_PARENTHESES",
5071 "Unnecessary parentheses$msg\n" . $herecurr);
5075 # comparisons with a constant or upper case identifier on the left
5076 # avoid cases like "foo + BAR < baz"
5077 # only fix matches surrounded by parentheses to avoid incorrect
5078 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5079 if ($perl_version_ok &&
5080 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5085 my $newcomp = $comp;
5086 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5087 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5088 WARN("CONSTANT_COMPARISON",
5089 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5093 } elsif ($comp eq "<=") {
5095 } elsif ($comp eq ">") {
5097 } elsif ($comp eq ">=") {
5100 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5104 # Return of what appears to be an errno should normally be negative
5105 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5107 if ($name ne 'EOF' && $name ne 'ERROR') {
5108 WARN("USE_NEGATIVE_ERRNO",
5109 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5113 # Need a space before open parenthesis after if, while etc
5114 if ($line =~ /\b(if|while|for|switch)\(/) {
5115 if (ERROR("SPACING",
5116 "space required before the open parenthesis '('\n" . $herecurr) &&
5118 $fixed[$fixlinenr] =~
5119 s/\b(if|while|for|switch)\(/$1 \(/;
5123 # Check for illegal assignment in if conditional -- and check for trailing
5124 # statements after the conditional.
5125 if ($line =~ /do\s*(?!{)/) {
5126 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5127 ctx_statement_block($linenr, $realcnt, 0)
5128 if (!defined $stat);
5129 my ($stat_next) = ctx_statement_block($line_nr_next,
5130 $remain_next, $off_next);
5131 $stat_next =~ s/\n./\n /g;
5132 ##print "stat<$stat> stat_next<$stat_next>\n";
5134 if ($stat_next =~ /^\s*while\b/) {
5135 # If the statement carries leading newlines,
5136 # then count those as offsets.
5138 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5140 statement_rawlines($whitespace) - 1;
5142 $suppress_whiletrailers{$line_nr_next +
5146 if (!defined $suppress_whiletrailers{$linenr} &&
5147 defined($stat) && defined($cond) &&
5148 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5149 my ($s, $c) = ($stat, $cond);
5151 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5152 if (ERROR("ASSIGN_IN_IF",
5153 "do not use assignment in if condition\n" . $herecurr) &&
5154 $fix && $perl_version_ok) {
5155 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5163 fix_delete_line($fixlinenr, $rawline);
5164 fix_insert_line($fixlinenr, "$space$statement;");
5165 my $newline = "${space}if (";
5166 $newline .= '!' if defined($not);
5167 $newline .= '(' if (defined $not && defined($test) && defined($against));
5168 $newline .= "$assigned";
5169 $newline .= " $test $against" if (defined($test) && defined($against));
5170 $newline .= ')' if (defined $not && defined($test) && defined($against));
5172 $newline .= " {" if (defined($brace));
5173 fix_insert_line($fixlinenr + 1, $newline);
5178 # Find out what is on the end of the line after the
5180 substr($s, 0, length($c), '');
5182 $s =~ s/$;//g; # Remove any comments
5183 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5184 $c !~ /}\s*while\s*/)
5186 # Find out how long the conditional actually is.
5187 my @newlines = ($c =~ /\n/gs);
5188 my $cond_lines = 1 + $#newlines;
5191 $stat_real = raw_line($linenr, $cond_lines)
5192 . "\n" if ($cond_lines);
5193 if (defined($stat_real) && $cond_lines > 1) {
5194 $stat_real = "[...]\n$stat_real";
5197 ERROR("TRAILING_STATEMENTS",
5198 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5202 # Check for bitwise tests written as boolean
5214 WARN("HEXADECIMAL_BOOLEAN_TEST",
5215 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5218 # if and else should not have general statements after it
5219 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5221 $s =~ s/$;//g; # Remove any comments
5222 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5223 ERROR("TRAILING_STATEMENTS",
5224 "trailing statements should be on next line\n" . $herecurr);
5227 # if should not continue a brace
5228 if ($line =~ /}\s*if\b/) {
5229 ERROR("TRAILING_STATEMENTS",
5230 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5233 # case and default should not have general statements after them
5234 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5236 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5240 ERROR("TRAILING_STATEMENTS",
5241 "trailing statements should be on next line\n" . $herecurr);
5244 # Check for }<nl>else {, these must be at the same
5245 # indent level to be relevant to each other.
5246 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5247 $previndent == $indent) {
5248 if (ERROR("ELSE_AFTER_BRACE",
5249 "else should follow close brace '}'\n" . $hereprev) &&
5250 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5251 fix_delete_line($fixlinenr - 1, $prevrawline);
5252 fix_delete_line($fixlinenr, $rawline);
5253 my $fixedline = $prevrawline;
5254 $fixedline =~ s/}\s*$//;
5255 if ($fixedline !~ /^\+\s*$/) {
5256 fix_insert_line($fixlinenr, $fixedline);
5258 $fixedline = $rawline;
5259 $fixedline =~ s/^(.\s*)else/$1} else/;
5260 fix_insert_line($fixlinenr, $fixedline);
5264 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5265 $previndent == $indent) {
5266 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5268 # Find out what is on the end of the line after the
5270 substr($s, 0, length($c), '');
5273 if ($s =~ /^\s*;/) {
5274 if (ERROR("WHILE_AFTER_BRACE",
5275 "while should follow close brace '}'\n" . $hereprev) &&
5276 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5277 fix_delete_line($fixlinenr - 1, $prevrawline);
5278 fix_delete_line($fixlinenr, $rawline);
5279 my $fixedline = $prevrawline;
5280 my $trailing = $rawline;
5281 $trailing =~ s/^\+//;
5282 $trailing = trim($trailing);
5283 $fixedline =~ s/}\s*$/} $trailing/;
5284 fix_insert_line($fixlinenr, $fixedline);
5289 #Specific variable tests
5290 while ($line =~ m{($Constant|$Lval)}g) {
5294 if ($var !~ /^$Constant$/ &&
5295 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5296 #Ignore Page<foo> variants
5297 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5298 #Ignore SI style variants like nS, mV and dB
5299 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5300 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5301 #Ignore some three character SI units explicitly, like MiB and KHz
5302 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5303 while ($var =~ m{($Ident)}g) {
5305 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5307 seed_camelcase_includes();
5308 if (!$file && !$camelcase_file_seeded) {
5309 seed_camelcase_file($realfile);
5310 $camelcase_file_seeded = 1;
5313 if (!defined $camelcase{$word}) {
5314 $camelcase{$word} = 1;
5316 "Avoid CamelCase: <$word>\n" . $herecurr);
5322 #no spaces allowed after \ in define
5323 if ($line =~ /\#\s*define.*\\\s+$/) {
5324 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5325 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5327 $fixed[$fixlinenr] =~ s/\s+$//;
5331 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5332 # itself <asm/foo.h> (uses RAW line)
5333 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5335 my $checkfile = "include/linux/$file";
5336 if (-f "$root/$checkfile" &&
5337 $realfile ne $checkfile &&
5338 $1 !~ /$allowed_asm_includes/)
5340 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5341 if ($asminclude > 0) {
5342 if ($realfile =~ m{^arch/}) {
5343 CHK("ARCH_INCLUDE_LINUX",
5344 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5346 WARN("INCLUDE_LINUX",
5347 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5353 # multi-statement macros should be enclosed in a do while loop, grab the
5354 # first statement and ensure its the whole macro if its not enclosed
5355 # in a known good container
5356 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5357 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5360 my ($off, $dstat, $dcond, $rest);
5362 my $has_flow_statement = 0;
5363 my $has_arg_concat = 0;
5364 ($dstat, $dcond, $ln, $cnt, $off) =
5365 ctx_statement_block($linenr, $realcnt, 0);
5367 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5368 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5370 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5371 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5373 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5374 my $define_args = $1;
5375 my $define_stmt = $dstat;
5378 if (defined $define_args && $define_args ne "") {
5379 $define_args = substr($define_args, 1, length($define_args) - 2);
5380 $define_args =~ s/\s*//g;
5381 $define_args =~ s/\\\+?//g;
5382 @def_args = split(",", $define_args);
5386 $dstat =~ s/\\\n.//g;
5387 $dstat =~ s/^\s*//s;
5388 $dstat =~ s/\s*$//s;
5390 # Flatten any parentheses and braces
5391 while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5392 $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5393 $dstat =~ s/.\[[^\[\]]*\]/1u/)
5397 # Flatten any obvious string concatenation.
5398 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5399 $dstat =~ s/$Ident\s*($String)/$1/)
5403 # Make asm volatile uses seem like a generic function
5404 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5406 my $exceptions = qr{
5419 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5422 my $stmt_cnt = statement_rawlines($ctx);
5423 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5426 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5427 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5428 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5429 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5430 $dstat !~ /$exceptions/ &&
5431 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5432 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5433 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5434 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...}
5435 $dstat !~ /^for\s*$Constant$/ && # for (...)
5436 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5437 $dstat !~ /^do\s*{/ && # do {...
5438 $dstat !~ /^\(\{/ && # ({...
5439 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5441 if ($dstat =~ /^\s*if\b/) {
5442 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5443 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5444 } elsif ($dstat =~ /;/) {
5445 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5446 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5448 ERROR("COMPLEX_MACRO",
5449 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5454 # Make $define_stmt single line, comment-free, etc
5455 my @stmt_array = split('\n', $define_stmt);
5458 foreach my $l (@stmt_array) {
5463 } elsif ($l =~ /^[\+ ]/) {
5464 $define_stmt .= substr($l, 1);
5467 $define_stmt =~ s/$;//g;
5468 $define_stmt =~ s/\s+/ /g;
5469 $define_stmt = trim($define_stmt);
5471 # check if any macro arguments are reused (ignore '...' and 'type')
5472 foreach my $arg (@def_args) {
5473 next if ($arg =~ /\.\.\./);
5474 next if ($arg =~ /^type$/i);
5475 my $tmp_stmt = $define_stmt;
5476 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5477 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5478 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5479 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5481 CHK("MACRO_ARG_REUSE",
5482 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5484 # check if any macro arguments may have other precedence issues
5485 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5486 ((defined($1) && $1 ne ',') ||
5487 (defined($2) && $2 ne ','))) {
5488 CHK("MACRO_ARG_PRECEDENCE",
5489 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5493 # check for macros with flow control, but without ## concatenation
5494 # ## concatenation is commonly a macro that defines a function so ignore those
5495 if ($has_flow_statement && !$has_arg_concat) {
5496 my $cnt = statement_rawlines($ctx);
5497 my $herectx = get_stat_here($linenr, $cnt, $here);
5499 WARN("MACRO_WITH_FLOW_CONTROL",
5500 "Macros with flow control statements should be avoided\n" . "$herectx");
5503 # check for line continuations outside of #defines, preprocessor #, and asm
5506 if ($prevline !~ /^..*\\$/ &&
5507 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5508 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5509 $line =~ /^\+.*\\$/) {
5510 WARN("LINE_CONTINUATIONS",
5511 "Avoid unnecessary line continuations\n" . $herecurr);
5515 # do {} while (0) macro tests:
5516 # single-statement macros do not need to be enclosed in do while (0) loop,
5517 # macro should not end with a semicolon
5518 if ($perl_version_ok &&
5519 $realfile !~ m@/vmlinux.lds.h$@ &&
5520 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5523 my ($off, $dstat, $dcond, $rest);
5525 ($dstat, $dcond, $ln, $cnt, $off) =
5526 ctx_statement_block($linenr, $realcnt, 0);
5529 $dstat =~ s/\\\n.//g;
5532 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5537 my $cnt = statement_rawlines($ctx);
5538 my $herectx = get_stat_here($linenr, $cnt, $here);
5540 if (($stmts =~ tr/;/;/) == 1 &&
5541 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5542 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5543 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5545 if (defined $semis && $semis ne "") {
5546 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5547 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5549 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5551 my $cnt = statement_rawlines($ctx);
5552 my $herectx = get_stat_here($linenr, $cnt, $here);
5554 WARN("TRAILING_SEMICOLON",
5555 "macros should not use a trailing semicolon\n" . "$herectx");
5559 # check for redundant bracing round if etc
5560 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5561 my ($level, $endln, @chunks) =
5562 ctx_statement_full($linenr, $realcnt, 1);
5563 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5564 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5565 if ($#chunks > 0 && $level == 0) {
5569 my $herectx = $here . "\n";
5570 my $ln = $linenr - 1;
5571 for my $chunk (@chunks) {
5572 my ($cond, $block) = @{$chunk};
5574 # If the condition carries leading newlines, then count those as offsets.
5575 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5576 my $offset = statement_rawlines($whitespace) - 1;
5578 $allowed[$allow] = 0;
5579 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5581 # We have looked at and allowed this specific line.
5582 $suppress_ifbraces{$ln + $offset} = 1;
5584 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5585 $ln += statement_rawlines($block) - 1;
5587 substr($block, 0, length($cond), '');
5589 $seen++ if ($block =~ /^\s*{/);
5591 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5592 if (statement_lines($cond) > 1) {
5593 #print "APW: ALLOWED: cond<$cond>\n";
5594 $allowed[$allow] = 1;
5596 if ($block =~/\b(?:if|for|while)\b/) {
5597 #print "APW: ALLOWED: block<$block>\n";
5598 $allowed[$allow] = 1;
5600 if (statement_block_size($block) > 1) {
5601 #print "APW: ALLOWED: lines block<$block>\n";
5602 $allowed[$allow] = 1;
5607 my $sum_allowed = 0;
5608 foreach (@allowed) {
5611 if ($sum_allowed == 0) {
5613 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5614 } elsif ($sum_allowed != $allow &&
5617 "braces {} should be used on all arms of this statement\n" . $herectx);
5622 if (!defined $suppress_ifbraces{$linenr - 1} &&
5623 $line =~ /\b(if|while|for|else)\b/) {
5626 # Check the pre-context.
5627 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5628 #print "APW: ALLOWED: pre<$1>\n";
5632 my ($level, $endln, @chunks) =
5633 ctx_statement_full($linenr, $realcnt, $-[0]);
5635 # Check the condition.
5636 my ($cond, $block) = @{$chunks[0]};
5637 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5638 if (defined $cond) {
5639 substr($block, 0, length($cond), '');
5641 if (statement_lines($cond) > 1) {
5642 #print "APW: ALLOWED: cond<$cond>\n";
5645 if ($block =~/\b(?:if|for|while)\b/) {
5646 #print "APW: ALLOWED: block<$block>\n";
5649 if (statement_block_size($block) > 1) {
5650 #print "APW: ALLOWED: lines block<$block>\n";
5653 # Check the post-context.
5654 if (defined $chunks[1]) {
5655 my ($cond, $block) = @{$chunks[1]};
5656 if (defined $cond) {
5657 substr($block, 0, length($cond), '');
5659 if ($block =~ /^\s*\{/) {
5660 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5664 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5665 my $cnt = statement_rawlines($block);
5666 my $herectx = get_stat_here($linenr, $cnt, $here);
5669 "braces {} are not necessary for single statement blocks\n" . $herectx);
5673 # check for single line unbalanced braces
5674 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5675 $sline =~ /^.\s*else\s*\{\s*$/) {
5676 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5679 # check for unnecessary blank lines around braces
5680 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5682 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5683 $fix && $prevrawline =~ /^\+/) {
5684 fix_delete_line($fixlinenr - 1, $prevrawline);
5687 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5689 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5691 fix_delete_line($fixlinenr, $rawline);
5695 # no volatiles please
5696 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5697 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5699 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5702 # Check for user-visible strings broken across lines, which breaks the ability
5703 # to grep for the string. Make exceptions when the previous string ends in a
5704 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5705 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5706 if ($line =~ /^\+\s*$String/ &&
5707 $prevline =~ /"\s*$/ &&
5708 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5709 if (WARN("SPLIT_STRING",
5710 "quoted string split across lines\n" . $hereprev) &&
5712 $prevrawline =~ /^\+.*"\s*$/ &&
5713 $last_coalesced_string_linenr != $linenr - 1) {
5714 my $extracted_string = get_quoted_string($line, $rawline);
5715 my $comma_close = "";
5716 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5720 fix_delete_line($fixlinenr - 1, $prevrawline);
5721 fix_delete_line($fixlinenr, $rawline);
5722 my $fixedline = $prevrawline;
5723 $fixedline =~ s/"\s*$//;
5724 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5725 fix_insert_line($fixlinenr - 1, $fixedline);
5726 $fixedline = $rawline;
5727 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5728 if ($fixedline !~ /\+\s*$/) {
5729 fix_insert_line($fixlinenr, $fixedline);
5731 $last_coalesced_string_linenr = $linenr;
5735 # check for missing a space in a string concatenation
5736 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5737 WARN('MISSING_SPACE',
5738 "break quoted strings at a space character\n" . $hereprev);
5741 # check for an embedded function name in a string when the function is known
5742 # This does not work very well for -f --file checking as it depends on patch
5743 # context providing the function name or a single line form for in-file
5744 # function declarations
5745 if ($line =~ /^\+.*$String/ &&
5746 defined($context_function) &&
5747 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5748 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5749 WARN("EMBEDDED_FUNCTION_NAME",
5750 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5753 # check for spaces before a quoted newline
5754 if ($rawline =~ /^.*\".*\s\\n/) {
5755 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5756 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5758 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5763 # concatenated string without spaces between elements
5764 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5765 if (CHK("CONCATENATED_STRING",
5766 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5768 while ($line =~ /($String)/g) {
5769 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5770 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5771 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5776 # uncoalesced string fragments
5777 if ($line =~ /$String\s*"/) {
5778 if (WARN("STRING_FRAGMENTS",
5779 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5781 while ($line =~ /($String)(?=\s*")/g) {
5782 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5783 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5788 # check for non-standard and hex prefixed decimal printf formats
5789 my $show_L = 1; #don't show the same defect twice
5791 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5792 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5793 $string =~ s/%%/__/g;
5795 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5797 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5801 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5803 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5806 # check for 0x<decimal>
5807 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5808 ERROR("PRINTF_0XDECIMAL",
5809 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5813 # check for line continuations in quoted strings with odd counts of "
5814 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5815 WARN("LINE_CONTINUATIONS",
5816 "Avoid line continuations in quoted strings\n" . $herecurr);
5820 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5822 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5826 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5828 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5831 # check for needless "if (<foo>) fn(<foo>)" uses
5832 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5833 my $tested = quotemeta($1);
5834 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5835 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5837 if (WARN('NEEDLESS_IF',
5838 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5841 my $leading_tabs = "";
5842 my $new_leading_tabs = "";
5843 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5848 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5849 $new_leading_tabs = $1;
5850 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5857 fix_delete_line($fixlinenr - 1, $prevrawline);
5858 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5864 # check for unnecessary "Out of Memory" messages
5865 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5866 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5867 (defined $1 || defined $3) &&
5870 my $testline = $lines[$linenr - 3];
5872 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5873 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5875 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5876 $s !~ /\b__GFP_NOWARN\b/ ) {
5878 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5882 # check for logging functions with KERN_<LEVEL>
5883 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5884 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5886 if (WARN("UNNECESSARY_KERN_LEVEL",
5887 "Possible unnecessary $level\n" . $herecurr) &&
5889 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5893 # check for logging continuations
5894 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5895 WARN("LOGGING_CONTINUATION",
5896 "Avoid logging continuation uses where feasible\n" . $herecurr);
5899 # check for mask then right shift without a parentheses
5900 if ($perl_version_ok &&
5901 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5902 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5903 WARN("MASK_THEN_SHIFT",
5904 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5907 # check for pointer comparisons to NULL
5908 if ($perl_version_ok) {
5909 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5912 $equal = "" if ($4 eq "!=");
5913 if (CHK("COMPARISON_TO_NULL",
5914 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5916 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5921 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5922 if ($line =~ /(\b$InitAttribute\b)/) {
5924 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5927 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5928 ERROR("MISPLACED_INIT",
5929 "$attr should be placed after $var\n" . $herecurr)) ||
5930 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5931 WARN("MISPLACED_INIT",
5932 "$attr should be placed after $var\n" . $herecurr))) &&
5934 $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;
5939 # check for $InitAttributeData (ie: __initdata) with const
5940 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5942 $attr =~ /($InitAttributePrefix)(.*)/;
5943 my $attr_prefix = $1;
5945 if (ERROR("INIT_ATTRIBUTE",
5946 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5948 $fixed[$fixlinenr] =~
5949 s/$InitAttributeData/${attr_prefix}initconst/;
5953 # check for $InitAttributeConst (ie: __initconst) without const
5954 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5956 if (ERROR("INIT_ATTRIBUTE",
5957 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5959 my $lead = $fixed[$fixlinenr] =~
5960 /(^\+\s*(?:static\s+))/;
5962 $lead = "$lead " if ($lead !~ /^\+$/);
5963 $lead = "${lead}const ";
5964 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5968 # check for __read_mostly with const non-pointer (should just be const)
5969 if ($line =~ /\b__read_mostly\b/ &&
5970 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5971 if (ERROR("CONST_READ_MOSTLY",
5972 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5974 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5978 # don't use __constant_<foo> functions outside of include/uapi/
5979 if ($realfile !~ m@^include/uapi/@ &&
5980 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5981 my $constant_func = $1;
5982 my $func = $constant_func;
5983 $func =~ s/^__constant_//;
5984 if (WARN("CONSTANT_CONVERSION",
5985 "$constant_func should be $func\n" . $herecurr) &&
5987 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5991 # prefer usleep_range over udelay
5992 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5994 # ignore udelay's < 10, however
5995 if (! ($delay < 10) ) {
5997 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5999 if ($delay > 2000) {
6001 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
6005 # warn about unexpectedly long msleep's
6006 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6009 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
6013 # check for comparisons of jiffies
6014 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6015 WARN("JIFFIES_COMPARISON",
6016 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6019 # check for comparisons of get_jiffies_64()
6020 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6021 WARN("JIFFIES_COMPARISON",
6022 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6025 # warn about #ifdefs in C files
6026 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6027 # print "#ifdef in C files should be avoided\n";
6028 # print "$herecurr";
6032 # warn about spacing in #ifdefs
6033 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6034 if (ERROR("SPACING",
6035 "exactly one space required after that #$1\n" . $herecurr) &&
6037 $fixed[$fixlinenr] =~
6038 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6043 # check for spinlock_t definitions without a comment.
6044 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6045 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6047 if (!ctx_has_comment($first_line, $linenr)) {
6048 CHK("UNCOMMENTED_DEFINITION",
6049 "$1 definition without comment\n" . $herecurr);
6052 # check for memory barriers without a comment.
6059 my $barrier_stems = qr{
6067 my $all_barriers = qr{
6069 smp_(?:$barrier_stems)|
6070 virt_(?:$barrier_stems)
6073 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6074 if (!ctx_has_comment($first_line, $linenr)) {
6075 WARN("MEMORY_BARRIER",
6076 "memory barrier without comment\n" . $herecurr);
6080 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6082 if ($realfile !~ m@^include/asm-generic/@ &&
6083 $realfile !~ m@/barrier\.h$@ &&
6084 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6085 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6086 WARN("MEMORY_BARRIER",
6087 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6090 # check for waitqueue_active without a comment.
6091 if ($line =~ /\bwaitqueue_active\s*\(/) {
6092 if (!ctx_has_comment($first_line, $linenr)) {
6093 WARN("WAITQUEUE_ACTIVE",
6094 "waitqueue_active without comment\n" . $herecurr);
6098 # check for data_race without a comment.
6099 if ($line =~ /\bdata_race\s*\(/) {
6100 if (!ctx_has_comment($first_line, $linenr)) {
6102 "data_race without comment\n" . $herecurr);
6106 # check of hardware specific defines
6107 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6109 "architecture specific defines should be avoided\n" . $herecurr);
6112 # check that the storage class is not after a type
6113 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6114 WARN("STORAGE_CLASS",
6115 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6117 # Check that the storage class is at the beginning of a declaration
6118 if ($line =~ /\b$Storage\b/ &&
6119 $line !~ /^.\s*$Storage/ &&
6120 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6121 $1 !~ /[\,\)]\s*$/) {
6122 WARN("STORAGE_CLASS",
6123 "storage class should be at the beginning of the declaration\n" . $herecurr);
6126 # check the location of the inline attribute, that it is between
6127 # storage class and type.
6128 if ($line =~ /\b$Type\s+$Inline\b/ ||
6129 $line =~ /\b$Inline\s+$Storage\b/) {
6130 ERROR("INLINE_LOCATION",
6131 "inline keyword should sit between storage class and type\n" . $herecurr);
6134 # Check for __inline__ and __inline, prefer inline
6135 if ($realfile !~ m@\binclude/uapi/@ &&
6136 $line =~ /\b(__inline__|__inline)\b/) {
6138 "plain inline is preferred over $1\n" . $herecurr) &&
6140 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6145 # Check for __attribute__ packed, prefer __packed
6146 if ($realfile !~ m@\binclude/uapi/@ &&
6147 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
6148 WARN("PREFER_PACKED",
6149 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
6152 # Check for __attribute__ aligned, prefer __aligned
6153 if ($realfile !~ m@\binclude/uapi/@ &&
6154 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
6155 WARN("PREFER_ALIGNED",
6156 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
6159 # Check for __attribute__ section, prefer __section
6160 if ($realfile !~ m@\binclude/uapi/@ &&
6161 $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
6162 my $old = substr($rawline, $-[1], $+[1] - $-[1]);
6163 my $new = substr($old, 1, -1);
6164 if (WARN("PREFER_SECTION",
6165 "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
6167 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
6171 # Check for __attribute__ format(printf, prefer __printf
6172 if ($realfile !~ m@\binclude/uapi/@ &&
6173 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
6174 if (WARN("PREFER_PRINTF",
6175 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
6177 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
6182 # Check for __attribute__ format(scanf, prefer __scanf
6183 if ($realfile !~ m@\binclude/uapi/@ &&
6184 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
6185 if (WARN("PREFER_SCANF",
6186 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
6188 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
6192 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6193 if ($perl_version_ok &&
6194 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6195 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6196 $line =~ /\b__weak\b/)) {
6197 ERROR("WEAK_DECLARATION",
6198 "Using weak declarations can have unintended link defects\n" . $herecurr);
6201 # check for c99 types like uint8_t used outside of uapi/ and tools/
6202 if ($realfile !~ m@\binclude/uapi/@ &&
6203 $realfile !~ m@\btools/@ &&
6204 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6206 if ($type =~ /\b($typeC99Typedefs)\b/) {
6208 my $kernel_type = 'u';
6209 $kernel_type = 's' if ($type =~ /^_*[si]/);
6212 if (CHK("PREFER_KERNEL_TYPES",
6213 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6215 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6220 # check for cast of C90 native int or longer types constants
6221 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6224 if (WARN("TYPECAST_INT_CONSTANT",
6225 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6228 my $newconst = $const;
6229 $newconst =~ s/${Int_type}$//;
6230 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6231 if ($cast =~ /\blong\s+long\b/) {
6233 } elsif ($cast =~ /\blong\b/) {
6236 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6240 # check for sizeof(&)
6241 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6242 WARN("SIZEOF_ADDRESS",
6243 "sizeof(& should be avoided\n" . $herecurr);
6246 # check for sizeof without parenthesis
6247 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6248 if (WARN("SIZEOF_PARENTHESIS",
6249 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6251 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6255 # check for struct spinlock declarations
6256 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6257 WARN("USE_SPINLOCK_T",
6258 "struct spinlock should be spinlock_t\n" . $herecurr);
6261 # check for seq_printf uses that could be seq_puts
6262 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6263 my $fmt = get_quoted_string($line, $rawline);
6266 if (WARN("PREFER_SEQ_PUTS",
6267 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6269 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6274 # check for vsprintf extension %p<foo> misuses
6275 if ($perl_version_ok &&
6277 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6278 $1 !~ /^_*volatile_*$/) {
6281 my $lc = $stat =~ tr@\n@@;
6282 $lc = $lc + $linenr;
6283 for (my $count = $linenr; $count <= $lc; $count++) {
6287 my $bad_specifier = "";
6288 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6291 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6295 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6296 ($extension eq "f" &&
6297 defined $qualifier && $qualifier !~ /^w/)) {
6298 $bad_specifier = $specifier;
6301 if ($extension eq "x" && !defined($stat_real)) {
6302 if (!defined($stat_real)) {
6303 $stat_real = get_stat_real($linenr, $lc);
6305 WARN("VSPRINTF_SPECIFIER_PX",
6306 "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");
6309 if ($bad_specifier ne "") {
6310 my $stat_real = get_stat_real($linenr, $lc);
6311 my $ext_type = "Invalid";
6313 if ($bad_specifier =~ /p[Ff]/) {
6314 $use = " - use %pS instead";
6315 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6318 WARN("VSPRINTF_POINTER_EXTENSION",
6319 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6324 # Check for misused memsets
6325 if ($perl_version_ok &&
6327 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6333 if ($ms_size =~ /^(0x|)0$/i) {
6335 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6336 } elsif ($ms_size =~ /^(0x|)1$/i) {
6338 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6342 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6343 # if ($perl_version_ok &&
6345 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6346 # if (WARN("PREFER_ETHER_ADDR_COPY",
6347 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6349 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6353 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6354 # if ($perl_version_ok &&
6356 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6357 # WARN("PREFER_ETHER_ADDR_EQUAL",
6358 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6361 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6362 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6363 # if ($perl_version_ok &&
6365 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6369 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6370 # if (WARN("PREFER_ETH_ZERO_ADDR",
6371 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6373 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6375 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6376 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6377 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6379 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6384 # typecasts on min/max could be min_t/max_t
6385 if ($perl_version_ok &&
6387 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6388 if (defined $2 || defined $7) {
6390 my $cast1 = deparenthesize($2);
6392 my $cast2 = deparenthesize($7);
6396 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6397 $cast = "$cast1 or $cast2";
6398 } elsif ($cast1 ne "") {
6404 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6408 # check usleep_range arguments
6409 if ($perl_version_ok &&
6411 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6415 WARN("USLEEP_RANGE",
6416 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6417 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6419 WARN("USLEEP_RANGE",
6420 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6424 # check for naked sscanf
6425 if ($perl_version_ok &&
6427 $line =~ /\bsscanf\b/ &&
6428 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6429 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6430 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6431 my $lc = $stat =~ tr@\n@@;
6432 $lc = $lc + $linenr;
6433 my $stat_real = get_stat_real($linenr, $lc);
6434 WARN("NAKED_SSCANF",
6435 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6438 # check for simple sscanf that should be kstrto<foo>
6439 if ($perl_version_ok &&
6441 $line =~ /\bsscanf\b/) {
6442 my $lc = $stat =~ tr@\n@@;
6443 $lc = $lc + $linenr;
6444 my $stat_real = get_stat_real($linenr, $lc);
6445 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6447 my $count = $format =~ tr@%@%@;
6449 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6450 WARN("SSCANF_TO_KSTRTO",
6451 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6456 # check for new externs in .h files.
6457 if ($realfile =~ /\.h$/ &&
6458 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6459 if (CHK("AVOID_EXTERNS",
6460 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6462 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6466 # check for new externs in .c files.
6467 if ($realfile =~ /\.c$/ && defined $stat &&
6468 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6470 my $function_name = $1;
6471 my $paren_space = $2;
6474 if (defined $cond) {
6475 substr($s, 0, length($cond), '');
6479 WARN("AVOID_EXTERNS",
6480 "externs should be avoided in .c files\n" . $herecurr);
6483 if ($paren_space =~ /\n/) {
6484 WARN("FUNCTION_ARGUMENTS",
6485 "arguments for function declarations should follow identifier\n" . $herecurr);
6488 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6489 $stat =~ /^.\s*extern\s+/)
6491 WARN("AVOID_EXTERNS",
6492 "externs should be avoided in .c files\n" . $herecurr);
6495 # check for function declarations that have arguments without identifier names
6496 if (defined $stat &&
6497 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6499 my $args = trim($1);
6500 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6502 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6503 WARN("FUNCTION_ARGUMENTS",
6504 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6509 # check for function definitions
6510 if ($perl_version_ok &&
6512 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6513 $context_function = $1;
6515 # check for multiline function definition with misplaced open brace
6517 my $cnt = statement_rawlines($stat);
6518 my $herectx = $here . "\n";
6519 for (my $n = 0; $n < $cnt; $n++) {
6520 my $rl = raw_line($linenr, $n);
6521 $herectx .= $rl . "\n";
6522 $ok = 1 if ($rl =~ /^[ \+]\{/);
6523 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6524 last if $rl =~ /^[ \+].*\{/;
6528 "open brace '{' following function definitions go on the next line\n" . $herectx);
6532 # checks for new __setup's
6533 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6536 if (!grep(/$name/, @setup_docs)) {
6537 CHK("UNDOCUMENTED_SETUP",
6538 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6542 # check for pointless casting of alloc functions
6543 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6544 WARN("UNNECESSARY_CASTS",
6545 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6549 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6550 if ($perl_version_ok &&
6551 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6552 CHK("ALLOC_SIZEOF_STRUCT",
6553 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6556 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6557 if ($perl_version_ok &&
6559 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6563 my $newfunc = "kmalloc_array";
6564 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6567 if ($a1 =~ /^sizeof\s*\S/) {
6571 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6572 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6573 my $cnt = statement_rawlines($stat);
6574 my $herectx = get_stat_here($linenr, $cnt, $here);
6576 if (WARN("ALLOC_WITH_MULTIPLY",
6577 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6580 $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;
6585 # check for krealloc arg reuse
6586 if ($perl_version_ok &&
6587 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6589 WARN("KREALLOC_ARG_REUSE",
6590 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6593 # check for alloc argument mismatch
6594 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6595 WARN("ALLOC_ARRAY_ARGS",
6596 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6599 # check for multiple semicolons
6600 if ($line =~ /;\s*;\s*$/) {
6601 if (WARN("ONE_SEMICOLON",
6602 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6604 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6608 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6609 if ($realfile !~ m@^include/uapi/@ &&
6610 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6612 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6613 if (CHK("BIT_MACRO",
6614 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6616 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6620 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6621 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6622 WARN("IS_ENABLED_CONFIG",
6623 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6626 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6627 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6629 if (WARN("PREFER_IS_ENABLED",
6630 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6632 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6636 # check for /* fallthrough */ like comment, prefer fallthrough;
6637 my @fallthroughs = (
6640 'lint -fallthrough[ \t]*',
6641 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6642 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6643 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6644 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6646 if ($raw_comment ne '') {
6647 foreach my $ft (@fallthroughs) {
6648 if ($raw_comment =~ /$ft/) {
6649 my $msg_level = \&WARN;
6650 $msg_level = \&CHK if ($file);
6651 &{$msg_level}("PREFER_FALLTHROUGH",
6652 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6658 # check for switch/default statements without a break;
6659 if ($perl_version_ok &&
6661 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6662 my $cnt = statement_rawlines($stat);
6663 my $herectx = get_stat_here($linenr, $cnt, $here);
6665 WARN("DEFAULT_NO_BREAK",
6666 "switch default: should use break\n" . $herectx);
6669 # check for gcc specific __FUNCTION__
6670 if ($line =~ /\b__FUNCTION__\b/) {
6671 if (WARN("USE_FUNC",
6672 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6674 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6678 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6679 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6681 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6684 # check for use of yield()
6685 if ($line =~ /\byield\s*\(\s*\)/) {
6687 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6690 # check for comparisons against true and false
6691 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6699 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6701 my $type = lc($otype);
6702 if ($type =~ /^(?:true|false)$/) {
6703 if (("$test" eq "==" && "$type" eq "true") ||
6704 ("$test" eq "!=" && "$type" eq "false")) {
6708 CHK("BOOL_COMPARISON",
6709 "Using comparison to $otype is error prone\n" . $herecurr);
6711 ## maybe suggesting a correct construct would better
6712 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6717 # check for semaphores initialized locked
6718 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6719 WARN("CONSIDER_COMPLETION",
6720 "consider using a completion\n" . $herecurr);
6723 # recommend kstrto* over simple_strto* and strict_strto*
6724 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6725 WARN("CONSIDER_KSTRTO",
6726 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6729 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6730 if ($line =~ /^.\s*__initcall\s*\(/) {
6731 WARN("USE_DEVICE_INITCALL",
6732 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6735 # check for spin_is_locked(), suggest lockdep instead
6736 if ($line =~ /\bspin_is_locked\(/) {
6738 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6741 # check for deprecated apis
6742 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6743 my $deprecated_api = $1;
6744 my $new_api = $deprecated_apis{$deprecated_api};
6745 WARN("DEPRECATED_API",
6746 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6749 # check for various structs that are normally const (ops, kgdb, device_tree)
6750 # and avoid what seem like struct definitions 'struct foo {'
6751 if (defined($const_structs) &&
6752 $line !~ /\bconst\b/ &&
6753 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6754 WARN("CONST_STRUCT",
6755 "struct $1 should normally be const\n" . $herecurr);
6758 # use of NR_CPUS is usually wrong
6759 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6760 if ($line =~ /\bNR_CPUS\b/ &&
6761 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6762 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6763 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6764 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6765 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6768 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6771 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6772 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6773 ERROR("DEFINE_ARCH_HAS",
6774 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6777 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6778 if ($perl_version_ok &&
6779 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6780 WARN("LIKELY_MISUSE",
6781 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6784 # nested likely/unlikely calls
6785 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6786 WARN("LIKELY_MISUSE",
6787 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6790 # whine mightly about in_atomic
6791 if ($line =~ /\bin_atomic\s*\(/) {
6792 if ($realfile =~ m@^drivers/@) {
6794 "do not use in_atomic in drivers\n" . $herecurr);
6795 } elsif ($realfile !~ m@^kernel/@) {
6797 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6801 # check for mutex_trylock_recursive usage
6802 if ($line =~ /mutex_trylock_recursive/) {
6804 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6807 # check for lockdep_set_novalidate_class
6808 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6809 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6810 if ($realfile !~ m@^kernel/lockdep@ &&
6811 $realfile !~ m@^include/linux/lockdep@ &&
6812 $realfile !~ m@^drivers/base/core@) {
6814 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6818 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6819 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6820 WARN("EXPORTED_WORLD_WRITABLE",
6821 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6824 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6825 # and whether or not function naming is typical and if
6826 # DEVICE_ATTR permissions uses are unusual too
6827 if ($perl_version_ok &&
6829 $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*\)/) {
6834 my $octal_perms = perms_to_octal($perms);
6835 if ($show =~ /^${var}_show$/ &&
6836 $store =~ /^${var}_store$/ &&
6837 $octal_perms eq "0644") {
6838 if (WARN("DEVICE_ATTR_RW",
6839 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6841 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6843 } elsif ($show =~ /^${var}_show$/ &&
6844 $store =~ /^NULL$/ &&
6845 $octal_perms eq "0444") {
6846 if (WARN("DEVICE_ATTR_RO",
6847 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6849 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6851 } elsif ($show =~ /^NULL$/ &&
6852 $store =~ /^${var}_store$/ &&
6853 $octal_perms eq "0200") {
6854 if (WARN("DEVICE_ATTR_WO",
6855 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6857 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6859 } elsif ($octal_perms eq "0644" ||
6860 $octal_perms eq "0444" ||
6861 $octal_perms eq "0200") {
6862 my $newshow = "$show";
6863 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6864 my $newstore = $store;
6865 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6867 if ($show ne $newshow) {
6868 $rename .= " '$show' to '$newshow'";
6870 if ($store ne $newstore) {
6871 $rename .= " '$store' to '$newstore'";
6873 WARN("DEVICE_ATTR_FUNCTIONS",
6874 "Consider renaming function(s)$rename\n" . $herecurr);
6876 WARN("DEVICE_ATTR_PERMS",
6877 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6881 # Mode permission misuses where it seems decimal should be octal
6882 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6883 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6884 # specific definition of not visible in sysfs.
6885 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6886 # use the default permissions
6887 if ($perl_version_ok &&
6889 $line =~ /$mode_perms_search/) {
6890 foreach my $entry (@mode_permission_funcs) {
6891 my $func = $entry->[0];
6892 my $arg_pos = $entry->[1];
6894 my $lc = $stat =~ tr@\n@@;
6895 $lc = $lc + $linenr;
6896 my $stat_real = get_stat_real($linenr, $lc);
6901 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6903 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6904 if ($stat =~ /$test/) {
6906 $val = $6 if ($skip_args ne "");
6907 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6908 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6909 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6910 ERROR("NON_OCTAL_PERMISSIONS",
6911 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6913 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6914 ERROR("EXPORTED_WORLD_WRITABLE",
6915 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6921 # check for uses of S_<PERMS> that could be octal for readability
6922 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6924 my $octal = perms_to_octal($oval);
6925 if (WARN("SYMBOLIC_PERMS",
6926 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6928 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6932 # validate content of MODULE_LICENSE against list from include/linux/module.h
6933 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6934 my $extracted_string = get_quoted_string($line, $rawline);
6935 my $valid_licenses = qr{
6938 GPL\ and\ additional\ rights|
6944 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6945 WARN("MODULE_LICENSE",
6946 "unknown module license " . $extracted_string . "\n" . $herecurr);
6950 # check for sysctl duplicate constants
6951 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6952 WARN("DUPLICATED_SYSCTL_CONST",
6953 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6957 # If we have no input at all, then there is nothing to report on
6958 # so just keep quiet.
6959 if ($#rawlines == -1) {
6963 # In mailback mode only produce a report in the negative, for
6964 # things that appear to be patches.
6965 if ($mailback && ($clean == 1 || !$is_patch)) {
6969 # This is not a patch, and we are are in 'no-patch' mode so
6971 if (!$chk_patch && !$is_patch) {
6975 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6976 ERROR("NOT_UNIFIED_DIFF",
6977 "Does not appear to be a unified-diff format patch\n");
6979 if ($is_patch && $has_commit_log && $chk_signoff) {
6980 if ($signoff == 0) {
6981 ERROR("MISSING_SIGN_OFF",
6982 "Missing Signed-off-by: line(s)\n");
6983 } elsif ($authorsignoff != 1) {
6984 # authorsignoff values:
6985 # 0 -> missing sign off
6986 # 1 -> sign off identical
6987 # 2 -> names and addresses match, comments mismatch
6988 # 3 -> addresses match, names different
6989 # 4 -> names match, addresses different
6990 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
6992 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
6994 if ($authorsignoff == 0) {
6995 ERROR("NO_AUTHOR_SIGN_OFF",
6996 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6997 } elsif ($authorsignoff == 2) {
6998 CHK("FROM_SIGN_OFF_MISMATCH",
6999 "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7000 } elsif ($authorsignoff == 3) {
7001 WARN("FROM_SIGN_OFF_MISMATCH",
7002 "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7003 } elsif ($authorsignoff == 4) {
7004 WARN("FROM_SIGN_OFF_MISMATCH",
7005 "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7006 } elsif ($authorsignoff == 5) {
7007 WARN("FROM_SIGN_OFF_MISMATCH",
7008 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7013 print report_dump();
7014 if ($summary && !($clean == 1 && $quiet == 1)) {
7015 print "$filename " if ($summary_file);
7016 print "total: $cnt_error errors, $cnt_warn warnings, " .
7017 (($check)? "$cnt_chk checks, " : "") .
7018 "$cnt_lines lines checked\n";
7022 # If there were any defects found and not already fixing them
7023 if (!$clean and !$fix) {
7026 NOTE: For some of the reported defects, checkpatch may be able to
7027 mechanically convert to the typical style using --fix or --fix-inplace.
7030 # If there were whitespace errors which cleanpatch can fix
7031 # then suggest that.
7032 if ($rpt_cleaners) {
7036 NOTE: Whitespace errors detected.
7037 You may wish to use scripts/cleanpatch or scripts/cleanfile
7042 if ($clean == 0 && $fix &&
7043 ("@rawlines" ne "@fixed" ||
7044 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7045 my $newfile = $filename;
7046 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7050 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7052 open($f, '>', $newfile)
7053 or die "$P: Can't open $newfile for write\n";
7054 foreach my $fixed_line (@fixed) {
7057 if ($linecount > 3) {
7058 $fixed_line =~ s/^\+//;
7059 print $f $fixed_line . "\n";
7062 print $f $fixed_line . "\n";
7070 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7072 Do _NOT_ trust the results written to this file.
7073 Do _NOT_ submit these changes without inspecting them for correctness.
7075 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7076 No warranties, expressed or implied...
7084 print "$vname has no obvious style problems and is ready for submission.\n";
7086 print "$vname has style problems, please review.\n";