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 $name = trim($name);
1185 $name =~ s/^\"|\"$//g;
1186 $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, $address) = @_;
1204 my $formatted_email;
1206 $name = trim($name);
1207 $name =~ s/^\"|\"$//g;
1208 $address = trim($address);
1210 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1211 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1212 $name = "\"$name\"";
1215 if ("$name" eq "") {
1216 $formatted_email = "$address";
1218 $formatted_email = "$name <$address>";
1221 return $formatted_email;
1224 sub reformat_email {
1227 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1228 return format_email($email_name, $email_address);
1231 sub same_email_addresses {
1232 my ($email1, $email2) = @_;
1234 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1235 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1237 return $email1_name eq $email2_name &&
1238 $email1_address eq $email2_address;
1244 foreach my $path (split(/:/, $ENV{PATH})) {
1245 if (-e "$path/$bin") {
1246 return "$path/$bin";
1256 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1257 if (-e "$path/$conf") {
1258 return "$path/$conf";
1270 for my $c (split(//, $str)) {
1274 for (; ($n % $tabsize) != 0; $n++) {
1286 (my $res = shift) =~ tr/\t/ /c;
1293 # Drop the diff line leader and expand tabs
1295 $line = expand_tabs($line);
1297 # Pick the indent from the front of the line.
1298 my ($white) = ($line =~ /^(\s*)/);
1300 return (length($line), length($white));
1303 my $sanitise_quote = '';
1305 sub sanitise_line_reset {
1306 my ($in_comment) = @_;
1309 $sanitise_quote = '*/';
1311 $sanitise_quote = '';
1324 # Always copy over the diff marker.
1325 $res = substr($line, 0, 1);
1327 for ($off = 1; $off < length($line); $off++) {
1328 $c = substr($line, $off, 1);
1330 # Comments we are whacking completely including the begin
1331 # and end, all to $;.
1332 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1333 $sanitise_quote = '*/';
1335 substr($res, $off, 2, "$;$;");
1339 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1340 $sanitise_quote = '';
1341 substr($res, $off, 2, "$;$;");
1345 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1346 $sanitise_quote = '//';
1348 substr($res, $off, 2, $sanitise_quote);
1353 # A \ in a string means ignore the next character.
1354 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1356 substr($res, $off, 2, 'XX');
1361 if ($c eq "'" || $c eq '"') {
1362 if ($sanitise_quote eq '') {
1363 $sanitise_quote = $c;
1365 substr($res, $off, 1, $c);
1367 } elsif ($sanitise_quote eq $c) {
1368 $sanitise_quote = '';
1372 #print "c<$c> SQ<$sanitise_quote>\n";
1373 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1374 substr($res, $off, 1, $;);
1375 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1376 substr($res, $off, 1, $;);
1377 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1378 substr($res, $off, 1, 'X');
1380 substr($res, $off, 1, $c);
1384 if ($sanitise_quote eq '//') {
1385 $sanitise_quote = '';
1388 # The pathname on a #include may be surrounded by '<' and '>'.
1389 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1390 my $clean = 'X' x length($1);
1391 $res =~ s@\<.*\>@<$clean>@;
1393 # The whole of a #error is a string.
1394 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1395 my $clean = 'X' x length($1);
1396 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1399 if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1401 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1407 sub get_quoted_string {
1408 my ($line, $rawline) = @_;
1410 return "" if (!defined($line) || !defined($rawline));
1411 return "" if ($line !~ m/($String)/g);
1412 return substr($rawline, $-[0], $+[0] - $-[0]);
1415 sub ctx_statement_block {
1416 my ($linenr, $remain, $off) = @_;
1417 my $line = $linenr - 1;
1420 my $coff = $off - 1;
1434 @stack = (['', 0]) if ($#stack == -1);
1436 #warn "CSB: blk<$blk> remain<$remain>\n";
1437 # If we are about to drop off the end, pull in more
1440 for (; $remain > 0; $line++) {
1441 last if (!defined $lines[$line]);
1442 next if ($lines[$line] =~ /^-/);
1445 $blk .= $lines[$line] . "\n";
1446 $len = length($blk);
1450 # Bail if there is no further context.
1451 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1455 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1461 $c = substr($blk, $off, 1);
1462 $remainder = substr($blk, $off);
1464 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1466 # Handle nested #if/#else.
1467 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1468 push(@stack, [ $type, $level ]);
1469 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1470 ($type, $level) = @{$stack[$#stack - 1]};
1471 } elsif ($remainder =~ /^#\s*endif\b/) {
1472 ($type, $level) = @{pop(@stack)};
1475 # Statement ends at the ';' or a close '}' at the
1477 if ($level == 0 && $c eq ';') {
1481 # An else is really a conditional as long as its not else if
1482 if ($level == 0 && $coff_set == 0 &&
1483 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1484 $remainder =~ /^(else)(?:\s|{)/ &&
1485 $remainder !~ /^else\s+if\b/) {
1486 $coff = $off + length($1) - 1;
1488 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1489 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1492 if (($type eq '' || $type eq '(') && $c eq '(') {
1496 if ($type eq '(' && $c eq ')') {
1498 $type = ($level != 0)? '(' : '';
1500 if ($level == 0 && $coff < $soff) {
1503 #warn "CSB: mark coff<$coff>\n";
1506 if (($type eq '' || $type eq '{') && $c eq '{') {
1510 if ($type eq '{' && $c eq '}') {
1512 $type = ($level != 0)? '{' : '';
1515 if (substr($blk, $off + 1, 1) eq ';') {
1521 # Preprocessor commands end at the newline unless escaped.
1522 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1530 # We are truly at the end, so shuffle to the next line.
1537 my $statement = substr($blk, $soff, $off - $soff + 1);
1538 my $condition = substr($blk, $soff, $coff - $soff + 1);
1540 #warn "STATEMENT<$statement>\n";
1541 #warn "CONDITION<$condition>\n";
1543 #print "coff<$coff> soff<$off> loff<$loff>\n";
1545 return ($statement, $condition,
1546 $line, $remain + 1, $off - $loff + 1, $level);
1549 sub statement_lines {
1552 # Strip the diff line prefixes and rip blank lines at start and end.
1553 $stmt =~ s/(^|\n)./$1/g;
1557 my @stmt_lines = ($stmt =~ /\n/g);
1559 return $#stmt_lines + 2;
1562 sub statement_rawlines {
1565 my @stmt_lines = ($stmt =~ /\n/g);
1567 return $#stmt_lines + 2;
1570 sub statement_block_size {
1573 $stmt =~ s/(^|\n)./$1/g;
1579 my @stmt_lines = ($stmt =~ /\n/g);
1580 my @stmt_statements = ($stmt =~ /;/g);
1582 my $stmt_lines = $#stmt_lines + 2;
1583 my $stmt_statements = $#stmt_statements + 1;
1585 if ($stmt_lines > $stmt_statements) {
1588 return $stmt_statements;
1592 sub ctx_statement_full {
1593 my ($linenr, $remain, $off) = @_;
1594 my ($statement, $condition, $level);
1598 # Grab the first conditional/block pair.
1599 ($statement, $condition, $linenr, $remain, $off, $level) =
1600 ctx_statement_block($linenr, $remain, $off);
1601 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1602 push(@chunks, [ $condition, $statement ]);
1603 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1604 return ($level, $linenr, @chunks);
1607 # Pull in the following conditional/block pairs and see if they
1608 # could continue the statement.
1610 ($statement, $condition, $linenr, $remain, $off, $level) =
1611 ctx_statement_block($linenr, $remain, $off);
1612 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1613 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1615 push(@chunks, [ $condition, $statement ]);
1618 return ($level, $linenr, @chunks);
1622 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1624 my $start = $linenr - 1;
1631 my @stack = ($level);
1632 for ($line = $start; $remain > 0; $line++) {
1633 next if ($rawlines[$line] =~ /^-/);
1636 $blk .= $rawlines[$line];
1638 # Handle nested #if/#else.
1639 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1640 push(@stack, $level);
1641 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1642 $level = $stack[$#stack - 1];
1643 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1644 $level = pop(@stack);
1647 foreach my $c (split(//, $lines[$line])) {
1648 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1654 if ($c eq $close && $level > 0) {
1656 last if ($level == 0);
1657 } elsif ($c eq $open) {
1662 if (!$outer || $level <= 1) {
1663 push(@res, $rawlines[$line]);
1666 last if ($level == 0);
1669 return ($level, @res);
1671 sub ctx_block_outer {
1672 my ($linenr, $remain) = @_;
1674 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1678 my ($linenr, $remain) = @_;
1680 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1684 my ($linenr, $remain, $off) = @_;
1686 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1689 sub ctx_block_level {
1690 my ($linenr, $remain) = @_;
1692 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1694 sub ctx_statement_level {
1695 my ($linenr, $remain, $off) = @_;
1697 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1700 sub ctx_locate_comment {
1701 my ($first_line, $end_line) = @_;
1703 # If c99 comment on the current line, or the line before or after
1704 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1705 return $current_comment if (defined $current_comment);
1706 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1707 return $current_comment if (defined $current_comment);
1708 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1709 return $current_comment if (defined $current_comment);
1711 # Catch a comment on the end of the line itself.
1712 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1713 return $current_comment if (defined $current_comment);
1715 # Look through the context and try and figure out if there is a
1718 $current_comment = '';
1719 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1720 my $line = $rawlines[$linenr - 1];
1722 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1725 if ($line =~ m@/\*@) {
1728 if (!$in_comment && $current_comment ne '') {
1729 $current_comment = '';
1731 $current_comment .= $line . "\n" if ($in_comment);
1732 if ($line =~ m@\*/@) {
1737 chomp($current_comment);
1738 return($current_comment);
1740 sub ctx_has_comment {
1741 my ($first_line, $end_line) = @_;
1742 my $cmt = ctx_locate_comment($first_line, $end_line);
1744 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1745 ##print "CMMT: $cmt\n";
1747 return ($cmt ne '');
1751 my ($linenr, $cnt) = @_;
1753 my $offset = $linenr - 1;
1758 $line = $rawlines[$offset++];
1759 next if (defined($line) && $line =~ /^-/);
1767 my ($linenr, $lc) = @_;
1769 my $stat_real = raw_line($linenr, 0);
1770 for (my $count = $linenr + 1; $count <= $lc; $count++) {
1771 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1778 my ($linenr, $cnt, $here) = @_;
1780 my $herectx = $here . "\n";
1781 for (my $n = 0; $n < $cnt; $n++) {
1782 $herectx .= raw_line($linenr, $n) . "\n";
1793 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1796 $coded = sprintf("^%c", unpack('C', $2) + 64);
1805 my $av_preprocessor = 0;
1810 sub annotate_reset {
1811 $av_preprocessor = 0;
1813 @av_paren_type = ('E');
1814 $av_pend_colon = 'O';
1817 sub annotate_values {
1818 my ($stream, $type) = @_;
1821 my $var = '_' x length($stream);
1824 print "$stream\n" if ($dbg_values > 1);
1826 while (length($cur)) {
1827 @av_paren_type = ('E') if ($#av_paren_type < 0);
1828 print " <" . join('', @av_paren_type) .
1829 "> <$type> <$av_pending>" if ($dbg_values > 1);
1830 if ($cur =~ /^(\s+)/o) {
1831 print "WS($1)\n" if ($dbg_values > 1);
1832 if ($1 =~ /\n/ && $av_preprocessor) {
1833 $type = pop(@av_paren_type);
1834 $av_preprocessor = 0;
1837 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1838 print "CAST($1)\n" if ($dbg_values > 1);
1839 push(@av_paren_type, $type);
1842 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1843 print "DECLARE($1)\n" if ($dbg_values > 1);
1846 } elsif ($cur =~ /^($Modifier)\s*/) {
1847 print "MODIFIER($1)\n" if ($dbg_values > 1);
1850 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1851 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1852 $av_preprocessor = 1;
1853 push(@av_paren_type, $type);
1859 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1860 print "UNDEF($1)\n" if ($dbg_values > 1);
1861 $av_preprocessor = 1;
1862 push(@av_paren_type, $type);
1864 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1865 print "PRE_START($1)\n" if ($dbg_values > 1);
1866 $av_preprocessor = 1;
1868 push(@av_paren_type, $type);
1869 push(@av_paren_type, $type);
1872 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1873 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1874 $av_preprocessor = 1;
1876 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1880 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1881 print "PRE_END($1)\n" if ($dbg_values > 1);
1883 $av_preprocessor = 1;
1885 # Assume all arms of the conditional end as this
1886 # one does, and continue as if the #endif was not here.
1887 pop(@av_paren_type);
1888 push(@av_paren_type, $type);
1891 } elsif ($cur =~ /^(\\\n)/o) {
1892 print "PRECONT($1)\n" if ($dbg_values > 1);
1894 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1895 print "ATTR($1)\n" if ($dbg_values > 1);
1896 $av_pending = $type;
1899 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1900 print "SIZEOF($1)\n" if ($dbg_values > 1);
1906 } elsif ($cur =~ /^(if|while|for)\b/o) {
1907 print "COND($1)\n" if ($dbg_values > 1);
1911 } elsif ($cur =~/^(case)/o) {
1912 print "CASE($1)\n" if ($dbg_values > 1);
1913 $av_pend_colon = 'C';
1916 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1917 print "KEYWORD($1)\n" if ($dbg_values > 1);
1920 } elsif ($cur =~ /^(\()/o) {
1921 print "PAREN('$1')\n" if ($dbg_values > 1);
1922 push(@av_paren_type, $av_pending);
1926 } elsif ($cur =~ /^(\))/o) {
1927 my $new_type = pop(@av_paren_type);
1928 if ($new_type ne '_') {
1930 print "PAREN('$1') -> $type\n"
1931 if ($dbg_values > 1);
1933 print "PAREN('$1')\n" if ($dbg_values > 1);
1936 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1937 print "FUNC($1)\n" if ($dbg_values > 1);
1941 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1942 if (defined $2 && $type eq 'C' || $type eq 'T') {
1943 $av_pend_colon = 'B';
1944 } elsif ($type eq 'E') {
1945 $av_pend_colon = 'L';
1947 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1950 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1951 print "IDENT($1)\n" if ($dbg_values > 1);
1954 } elsif ($cur =~ /^($Assignment)/o) {
1955 print "ASSIGN($1)\n" if ($dbg_values > 1);
1958 } elsif ($cur =~/^(;|{|})/) {
1959 print "END($1)\n" if ($dbg_values > 1);
1961 $av_pend_colon = 'O';
1963 } elsif ($cur =~/^(,)/) {
1964 print "COMMA($1)\n" if ($dbg_values > 1);
1967 } elsif ($cur =~ /^(\?)/o) {
1968 print "QUESTION($1)\n" if ($dbg_values > 1);
1971 } elsif ($cur =~ /^(:)/o) {
1972 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1974 substr($var, length($res), 1, $av_pend_colon);
1975 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1980 $av_pend_colon = 'O';
1982 } elsif ($cur =~ /^(\[)/o) {
1983 print "CLOSE($1)\n" if ($dbg_values > 1);
1986 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1989 print "OPV($1)\n" if ($dbg_values > 1);
1996 substr($var, length($res), 1, $variant);
1999 } elsif ($cur =~ /^($Operators)/o) {
2000 print "OP($1)\n" if ($dbg_values > 1);
2001 if ($1 ne '++' && $1 ne '--') {
2005 } elsif ($cur =~ /(^.)/o) {
2006 print "C($1)\n" if ($dbg_values > 1);
2009 $cur = substr($cur, length($1));
2010 $res .= $type x length($1);
2014 return ($res, $var);
2018 my ($possible, $line) = @_;
2019 my $notPermitted = qr{(?:
2036 ^(?:typedef|struct|enum)\b
2038 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2039 if ($possible !~ $notPermitted) {
2040 # Check for modifiers.
2041 $possible =~ s/\s*$Storage\s*//g;
2042 $possible =~ s/\s*$Sparse\s*//g;
2043 if ($possible =~ /^\s*$/) {
2045 } elsif ($possible =~ /\s/) {
2046 $possible =~ s/\s*$Type\s*//g;
2047 for my $modifier (split(' ', $possible)) {
2048 if ($modifier !~ $notPermitted) {
2049 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2050 push(@modifierListFile, $modifier);
2055 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2056 push(@typeListFile, $possible);
2060 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2069 $type =~ tr/[a-z]/[A-Z]/;
2071 return defined $use_type{$type} if (scalar keys %use_type > 0);
2073 return !defined $ignore_type{$type};
2077 my ($level, $type, $msg) = @_;
2079 if (!show_type($type) ||
2080 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2085 if ($level eq 'ERROR') {
2087 } elsif ($level eq 'WARNING') {
2093 $output .= $prefix . $level . ':';
2095 $output .= BLUE if ($color);
2096 $output .= "$type:";
2098 $output .= RESET if ($color);
2099 $output .= ' ' . $msg . "\n";
2102 my @lines = split("\n", $output, -1);
2103 splice(@lines, 1, 1);
2104 $output = join("\n", @lines);
2106 $output = (split('\n', $output))[0] . "\n" if ($terse);
2108 push(our @report, $output);
2117 sub fixup_current_range {
2118 my ($lineRef, $offset, $length) = @_;
2120 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2123 my $no = $o + $offset;
2124 my $nl = $l + $length;
2125 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2129 sub fix_inserted_deleted_lines {
2130 my ($linesRef, $insertedRef, $deletedRef) = @_;
2132 my $range_last_linenr = 0;
2133 my $delta_offset = 0;
2138 my $next_insert = 0;
2139 my $next_delete = 0;
2143 my $inserted = @{$insertedRef}[$next_insert++];
2144 my $deleted = @{$deletedRef}[$next_delete++];
2146 foreach my $old_line (@{$linesRef}) {
2148 my $line = $old_line; #don't modify the array
2149 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
2151 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
2152 $range_last_linenr = $new_linenr;
2153 fixup_current_range(\$line, $delta_offset, 0);
2156 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2157 $deleted = @{$deletedRef}[$next_delete++];
2159 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2162 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2163 push(@lines, ${$inserted}{'LINE'});
2164 $inserted = @{$insertedRef}[$next_insert++];
2166 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2170 push(@lines, $line);
2180 sub fix_insert_line {
2181 my ($linenr, $line) = @_;
2187 push(@fixed_inserted, $inserted);
2190 sub fix_delete_line {
2191 my ($linenr, $line) = @_;
2198 push(@fixed_deleted, $deleted);
2202 my ($type, $msg) = @_;
2204 if (report("ERROR", $type, $msg)) {
2212 my ($type, $msg) = @_;
2214 if (report("WARNING", $type, $msg)) {
2222 my ($type, $msg) = @_;
2224 if ($check && report("CHECK", $type, $msg)) {
2232 sub check_absolute_file {
2233 my ($absolute, $herecurr) = @_;
2234 my $file = $absolute;
2236 ##print "absolute<$absolute>\n";
2238 # See if any suffix of this path is a path within the tree.
2239 while ($file =~ s@^[^/]*/@@) {
2240 if (-f "$root/$file") {
2241 ##print "file<$file>\n";
2249 # It is, so see if the prefix is acceptable.
2250 my $prefix = $absolute;
2251 substr($prefix, -length($file)) = '';
2253 ##print "prefix<$prefix>\n";
2254 if ($prefix ne ".../") {
2255 WARN("USE_RELATIVE_PATH",
2256 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2263 $string =~ s/^\s+|\s+$//g;
2271 $string =~ s/^\s+//;
2279 $string =~ s/\s+$//;
2284 sub string_find_replace {
2285 my ($string, $find, $replace) = @_;
2287 $string =~ s/$find/$replace/g;
2295 my $source_indent = $tabsize;
2296 my $max_spaces_before_tab = $source_indent - 1;
2297 my $spaces_to_tab = " " x $source_indent;
2299 #convert leading spaces to tabs
2300 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2301 #Remove spaces before a tab
2302 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2307 sub pos_last_openparen {
2312 my $opens = $line =~ tr/\(/\(/;
2313 my $closes = $line =~ tr/\)/\)/;
2315 my $last_openparen = 0;
2317 if (($opens == 0) || ($closes >= $opens)) {
2321 my $len = length($line);
2323 for ($pos = 0; $pos < $len; $pos++) {
2324 my $string = substr($line, $pos);
2325 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2326 $pos += length($1) - 1;
2327 } elsif (substr($line, $pos, 1) eq '(') {
2328 $last_openparen = $pos;
2329 } elsif (index($string, '(') == -1) {
2334 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2337 sub get_raw_comment {
2338 my ($line, $rawline) = @_;
2341 for my $i (0 .. (length($line) - 1)) {
2342 if (substr($line, $i, 1) eq "$;") {
2343 $comment .= substr($rawline, $i, 1);
2351 my $filename = shift;
2357 my $stashrawline="";
2367 my $authorsignoff = 0;
2369 my $is_binding_patch = -1;
2370 my $in_header_lines = $file ? 0 : 1;
2371 my $in_commit_log = 0; #Scanning lines before patch
2372 my $has_patch_separator = 0; #Found a --- line
2373 my $has_commit_log = 0; #Encountered lines before patch
2374 my $commit_log_lines = 0; #Number of commit log lines
2375 my $commit_log_possible_stack_dump = 0;
2376 my $commit_log_long_line = 0;
2377 my $commit_log_has_diff = 0;
2378 my $reported_maintainer_file = 0;
2379 my $non_utf8_charset = 0;
2381 my $last_blank_line = 0;
2382 my $last_coalesced_string_linenr = -1;
2390 # Trace the real file/line as we go.
2395 my $context_function; #undef'd unless there's a known function
2397 my $comment_edge = 0;
2401 my $prev_values = 'E';
2404 my %suppress_ifbraces;
2405 my %suppress_whiletrailers;
2406 my %suppress_export;
2407 my $suppress_statement = 0;
2409 my %signatures = ();
2411 # Pre-scan the patch sanitizing the lines.
2412 # Pre-scan the patch looking for any __setup documentation.
2414 my @setup_docs = ();
2417 my $camelcase_file_seeded = 0;
2419 my $checklicenseline = 1;
2421 sanitise_line_reset();
2423 foreach my $rawline (@rawlines) {
2427 push(@fixed, $rawline) if ($fix);
2429 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2431 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2436 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2445 # Guestimate if this is a continuing comment. Run
2446 # the context looking for a comment "edge". If this
2447 # edge is a close comment then we must be in a comment
2451 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2452 next if (defined $rawlines[$ln - 1] &&
2453 $rawlines[$ln - 1] =~ /^-/);
2455 #print "RAW<$rawlines[$ln - 1]>\n";
2456 last if (!defined $rawlines[$ln - 1]);
2457 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2458 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2463 if (defined $edge && $edge eq '*/') {
2467 # Guestimate if this is a continuing comment. If this
2468 # is the start of a diff block and this line starts
2469 # ' *' then it is very likely a comment.
2470 if (!defined $edge &&
2471 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2476 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2477 sanitise_line_reset($in_comment);
2479 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2480 # Standardise the strings and chars within the input to
2481 # simplify matching -- only bother with positive lines.
2482 $line = sanitise_line($rawline);
2484 push(@lines, $line);
2487 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2492 #print "==>$rawline\n";
2493 #print "-->$line\n";
2495 if ($setup_docs && $line =~ /^\+/) {
2496 push(@setup_docs, $line);
2505 foreach my $line (@lines) {
2508 my $sline = $line; #copy of $line
2509 $sline =~ s/$;/ /g; #with comments as spaces
2511 my $rawline = $rawlines[$linenr - 1];
2512 my $raw_comment = get_raw_comment($line, $rawline);
2514 # check if it's a mode change, rename or start of a patch
2515 if (!$in_commit_log &&
2516 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2517 ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2518 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2522 #extract the line range in the file after the patch is applied
2523 if (!$in_commit_log &&
2524 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2527 $first_line = $linenr + 1;
2537 %suppress_ifbraces = ();
2538 %suppress_whiletrailers = ();
2539 %suppress_export = ();
2540 $suppress_statement = 0;
2541 if ($context =~ /\b(\w+)\s*\(/) {
2542 $context_function = $1;
2544 undef $context_function;
2548 # track the line number as we move through the hunk, note that
2549 # new versions of GNU diff omit the leading space on completely
2550 # blank context lines so we need to count that too.
2551 } elsif ($line =~ /^( |\+|$)/) {
2553 $realcnt-- if ($realcnt != 0);
2555 # Measure the line length and indent.
2556 ($length, $indent) = line_stats($rawline);
2558 # Track the previous line.
2559 ($prevline, $stashline) = ($stashline, $line);
2560 ($previndent, $stashindent) = ($stashindent, $indent);
2561 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2563 #warn "line<$line>\n";
2565 } elsif ($realcnt == 1) {
2569 my $hunk_line = ($realcnt != 0);
2571 $here = "#$linenr: " if (!$file);
2572 $here = "#$realline: " if ($file);
2575 # extract the filename as it passes
2576 if ($line =~ /^diff --git.*?(\S+)$/) {
2578 $realfile =~ s@^([^/]*)/@@ if (!$file);
2581 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2583 $realfile =~ s@^([^/]*)/@@ if (!$file);
2587 if (!$file && $tree && $p1_prefix ne '' &&
2588 -e "$root/$p1_prefix") {
2589 WARN("PATCH_PREFIX",
2590 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2593 if ($realfile =~ m@^include/asm/@) {
2594 ERROR("MODIFIED_INCLUDE_ASM",
2595 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2600 #make up the handle for any error we report on this line
2602 $prefix = "$realfile:$realline: "
2605 $prefix = "$filename:$realline: ";
2607 $prefix = "$filename:$linenr: ";
2612 if (is_maintained_obsolete($realfile)) {
2614 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n");
2616 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2619 $check = $check_orig;
2621 $checklicenseline = 1;
2623 if ($realfile !~ /^MAINTAINERS/) {
2624 my $last_binding_patch = $is_binding_patch;
2626 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2628 if (($last_binding_patch != -1) &&
2629 ($last_binding_patch ^ $is_binding_patch)) {
2630 WARN("DT_SPLIT_BINDING_PATCH",
2631 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2638 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2640 my $hereline = "$here\n$rawline\n";
2641 my $herecurr = "$here\n$rawline\n";
2642 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2644 $cnt_lines++ if ($realcnt != 0);
2646 # Verify the existence of a commit log if appropriate
2647 # 2 is used because a $signature is counted in $commit_log_lines
2648 if ($in_commit_log) {
2649 if ($line !~ /^\s*$/) {
2650 $commit_log_lines++; #could be a $signature
2652 } elsif ($has_commit_log && $commit_log_lines < 2) {
2653 WARN("COMMIT_MESSAGE",
2654 "Missing commit description - Add an appropriate one\n");
2655 $commit_log_lines = 2; #warn only once
2658 # Check if the commit log has what seems like a diff which can confuse patch
2659 if ($in_commit_log && !$commit_log_has_diff &&
2660 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2661 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2662 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2663 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2664 ERROR("DIFF_IN_COMMIT_MSG",
2665 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2666 $commit_log_has_diff = 1;
2669 # Check for incorrect file permissions
2670 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2671 my $permhere = $here . "FILE: $realfile\n";
2672 if ($realfile !~ m@scripts/@ &&
2673 $realfile !~ /\.(py|pl|awk|sh)$/) {
2674 ERROR("EXECUTE_PERMISSIONS",
2675 "do not set execute permissions for source files\n" . $permhere);
2679 # Check the patch for a From:
2680 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2682 my $curline = $linenr;
2683 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2686 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2688 $author = reformat_email($author);
2691 # Check the patch for a signoff:
2692 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2695 if ($author ne '') {
2696 if (same_email_addresses($1, $author)) {
2702 # Check for patch separator
2703 if ($line =~ /^---$/) {
2704 $has_patch_separator = 1;
2708 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2709 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2710 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2711 $reported_maintainer_file = 1;
2714 # Check signature styles
2715 if (!$in_header_lines &&
2716 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2717 my $space_before = $1;
2719 my $space_after = $3;
2721 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2723 if ($sign_off !~ /$signature_tags/) {
2724 WARN("BAD_SIGN_OFF",
2725 "Non-standard signature: $sign_off\n" . $herecurr);
2727 if (defined $space_before && $space_before ne "") {
2728 if (WARN("BAD_SIGN_OFF",
2729 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2731 $fixed[$fixlinenr] =
2732 "$ucfirst_sign_off $email";
2735 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2736 if (WARN("BAD_SIGN_OFF",
2737 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2739 $fixed[$fixlinenr] =
2740 "$ucfirst_sign_off $email";
2744 if (!defined $space_after || $space_after ne " ") {
2745 if (WARN("BAD_SIGN_OFF",
2746 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2748 $fixed[$fixlinenr] =
2749 "$ucfirst_sign_off $email";
2753 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2754 my $suggested_email = format_email(($email_name, $email_address));
2755 if ($suggested_email eq "") {
2756 ERROR("BAD_SIGN_OFF",
2757 "Unrecognized email address: '$email'\n" . $herecurr);
2759 my $dequoted = $suggested_email;
2760 $dequoted =~ s/^"//;
2761 $dequoted =~ s/" </ </;
2762 # Don't force email to have quotes
2763 # Allow just an angle bracketed address
2764 if (!same_email_addresses($email, $suggested_email)) {
2765 WARN("BAD_SIGN_OFF",
2766 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2770 # Check for duplicate signatures
2771 my $sig_nospace = $line;
2772 $sig_nospace =~ s/\s//g;
2773 $sig_nospace = lc($sig_nospace);
2774 if (defined $signatures{$sig_nospace}) {
2775 WARN("BAD_SIGN_OFF",
2776 "Duplicate signature\n" . $herecurr);
2778 $signatures{$sig_nospace} = 1;
2781 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2782 if ($sign_off =~ /^co-developed-by:$/i) {
2783 if ($email eq $author) {
2784 WARN("BAD_SIGN_OFF",
2785 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2787 if (!defined $lines[$linenr]) {
2788 WARN("BAD_SIGN_OFF",
2789 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2790 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2791 WARN("BAD_SIGN_OFF",
2792 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2793 } elsif ($1 ne $email) {
2794 WARN("BAD_SIGN_OFF",
2795 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2800 # Check email subject for common tools that don't need to be mentioned
2801 if ($in_header_lines &&
2802 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2803 WARN("EMAIL_SUBJECT",
2804 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2807 # Check for Gerrit Change-Ids not in any patch context
2808 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2809 ERROR("GERRIT_CHANGE_ID",
2810 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr);
2813 # Check if the commit log is in a possible stack dump
2814 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2815 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2816 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2818 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2819 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2820 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2821 # stack dump address styles
2822 $commit_log_possible_stack_dump = 1;
2825 # Check for line lengths > 75 in commit log, warn once
2826 if ($in_commit_log && !$commit_log_long_line &&
2827 length($line) > 75 &&
2828 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2829 # file delta changes
2830 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2832 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2833 # A Fixes: or Link: line
2834 $commit_log_possible_stack_dump)) {
2835 WARN("COMMIT_LOG_LONG_LINE",
2836 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2837 $commit_log_long_line = 1;
2840 # Reset possible stack dump if a blank line is found
2841 if ($in_commit_log && $commit_log_possible_stack_dump &&
2843 $commit_log_possible_stack_dump = 0;
2846 # Check for git id commit length and improperly formed commit descriptions
2847 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2848 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
2849 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2850 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2851 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2852 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2853 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2854 my $init_char = "c";
2855 my $orig_commit = "";
2862 my $id = '0123456789ab';
2863 my $orig_desc = "commit description";
2864 my $description = "";
2866 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2868 $orig_commit = lc($2);
2869 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2870 $orig_commit = lc($1);
2873 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2874 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2875 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2876 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2877 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2880 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2881 defined $rawlines[$linenr] &&
2882 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2885 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2886 defined $rawlines[$linenr] &&
2887 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2888 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2890 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2891 $orig_desc .= " " . $1;
2895 ($id, $description) = git_commit_info($orig_commit,
2899 ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2900 ERROR("GIT_COMMIT_ID",
2901 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2905 # Check for added, moved or deleted files
2906 if (!$reported_maintainer_file && !$in_commit_log &&
2907 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2908 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2909 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2910 (defined($1) || defined($2))))) {
2912 $reported_maintainer_file = 1;
2913 WARN("FILE_PATH_CHANGES",
2914 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2917 # Check for adding new DT bindings not in schema format
2918 if (!$in_commit_log &&
2919 ($line =~ /^new file mode\s*\d+\s*$/) &&
2920 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
2921 WARN("DT_SCHEMA_BINDING_PATCH",
2922 "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
2925 # Check for wrappage within a valid hunk of the file
2926 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2927 ERROR("CORRUPTED_PATCH",
2928 "patch seems to be corrupt (line wrapped?)\n" .
2929 $herecurr) if (!$emitted_corrupt++);
2932 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2933 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2934 $rawline !~ m/^$UTF8*$/) {
2935 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2937 my $blank = copy_spacing($rawline);
2938 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2939 my $hereptr = "$hereline$ptr\n";
2942 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2945 # Check if it's the start of a commit log
2946 # (not a header line and we haven't seen the patch filename)
2947 if ($in_header_lines && $realfile =~ /^$/ &&
2948 !($rawline =~ /^\s+(?:\S|$)/ ||
2949 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2950 $in_header_lines = 0;
2952 $has_commit_log = 1;
2955 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2956 # declined it, i.e defined some charset where it is missing.
2957 if ($in_header_lines &&
2958 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2960 $non_utf8_charset = 1;
2963 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2964 $rawline =~ /$NON_ASCII_UTF8/) {
2965 WARN("UTF8_BEFORE_PATCH",
2966 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2969 # Check for absolute kernel paths in commit message
2970 if ($tree && $in_commit_log) {
2971 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2974 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2975 check_absolute_file($1, $herecurr)) {
2978 check_absolute_file($file, $herecurr);
2983 # Check for various typo / spelling mistakes
2984 if (defined($misspellings) &&
2985 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2986 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2988 my $typo_fix = $spelling_fix{lc($typo)};
2989 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2990 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2991 my $msg_level = \&WARN;
2992 $msg_level = \&CHK if ($file);
2993 if (&{$msg_level}("TYPO_SPELLING",
2994 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2996 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3001 # check for invalid commit id
3002 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3005 ($id, $description) = git_commit_info($2, undef, undef);
3006 if (!defined($id)) {
3007 WARN("UNKNOWN_COMMIT_ID",
3008 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3012 # check for repeated words separated by a single space
3013 if ($rawline =~ /^\+/ || $in_commit_log) {
3014 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3019 if ($first =~ /(?:struct|union|enum)/) {
3020 pos($rawline) += length($first) + length($second) + 1;
3024 next if ($first ne $second);
3025 next if ($first eq 'long');
3027 if (WARN("REPEATED_WORD",
3028 "Possible repeated word: '$first'\n" . $herecurr) &&
3030 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3034 # if it's a repeated word on consecutive lines in a comment block
3035 if ($prevline =~ /$;+\s*$/ &&
3036 $prevrawline =~ /($word_pattern)\s*$/) {
3038 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3039 if (WARN("REPEATED_WORD",
3040 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3042 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3048 # ignore non-hunk lines and lines being removed
3049 next if (!$hunk_line || $line =~ /^-/);
3051 #trailing whitespace
3052 if ($line =~ /^\+.*\015/) {
3053 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3054 if (ERROR("DOS_LINE_ENDINGS",
3055 "DOS line endings\n" . $herevet) &&
3057 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3059 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3060 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3061 if (ERROR("TRAILING_WHITESPACE",
3062 "trailing whitespace\n" . $herevet) &&
3064 $fixed[$fixlinenr] =~ s/\s+$//;
3070 # Check for FSF mailing addresses.
3071 if ($rawline =~ /\bwrite to the Free/i ||
3072 $rawline =~ /\b675\s+Mass\s+Ave/i ||
3073 $rawline =~ /\b59\s+Temple\s+Pl/i ||
3074 $rawline =~ /\b51\s+Franklin\s+St/i) {
3075 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3076 my $msg_level = \&ERROR;
3077 $msg_level = \&CHK if ($file);
3078 &{$msg_level}("FSF_MAILING_ADDRESS",
3079 "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)
3082 # check for Kconfig help text having a real description
3083 # Only applies when adding the entry originally, after that we do not have
3084 # sufficient context to determine whether it is indeed long enough.
3085 if ($realfile =~ /Kconfig/ &&
3086 # 'choice' is usually the last thing on the line (though
3087 # Kconfig supports named choices), so use a word boundary
3088 # (\b) rather than a whitespace character (\s)
3089 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3092 my $ln = $linenr + 1;
3096 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3097 $f = $lines[$ln - 1];
3098 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3099 $is_end = $lines[$ln - 1] =~ /^\+/;
3101 next if ($f =~ /^-/);
3102 last if (!$file && $f =~ /^\@\@/);
3104 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3106 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3113 next if ($f =~ /^$/);
3115 # This only checks context lines in the patch
3116 # and so hopefully shouldn't trigger false
3117 # positives, even though some of these are
3118 # common words in help texts
3119 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3120 if|endif|menu|endmenu|source)\b/x) {
3126 if ($is_start && $is_end && $length < $min_conf_desc_length) {
3127 WARN("CONFIG_DESCRIPTION",
3128 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3130 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3133 # check MAINTAINERS entries
3134 if ($realfile =~ /^MAINTAINERS$/) {
3135 # check MAINTAINERS entries for the right form
3136 if ($rawline =~ /^\+[A-Z]:/ &&
3137 $rawline !~ /^\+[A-Z]:\t\S/) {
3138 if (WARN("MAINTAINERS_STYLE",
3139 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3141 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3144 # check MAINTAINERS entries for the right ordering too
3145 my $preferred_order = 'MRLSWQBCPTFXNK';
3146 if ($rawline =~ /^\+[A-Z]:/ &&
3147 $prevrawline =~ /^[\+ ][A-Z]:/) {
3148 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3151 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3154 my $curindex = index($preferred_order, $cur);
3155 my $previndex = index($preferred_order, $prev);
3156 if ($curindex < 0) {
3157 WARN("MAINTAINERS_STYLE",
3158 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3160 if ($previndex >= 0 && $curindex < $previndex) {
3161 WARN("MAINTAINERS_STYLE",
3162 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3163 } elsif ((($prev eq 'F' && $cur eq 'F') ||
3164 ($prev eq 'X' && $cur eq 'X')) &&
3165 ($prevval cmp $curval) > 0) {
3166 WARN("MAINTAINERS_STYLE",
3167 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3173 # discourage the use of boolean for type definition attributes of Kconfig options
3174 if ($realfile =~ /Kconfig/ &&
3175 $line =~ /^\+\s*\bboolean\b/) {
3176 WARN("CONFIG_TYPE_BOOLEAN",
3177 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3180 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3181 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3184 'EXTRA_AFLAGS' => 'asflags-y',
3185 'EXTRA_CFLAGS' => 'ccflags-y',
3186 'EXTRA_CPPFLAGS' => 'cppflags-y',
3187 'EXTRA_LDFLAGS' => 'ldflags-y',
3190 WARN("DEPRECATED_VARIABLE",
3191 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3194 # check for DT compatible documentation
3195 if (defined $root &&
3196 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3197 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3199 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3201 my $dt_path = $root . "/Documentation/devicetree/bindings/";
3202 my $vp_file = $dt_path . "vendor-prefixes.yaml";
3204 foreach my $compat (@compats) {
3205 my $compat2 = $compat;
3206 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3207 my $compat3 = $compat;
3208 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3209 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3211 WARN("UNDOCUMENTED_DT_STRING",
3212 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3215 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3217 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3219 WARN("UNDOCUMENTED_DT_STRING",
3220 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3225 # check for using SPDX license tag at beginning of files
3226 if ($realline == $checklicenseline) {
3227 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3228 $checklicenseline = 2;
3229 } elsif ($rawline =~ /^\+/) {
3231 if ($realfile =~ /\.(h|s|S)$/) {
3233 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3235 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3237 } elsif ($realfile =~ /\.rst$/) {
3241 # check SPDX comment style for .[chsS] files
3242 if ($realfile =~ /\.[chsS]$/ &&
3243 $rawline =~ /SPDX-License-Identifier:/ &&
3244 $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3245 WARN("SPDX_LICENSE_TAG",
3246 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3249 if ($comment !~ /^$/ &&
3250 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3251 WARN("SPDX_LICENSE_TAG",
3252 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3253 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3254 my $spdx_license = $1;
3255 if (!is_SPDX_License_valid($spdx_license)) {
3256 WARN("SPDX_LICENSE_TAG",
3257 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3259 if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3260 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3261 my $msg_level = \&WARN;
3262 $msg_level = \&CHK if ($file);
3263 if (&{$msg_level}("SPDX_LICENSE_TAG",
3265 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3267 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3274 # check we are in a valid source file if not then ignore this hunk
3275 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3277 # check for using SPDX-License-Identifier on the wrong line number
3278 if ($realline != $checklicenseline &&
3279 $rawline =~ /\bSPDX-License-Identifier:/ &&
3280 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3281 WARN("SPDX_LICENSE_TAG",
3282 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3285 # line length limit (with some exclusions)
3287 # There are a few types of lines that may extend beyond $max_line_length:
3288 # logging functions like pr_info that end in a string
3289 # lines with a single string
3290 # #defines that are a single string
3291 # lines with an RFC3986 like URL
3293 # There are 3 different line length message types:
3294 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length
3295 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
3296 # LONG_LINE all other lines longer than $max_line_length
3298 # if LONG_LINE is ignored, the other 2 types are also ignored
3301 if ($line =~ /^\+/ && $length > $max_line_length) {
3302 my $msg_type = "LONG_LINE";
3304 # Check the allowed long line types first
3306 # logging functions that end in a string that starts
3307 # before $max_line_length
3308 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3309 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3312 # lines with only strings (w/ possible termination)
3313 # #defines with only strings
3314 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3315 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3318 # More special cases
3319 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3320 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3323 # URL ($rawline is used in case the URL is in a comment)
3324 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3327 # Otherwise set the alternate message types
3329 # a comment starts before $max_line_length
3330 } elsif ($line =~ /($;[\s$;]*)$/ &&
3331 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3332 $msg_type = "LONG_LINE_COMMENT"
3334 # a quoted string starts before $max_line_length
3335 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3336 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3337 $msg_type = "LONG_LINE_STRING"
3340 if ($msg_type ne "" &&
3341 (show_type("LONG_LINE") || show_type($msg_type))) {
3342 my $msg_level = \&WARN;
3343 $msg_level = \&CHK if ($file);
3344 &{$msg_level}($msg_type,
3345 "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3349 # check for adding lines without a newline.
3350 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3351 WARN("MISSING_EOF_NEWLINE",
3352 "adding a line without newline at end of file\n" . $herecurr);
3355 # check we are in a valid source file C or perl if not then ignore this hunk
3356 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3358 # at the beginning of a line any tabs must come first and anything
3359 # more than $tabsize must use tabs.
3360 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3361 $rawline =~ /^\+\s* \s*/) {
3362 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3364 if (ERROR("CODE_INDENT",
3365 "code indent should use tabs where possible\n" . $herevet) &&
3367 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3371 # check for space before tabs.
3372 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3373 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3374 if (WARN("SPACE_BEFORE_TAB",
3375 "please, no space before tabs\n" . $herevet) &&
3377 while ($fixed[$fixlinenr] =~
3378 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3379 while ($fixed[$fixlinenr] =~
3380 s/(^\+.*) +\t/$1\t/) {}
3384 # check for assignments on the start of a line
3385 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3386 CHK("ASSIGNMENT_CONTINUATIONS",
3387 "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3390 # check for && or || at the start of a line
3391 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3392 CHK("LOGICAL_CONTINUATIONS",
3393 "Logical continuations should be on the previous line\n" . $hereprev);
3396 # check indentation starts on a tab stop
3397 if ($perl_version_ok &&
3398 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3399 my $indent = length($1);
3400 if ($indent % $tabsize) {
3402 "Statements should start on a tabstop\n" . $herecurr) &&
3404 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3409 # check multi-line statement indentation matches previous line
3410 if ($perl_version_ok &&
3411 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3412 $prevline =~ /^\+(\t*)(.*)$/;
3416 my $pos = pos_last_openparen($rest);
3418 $line =~ /^(\+| )([ \t]*)/;
3421 my $goodtabindent = $oldindent .
3422 "\t" x ($pos / $tabsize) .
3423 " " x ($pos % $tabsize);
3424 my $goodspaceindent = $oldindent . " " x $pos;
3426 if ($newindent ne $goodtabindent &&
3427 $newindent ne $goodspaceindent) {
3429 if (CHK("PARENTHESIS_ALIGNMENT",
3430 "Alignment should match open parenthesis\n" . $hereprev) &&
3431 $fix && $line =~ /^\+/) {
3432 $fixed[$fixlinenr] =~
3433 s/^\+[ \t]*/\+$goodtabindent/;
3439 # check for space after cast like "(int) foo" or "(struct foo) bar"
3440 # avoid checking a few false positives:
3441 # "sizeof(<type>)" or "__alignof__(<type>)"
3442 # function pointer declarations like "(*foo)(int) = bar;"
3443 # structure definitions like "(struct foo) { 0 };"
3444 # multiline macros that define functions
3445 # known attributes or the __attribute__ keyword
3446 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3447 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3449 "No space is necessary after a cast\n" . $herecurr) &&
3451 $fixed[$fixlinenr] =~
3452 s/(\(\s*$Type\s*\))[ \t]+/$1/;
3456 # Block comment styles
3457 # Networking with an initial /*
3458 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3459 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3460 $rawline =~ /^\+[ \t]*\*/ &&
3462 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3463 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3466 # Block comments use * on subsequent lines
3467 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3468 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
3469 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
3470 $rawline =~ /^\+/ && #line is new
3471 $rawline !~ /^\+[ \t]*\*/) { #no leading *
3472 WARN("BLOCK_COMMENT_STYLE",
3473 "Block comments use * on subsequent lines\n" . $hereprev);
3476 # Block comments use */ on trailing lines
3477 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
3478 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
3479 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
3480 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
3481 WARN("BLOCK_COMMENT_STYLE",
3482 "Block comments use a trailing */ on a separate line\n" . $herecurr);
3485 # Block comment * alignment
3486 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
3487 $line =~ /^\+[ \t]*$;/ && #leading comment
3488 $rawline =~ /^\+[ \t]*\*/ && #leading *
3489 (($prevrawline =~ /^\+.*?\/\*/ && #leading /*
3490 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */
3491 $prevrawline =~ /^\+[ \t]*\*/)) { #leading *
3493 $prevrawline =~ m@^\+([ \t]*/?)\*@;
3495 $oldindent = expand_tabs($1);
3497 $prevrawline =~ m@^\+(.*/?)\*@;
3498 $oldindent = expand_tabs($1);
3500 $rawline =~ m@^\+([ \t]*)\*@;
3502 $newindent = expand_tabs($newindent);
3503 if (length($oldindent) ne length($newindent)) {
3504 WARN("BLOCK_COMMENT_STYLE",
3505 "Block comments should align the * on each line\n" . $hereprev);
3509 # check for missing blank lines after struct/union declarations
3510 # with exceptions for various attributes and macros
3511 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3513 !($line =~ /^\+\s*$/ ||
3514 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3515 $line =~ /^\+\s*MODULE_/i ||
3516 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3517 $line =~ /^\+[a-z_]*init/ ||
3518 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3519 $line =~ /^\+\s*DECLARE/ ||
3520 $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3521 $line =~ /^\+\s*__setup/)) {
3522 if (CHK("LINE_SPACING",
3523 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3525 fix_insert_line($fixlinenr, "\+");
3529 # check for multiple consecutive blank lines
3530 if ($prevline =~ /^[\+ ]\s*$/ &&
3531 $line =~ /^\+\s*$/ &&
3532 $last_blank_line != ($linenr - 1)) {
3533 if (CHK("LINE_SPACING",
3534 "Please don't use multiple blank lines\n" . $hereprev) &&
3536 fix_delete_line($fixlinenr, $rawline);
3539 $last_blank_line = $linenr;
3542 # check for missing blank lines after declarations
3543 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3544 # actual declarations
3545 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3546 # function pointer declarations
3547 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3548 # foo bar; where foo is some local typedef or #define
3549 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3550 # known declaration macros
3551 $prevline =~ /^\+\s+$declaration_macros/) &&
3552 # for "else if" which can look like "$Ident $Ident"
3553 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3554 # other possible extensions of declaration lines
3555 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3556 # not starting a section or a macro "\" extended line
3557 $prevline =~ /(?:\{\s*|\\)$/) &&
3558 # looks like a declaration
3559 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3560 # function pointer declarations
3561 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3562 # foo bar; where foo is some local typedef or #define
3563 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3564 # known declaration macros
3565 $sline =~ /^\+\s+$declaration_macros/ ||
3566 # start of struct or union or enum
3567 $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3568 # start or end of block or continuation of declaration
3569 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3570 # bitfield continuation
3571 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3572 # other possible extensions of declaration lines
3573 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3574 # indentation of previous and current line are the same
3575 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3576 if (WARN("LINE_SPACING",
3577 "Missing a blank line after declarations\n" . $hereprev) &&
3579 fix_insert_line($fixlinenr, "\+");
3583 # check for spaces at the beginning of a line.
3585 # 1) within comments
3586 # 2) indented preprocessor commands
3588 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3589 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3590 if (WARN("LEADING_SPACE",
3591 "please, no spaces at the start of a line\n" . $herevet) &&
3593 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3597 # check we are in a valid C source file if not then ignore this hunk
3598 next if ($realfile !~ /\.(h|c)$/);
3600 # check for unusual line ending [ or (
3601 if ($line =~ /^\+.*([\[\(])\s*$/) {
3602 CHK("OPEN_ENDED_LINE",
3603 "Lines should not end with a '$1'\n" . $herecurr);
3606 # check if this appears to be the start function declaration, save the name
3607 if ($sline =~ /^\+\{\s*$/ &&
3608 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3609 $context_function = $1;
3612 # check if this appears to be the end of function declaration
3613 if ($sline =~ /^\+\}\s*$/) {
3614 undef $context_function;
3617 # check indentation of any line with a bare else
3618 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3619 # if the previous line is a break or return and is indented 1 tab more...
3620 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3621 my $tabs = length($1) + 1;
3622 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3623 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3624 defined $lines[$linenr] &&
3625 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3626 WARN("UNNECESSARY_ELSE",
3627 "else is not generally useful after a break or return\n" . $hereprev);
3631 # check indentation of a line with a break;
3632 # if the previous line is a goto or return and is indented the same # of tabs
3633 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3635 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3636 WARN("UNNECESSARY_BREAK",
3637 "break is not useful after a goto or return\n" . $hereprev);
3641 # check for RCS/CVS revision markers
3642 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3644 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3647 # check for old HOTPLUG __dev<foo> section markings
3648 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3649 WARN("HOTPLUG_SECTION",
3650 "Using $1 is unnecessary\n" . $herecurr);
3653 # Check for potential 'bare' types
3654 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3656 #print "LINE<$line>\n";
3657 if ($linenr > $suppress_statement &&
3658 $realcnt && $sline =~ /.\s*\S/) {
3659 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3660 ctx_statement_block($linenr, $realcnt, 0);
3661 $stat =~ s/\n./\n /g;
3662 $cond =~ s/\n./\n /g;
3664 #print "linenr<$linenr> <$stat>\n";
3665 # If this statement has no statement boundaries within
3666 # it there is no point in retrying a statement scan
3667 # until we hit end of it.
3668 my $frag = $stat; $frag =~ s/;+\s*$//;
3669 if ($frag !~ /(?:{|;)/) {
3670 #print "skip<$line_nr_next>\n";
3671 $suppress_statement = $line_nr_next;
3674 # Find the real next line.
3675 $realline_next = $line_nr_next;
3676 if (defined $realline_next &&
3677 (!defined $lines[$realline_next - 1] ||
3678 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3685 # Ignore goto labels.
3686 if ($s =~ /$Ident:\*$/s) {
3688 # Ignore functions being called
3689 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3691 } elsif ($s =~ /^.\s*else\b/s) {
3693 # declarations always start with types
3694 } 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) {
3697 possible($type, "A:" . $s);
3699 # definitions in global scope can only start with types
3700 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3701 possible($1, "B:" . $s);
3704 # any (foo ... *) is a pointer cast, and foo is a type
3705 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3706 possible($1, "C:" . $s);
3709 # Check for any sort of function declaration.
3710 # int foo(something bar, other baz);
3711 # void (*store_gdt)(x86_descr_ptr *);
3712 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3713 my ($name_len) = length($1);
3716 substr($ctx, 0, $name_len + 1, '');
3717 $ctx =~ s/\)[^\)]*$//;
3719 for my $arg (split(/\s*,\s*/, $ctx)) {
3720 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3722 possible($1, "D:" . $s);
3730 # Checks which may be anchored in the context.
3733 # Check for switch () and associated case and default
3734 # statements should be at the same indent.
3735 if ($line=~/\bswitch\s*\(.*\)/) {
3738 my @ctx = ctx_block_outer($linenr, $realcnt);
3740 for my $ctx (@ctx) {
3741 my ($clen, $cindent) = line_stats($ctx);
3742 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3743 $indent != $cindent) {
3744 $err .= "$sep$ctx\n";
3751 ERROR("SWITCH_CASE_INDENT_LEVEL",
3752 "switch and case should be at the same indent\n$hereline$err");
3756 # if/while/etc brace do not go on next line, unless defining a do while loop,
3757 # or if that brace on the next line is for something else
3758 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3759 my $pre_ctx = "$1$2";
3761 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3763 if ($line =~ /^\+\t{6,}/) {
3764 WARN("DEEP_INDENTATION",
3765 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3768 my $ctx_cnt = $realcnt - $#ctx - 1;
3769 my $ctx = join("\n", @ctx);
3771 my $ctx_ln = $linenr;
3772 my $ctx_skip = $realcnt;
3774 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3775 defined $lines[$ctx_ln - 1] &&
3776 $lines[$ctx_ln - 1] =~ /^-/)) {
3777 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3778 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3782 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3783 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3785 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3787 "that open brace { should be on the previous line\n" .
3788 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3790 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3791 $ctx =~ /\)\s*\;\s*$/ &&
3792 defined $lines[$ctx_ln - 1])
3794 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3795 if ($nindent > $indent) {
3796 WARN("TRAILING_SEMICOLON",
3797 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3798 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3803 # Check relative indent for conditionals and blocks.
3804 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3805 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3806 ctx_statement_block($linenr, $realcnt, 0)
3807 if (!defined $stat);
3808 my ($s, $c) = ($stat, $cond);
3810 substr($s, 0, length($c), '');
3812 # remove inline comments
3816 # Find out how long the conditional actually is.
3817 my @newlines = ($c =~ /\n/gs);
3818 my $cond_lines = 1 + $#newlines;
3820 # Make sure we remove the line prefixes as we have
3821 # none on the first line, and are going to readd them
3824 while ($s =~ /\n\s+\\\n/) {
3825 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3828 # We want to check the first line inside the block
3829 # starting at the end of the conditional, so remove:
3830 # 1) any blank line termination
3831 # 2) any opening brace { on end of the line
3833 my $continuation = 0;
3835 $s =~ s/^.*\bdo\b//;
3837 if ($s =~ s/^\s*\\//) {
3840 if ($s =~ s/^\s*?\n//) {
3845 # Also ignore a loop construct at the end of a
3846 # preprocessor statement.
3847 if (($prevline =~ /^.\s*#\s*define\s/ ||
3848 $prevline =~ /\\\s*$/) && $continuation == 0) {
3854 while ($cond_ptr != $cond_lines) {
3855 $cond_ptr = $cond_lines;
3857 # If we see an #else/#elif then the code
3859 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3864 # 1) blank lines, they should be at 0,
3865 # 2) preprocessor lines, and
3867 if ($continuation ||
3869 $s =~ /^\s*#\s*?/ ||
3870 $s =~ /^\s*$Ident\s*:/) {
3871 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3872 if ($s =~ s/^.*?\n//) {
3878 my (undef, $sindent) = line_stats("+" . $s);
3879 my $stat_real = raw_line($linenr, $cond_lines);
3881 # Check if either of these lines are modified, else
3882 # this is not this patch's fault.
3883 if (!defined($stat_real) ||
3884 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3887 if (defined($stat_real) && $cond_lines > 1) {
3888 $stat_real = "[...]\n$stat_real";
3891 #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";
3893 if ($check && $s ne '' &&
3894 (($sindent % $tabsize) != 0 ||
3895 ($sindent < $indent) ||
3896 ($sindent == $indent &&
3897 ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3898 ($sindent > $indent + $tabsize))) {
3899 WARN("SUSPECT_CODE_INDENT",
3900 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3904 # Track the 'values' across context and added lines.
3905 my $opline = $line; $opline =~ s/^./ /;
3906 my ($curr_values, $curr_vars) =
3907 annotate_values($opline . "\n", $prev_values);
3908 $curr_values = $prev_values . $curr_values;
3910 my $outline = $opline; $outline =~ s/\t/ /g;
3911 print "$linenr > .$outline\n";
3912 print "$linenr > $curr_values\n";
3913 print "$linenr > $curr_vars\n";
3915 $prev_values = substr($curr_values, -1);
3917 #ignore lines not being added
3918 next if ($line =~ /^[^\+]/);
3920 # check for self assignments used to avoid compiler warnings
3921 # e.g.: int foo = foo, *bar = NULL;
3922 # struct foo bar = *(&(bar));
3923 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
3925 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
3926 WARN("SELF_ASSIGNMENT",
3927 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
3931 # check for dereferences that span multiple lines
3932 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3933 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3934 $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3936 $line =~ /^.\s*($Lval)/;
3939 WARN("MULTILINE_DEREFERENCE",
3940 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3943 # check for declarations of signed or unsigned without int
3944 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3947 $var = "" if (!defined $var);
3948 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3952 $pointer = "" if (!defined $pointer);
3954 if (WARN("UNSPECIFIED_INT",
3955 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3957 my $decl = trim($sign) . " int ";
3958 my $comp_pointer = $pointer;
3959 $comp_pointer =~ s/\s//g;
3960 $decl .= $comp_pointer;
3961 $decl = rtrim($decl) if ($var eq "");
3962 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3967 # TEST: allow direct testing of the type matcher.
3969 if ($line =~ /^.\s*$Declare\s*$/) {
3971 "TEST: is type\n" . $herecurr);
3972 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3973 ERROR("TEST_NOT_TYPE",
3974 "TEST: is not type ($1 is)\n". $herecurr);
3978 # TEST: allow direct testing of the attribute matcher.
3980 if ($line =~ /^.\s*$Modifier\s*$/) {
3982 "TEST: is attr\n" . $herecurr);
3983 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3984 ERROR("TEST_NOT_ATTR",
3985 "TEST: is not attr ($1 is)\n". $herecurr);
3990 # check for initialisation to aggregates open brace on the next line
3991 if ($line =~ /^.\s*{/ &&
3992 $prevline =~ /(?:^|[^=])=\s*$/) {
3993 if (ERROR("OPEN_BRACE",
3994 "that open brace { should be on the previous line\n" . $hereprev) &&
3995 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3996 fix_delete_line($fixlinenr - 1, $prevrawline);
3997 fix_delete_line($fixlinenr, $rawline);
3998 my $fixedline = $prevrawline;
3999 $fixedline =~ s/\s*=\s*$/ = {/;
4000 fix_insert_line($fixlinenr, $fixedline);
4002 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4003 fix_insert_line($fixlinenr, $fixedline);
4008 # Checks which are anchored on the added line.
4011 # check for malformed paths in #include statements (uses RAW line)
4012 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4014 if ($path =~ m{//}) {
4015 ERROR("MALFORMED_INCLUDE",
4016 "malformed #include filename\n" . $herecurr);
4018 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4019 ERROR("UAPI_INCLUDE",
4020 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4024 # no C99 // comments
4025 if ($line =~ m{//}) {
4026 if (ERROR("C99_COMMENTS",
4027 "do not use C99 // comments\n" . $herecurr) &&
4029 my $line = $fixed[$fixlinenr];
4030 if ($line =~ /\/\/(.*)$/) {
4031 my $comment = trim($1);
4032 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4036 # Remove C99 comments.
4038 $opline =~ s@//.*@@;
4040 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4041 # the whole statement.
4042 #print "APW <$lines[$realline_next - 1]>\n";
4043 if (defined $realline_next &&
4044 exists $lines[$realline_next - 1] &&
4045 !defined $suppress_export{$realline_next} &&
4046 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4047 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4048 # Handle definitions which produce identifiers with
4051 # EXPORT_SYMBOL(something_foo);
4053 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4054 $name =~ /^${Ident}_$2/) {
4055 #print "FOO C name<$name>\n";
4056 $suppress_export{$realline_next} = 1;
4058 } elsif ($stat !~ /(?:
4060 ^.DEFINE_$Ident\(\Q$name\E\)|
4061 ^.DECLARE_$Ident\(\Q$name\E\)|
4062 ^.LIST_HEAD\(\Q$name\E\)|
4063 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4064 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4066 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4067 $suppress_export{$realline_next} = 2;
4069 $suppress_export{$realline_next} = 1;
4072 if (!defined $suppress_export{$linenr} &&
4073 $prevline =~ /^.\s*$/ &&
4074 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4075 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4076 #print "FOO B <$lines[$linenr - 1]>\n";
4077 $suppress_export{$linenr} = 2;
4079 if (defined $suppress_export{$linenr} &&
4080 $suppress_export{$linenr} == 2) {
4081 WARN("EXPORT_SYMBOL",
4082 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4085 # check for global initialisers.
4086 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4087 if (ERROR("GLOBAL_INITIALISERS",
4088 "do not initialise globals to $1\n" . $herecurr) &&
4090 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4093 # check for static initialisers.
4094 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4095 if (ERROR("INITIALISED_STATIC",
4096 "do not initialise statics to $1\n" .
4099 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4103 # check for misordered declarations of char/short/int/long with signed/unsigned
4104 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4106 WARN("MISORDERED_TYPE",
4107 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4110 # check for unnecessary <signed> int declarations of short/long/long long
4111 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4112 my $type = trim($1);
4113 next if ($type !~ /\bint\b/);
4114 next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4115 my $new_type = $type;
4116 $new_type =~ s/\b\s*int\s*\b/ /;
4117 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4118 $new_type =~ s/^const\s+//;
4119 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4120 $new_type = "const $new_type" if ($type =~ /^const\b/);
4121 $new_type =~ s/\s+/ /g;
4122 $new_type = trim($new_type);
4123 if (WARN("UNNECESSARY_INT",
4124 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4126 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4130 # check for static const char * arrays.
4131 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4132 WARN("STATIC_CONST_CHAR_ARRAY",
4133 "static const char * array should probably be static const char * const\n" .
4137 # check for initialized const char arrays that should be static const
4138 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4139 if (WARN("STATIC_CONST_CHAR_ARRAY",
4140 "const array should probably be static const\n" . $herecurr) &&
4142 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4146 # check for static char foo[] = "bar" declarations.
4147 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4148 WARN("STATIC_CONST_CHAR_ARRAY",
4149 "static char array declaration should probably be static const char\n" .
4153 # check for const <foo> const where <foo> is not a pointer or array type
4154 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4156 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4158 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4159 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4161 "'const $found const' should probably be 'const $found'\n" . $herecurr);
4165 # check for non-global char *foo[] = {"bar", ...} declarations.
4166 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4167 WARN("STATIC_CONST_CHAR_ARRAY",
4168 "char * array declaration might be better as static const\n" .
4172 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4173 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4175 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4177 if (WARN("ARRAY_SIZE",
4178 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4180 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4185 # check for function declarations without arguments like "int foo()"
4186 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4187 if (ERROR("FUNCTION_WITHOUT_ARGS",
4188 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4190 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4194 # check for new typedefs, only function parameters and sparse annotations
4196 if ($line =~ /\btypedef\s/ &&
4197 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4198 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4199 $line !~ /\b$typeTypedefs\b/ &&
4200 $line !~ /\b__bitwise\b/) {
4201 WARN("NEW_TYPEDEFS",
4202 "do not add new typedefs\n" . $herecurr);
4205 # * goes on variable not on type
4207 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4209 my ($ident, $from, $to) = ($1, $2, $2);
4211 # Should start with a space.
4212 $to =~ s/^(\S)/ $1/;
4213 # Should not end with a space.
4215 # '*'s should not have spaces between.
4216 while ($to =~ s/\*\s+\*/\*\*/) {
4219 ## print "1: from<$from> to<$to> ident<$ident>\n";
4221 if (ERROR("POINTER_LOCATION",
4222 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
4224 my $sub_from = $ident;
4225 my $sub_to = $ident;
4226 $sub_to =~ s/\Q$from\E/$to/;
4227 $fixed[$fixlinenr] =~
4228 s@\Q$sub_from\E@$sub_to@;
4232 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4234 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4236 # Should start with a space.
4237 $to =~ s/^(\S)/ $1/;
4238 # Should not end with a space.
4240 # '*'s should not have spaces between.
4241 while ($to =~ s/\*\s+\*/\*\*/) {
4243 # Modifiers should have spaces.
4244 $to =~ s/(\b$Modifier$)/$1 /;
4246 ## print "2: from<$from> to<$to> ident<$ident>\n";
4247 if ($from ne $to && $ident !~ /^$Modifier$/) {
4248 if (ERROR("POINTER_LOCATION",
4249 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
4252 my $sub_from = $match;
4253 my $sub_to = $match;
4254 $sub_to =~ s/\Q$from\E/$to/;
4255 $fixed[$fixlinenr] =~
4256 s@\Q$sub_from\E@$sub_to@;
4261 # avoid BUG() or BUG_ON()
4262 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4263 my $msg_level = \&WARN;
4264 $msg_level = \&CHK if ($file);
4265 &{$msg_level}("AVOID_BUG",
4266 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4269 # avoid LINUX_VERSION_CODE
4270 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4271 WARN("LINUX_VERSION_CODE",
4272 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4275 # check for uses of printk_ratelimit
4276 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4277 WARN("PRINTK_RATELIMITED",
4278 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4281 # printk should use KERN_* levels
4282 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4283 WARN("PRINTK_WITHOUT_KERN_LEVEL",
4284 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4287 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4289 my $level = lc($orig);
4290 $level = "warn" if ($level eq "warning");
4291 my $level2 = $level;
4292 $level2 = "dbg" if ($level eq "debug");
4293 WARN("PREFER_PR_LEVEL",
4294 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
4297 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4299 my $level = lc($orig);
4300 $level = "warn" if ($level eq "warning");
4301 $level = "dbg" if ($level eq "debug");
4302 WARN("PREFER_DEV_LEVEL",
4303 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4306 # trace_printk should not be used in production code.
4307 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4308 WARN("TRACE_PRINTK",
4309 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4312 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
4313 # number of false positives, but assembly files are not checked, so at
4314 # least the arch entry code will not trigger this warning.
4315 if ($line =~ /\bENOSYS\b/) {
4317 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4320 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4321 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4322 # Similarly to ENOSYS warning a small number of false positives is expected.
4323 if (!$file && $line =~ /\bENOTSUPP\b/) {
4324 if (WARN("ENOTSUPP",
4325 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4327 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4331 # function brace can't be on same line, except for #defines of do while,
4332 # or if closed on same line
4333 if ($perl_version_ok &&
4334 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4335 $sline !~ /\#\s*define\b.*do\s*\{/ &&
4337 if (ERROR("OPEN_BRACE",
4338 "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4340 fix_delete_line($fixlinenr, $rawline);
4341 my $fixed_line = $rawline;
4342 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4345 fix_insert_line($fixlinenr, ltrim($line1));
4346 fix_insert_line($fixlinenr, "\+{");
4347 if ($line2 !~ /^\s*$/) {
4348 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4353 # open braces for enum, union and struct go on the same line.
4354 if ($line =~ /^.\s*{/ &&
4355 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4356 if (ERROR("OPEN_BRACE",
4357 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4358 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4359 fix_delete_line($fixlinenr - 1, $prevrawline);
4360 fix_delete_line($fixlinenr, $rawline);
4361 my $fixedline = rtrim($prevrawline) . " {";
4362 fix_insert_line($fixlinenr, $fixedline);
4363 $fixedline = $rawline;
4364 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4365 if ($fixedline !~ /^\+\s*$/) {
4366 fix_insert_line($fixlinenr, $fixedline);
4371 # missing space after union, struct or enum definition
4372 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4374 "missing space after $1 definition\n" . $herecurr) &&
4376 $fixed[$fixlinenr] =~
4377 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4381 # Function pointer declarations
4382 # check spacing between type, funcptr, and args
4383 # canonical declaration is "type (*funcptr)(args...)"
4384 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4386 my $pre_pointer_space = $2;
4387 my $post_pointer_space = $3;
4389 my $post_funcname_space = $5;
4390 my $pre_args_space = $6;
4392 # the $Declare variable will capture all spaces after the type
4393 # so check it for a missing trailing missing space but pointer return types
4394 # don't need a space so don't warn for those.
4395 my $post_declare_space = "";
4396 if ($declare =~ /(\s+)$/) {
4397 $post_declare_space = $1;
4398 $declare = rtrim($declare);
4400 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4402 "missing space after return type\n" . $herecurr);
4403 $post_declare_space = " ";
4406 # unnecessary space "type (*funcptr)(args...)"
4407 # This test is not currently implemented because these declarations are
4409 # int foo(int bar, ...)
4410 # and this is form shouldn't/doesn't generate a checkpatch warning.
4412 # elsif ($declare =~ /\s{2,}$/) {
4414 # "Multiple spaces after return type\n" . $herecurr);
4417 # unnecessary space "type ( *funcptr)(args...)"
4418 if (defined $pre_pointer_space &&
4419 $pre_pointer_space =~ /^\s/) {
4421 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4424 # unnecessary space "type (* funcptr)(args...)"
4425 if (defined $post_pointer_space &&
4426 $post_pointer_space =~ /^\s/) {
4428 "Unnecessary space before function pointer name\n" . $herecurr);
4431 # unnecessary space "type (*funcptr )(args...)"
4432 if (defined $post_funcname_space &&
4433 $post_funcname_space =~ /^\s/) {
4435 "Unnecessary space after function pointer name\n" . $herecurr);
4438 # unnecessary space "type (*funcptr) (args...)"
4439 if (defined $pre_args_space &&
4440 $pre_args_space =~ /^\s/) {
4442 "Unnecessary space before function pointer arguments\n" . $herecurr);
4445 if (show_type("SPACING") && $fix) {
4446 $fixed[$fixlinenr] =~
4447 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4451 # check for spacing round square brackets; allowed:
4452 # 1. with a type on the left -- int [] a;
4453 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4454 # 3. inside a curly brace -- = { [0...10] = 5 }
4455 while ($line =~ /(.*?\s)\[/g) {
4456 my ($where, $prefix) = ($-[1], $1);
4457 if ($prefix !~ /$Type\s+$/ &&
4458 ($where != 0 || $prefix !~ /^.\s+$/) &&
4459 $prefix !~ /[{,:]\s+$/) {
4460 if (ERROR("BRACKET_SPACE",
4461 "space prohibited before open square bracket '['\n" . $herecurr) &&
4463 $fixed[$fixlinenr] =~
4464 s/^(\+.*?)\s+\[/$1\[/;
4469 # check for spaces between functions and their parentheses.
4470 while ($line =~ /($Ident)\s+\(/g) {
4472 my $ctx_before = substr($line, 0, $-[1]);
4473 my $ctx = "$ctx_before$name";
4475 # Ignore those directives where spaces _are_ permitted.
4477 if|for|while|switch|return|case|
4478 volatile|__volatile__|
4479 __attribute__|format|__extension__|
4482 # cpp #define statements have non-optional spaces, ie
4483 # if there is a space between the name and the open
4484 # parenthesis it is simply not a parameter group.
4485 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4487 # cpp #elif statement condition may start with a (
4488 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4490 # If this whole things ends with a type its most
4491 # likely a typedef for a function.
4492 } elsif ($ctx =~ /$Type$/) {
4496 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4498 $fixed[$fixlinenr] =~
4499 s/\b$name\s+\(/$name\(/;
4504 # Check operator spacing.
4505 if (!($line=~/\#\s*include/)) {
4506 my $fixed_line = "";
4510 <<=|>>=|<=|>=|==|!=|
4511 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4512 =>|->|<<|>>|<|>|=|!|~|
4513 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4516 my @elements = split(/($ops|;)/, $opline);
4518 ## print("element count: <" . $#elements . ">\n");
4519 ## foreach my $el (@elements) {
4520 ## print("el: <$el>\n");
4523 my @fix_elements = ();
4526 foreach my $el (@elements) {
4527 push(@fix_elements, substr($rawline, $off, length($el)));
4528 $off += length($el);
4533 my $blank = copy_spacing($opline);
4534 my $last_after = -1;
4536 for (my $n = 0; $n < $#elements; $n += 2) {
4538 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4540 ## print("n: <$n> good: <$good>\n");
4542 $off += length($elements[$n]);
4544 # Pick up the preceding and succeeding characters.
4545 my $ca = substr($opline, 0, $off);
4547 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4548 $cc = substr($opline, $off + length($elements[$n + 1]));
4550 my $cb = "$ca$;$cc";
4553 $a = 'V' if ($elements[$n] ne '');
4554 $a = 'W' if ($elements[$n] =~ /\s$/);
4555 $a = 'C' if ($elements[$n] =~ /$;$/);
4556 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4557 $a = 'O' if ($elements[$n] eq '');
4558 $a = 'E' if ($ca =~ /^\s*$/);
4560 my $op = $elements[$n + 1];
4563 if (defined $elements[$n + 2]) {
4564 $c = 'V' if ($elements[$n + 2] ne '');
4565 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4566 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4567 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4568 $c = 'O' if ($elements[$n + 2] eq '');
4569 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4574 my $ctx = "${a}x${c}";
4576 my $at = "(ctx:$ctx)";
4578 my $ptr = substr($blank, 0, $off) . "^";
4579 my $hereptr = "$hereline$ptr\n";
4581 # Pull out the value of this operator.
4582 my $op_type = substr($curr_values, $off + 1, 1);
4584 # Get the full operator variant.
4585 my $opv = $op . substr($curr_vars, $off, 1);
4587 # Ignore operators passed as parameters.
4588 if ($op_type ne 'V' &&
4589 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4592 # } elsif ($op =~ /^$;+$/) {
4594 # ; should have either the end of line or a space or \ after it
4595 } elsif ($op eq ';') {
4596 if ($ctx !~ /.x[WEBC]/ &&
4597 $cc !~ /^\\/ && $cc !~ /^;/) {
4598 if (ERROR("SPACING",
4599 "space required after that '$op' $at\n" . $hereptr)) {
4600 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4606 } elsif ($op eq '//') {
4608 # : when part of a bitfield
4609 } elsif ($opv eq ':B') {
4610 # skip the bitfield test for now
4614 } elsif ($op eq '->') {
4615 if ($ctx =~ /Wx.|.xW/) {
4616 if (ERROR("SPACING",
4617 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4618 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4619 if (defined $fix_elements[$n + 2]) {
4620 $fix_elements[$n + 2] =~ s/^\s+//;
4626 # , must not have a space before and must have a space on the right.
4627 } elsif ($op eq ',') {
4628 my $rtrim_before = 0;
4629 my $space_after = 0;
4630 if ($ctx =~ /Wx./) {
4631 if (ERROR("SPACING",
4632 "space prohibited before that '$op' $at\n" . $hereptr)) {
4637 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4638 if (ERROR("SPACING",
4639 "space required after that '$op' $at\n" . $hereptr)) {
4645 if ($rtrim_before || $space_after) {
4646 if ($rtrim_before) {
4647 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4649 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4656 # '*' as part of a type definition -- reported already.
4657 } elsif ($opv eq '*_') {
4658 #warn "'*' is part of type\n";
4660 # unary operators should have a space before and
4661 # none after. May be left adjacent to another
4662 # unary operator, or a cast
4663 } elsif ($op eq '!' || $op eq '~' ||
4664 $opv eq '*U' || $opv eq '-U' ||
4665 $opv eq '&U' || $opv eq '&&U') {
4666 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4667 if (ERROR("SPACING",
4668 "space required before that '$op' $at\n" . $hereptr)) {
4669 if ($n != $last_after + 2) {
4670 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4675 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4676 # A unary '*' may be const
4678 } elsif ($ctx =~ /.xW/) {
4679 if (ERROR("SPACING",
4680 "space prohibited after that '$op' $at\n" . $hereptr)) {
4681 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4682 if (defined $fix_elements[$n + 2]) {
4683 $fix_elements[$n + 2] =~ s/^\s+//;
4689 # unary ++ and unary -- are allowed no space on one side.
4690 } elsif ($op eq '++' or $op eq '--') {
4691 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4692 if (ERROR("SPACING",
4693 "space required one side of that '$op' $at\n" . $hereptr)) {
4694 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4698 if ($ctx =~ /Wx[BE]/ ||
4699 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4700 if (ERROR("SPACING",
4701 "space prohibited before that '$op' $at\n" . $hereptr)) {
4702 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4706 if ($ctx =~ /ExW/) {
4707 if (ERROR("SPACING",
4708 "space prohibited after that '$op' $at\n" . $hereptr)) {
4709 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4710 if (defined $fix_elements[$n + 2]) {
4711 $fix_elements[$n + 2] =~ s/^\s+//;
4717 # << and >> may either have or not have spaces both sides
4718 } elsif ($op eq '<<' or $op eq '>>' or
4719 $op eq '&' or $op eq '^' or $op eq '|' or
4720 $op eq '+' or $op eq '-' or
4721 $op eq '*' or $op eq '/' or
4725 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4727 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4728 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4729 $fix_elements[$n + 2] =~ s/^\s+//;
4732 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4734 "space preferred before that '$op' $at\n" . $hereptr)) {
4735 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4739 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4740 if (ERROR("SPACING",
4741 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4742 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4743 if (defined $fix_elements[$n + 2]) {
4744 $fix_elements[$n + 2] =~ s/^\s+//;
4750 # A colon needs no spaces before when it is
4751 # terminating a case value or a label.
4752 } elsif ($opv eq ':C' || $opv eq ':L') {
4753 if ($ctx =~ /Wx./) {
4754 if (ERROR("SPACING",
4755 "space prohibited before that '$op' $at\n" . $hereptr)) {
4756 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4761 # All the others need spaces both sides.
4762 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4765 # Ignore email addresses <foo@bar>
4767 $cc =~ /^\S+\@\S+>/) ||
4769 $ca =~ /<\S+\@\S+$/))
4774 # for asm volatile statements
4775 # ignore a colon with another
4776 # colon immediately before or after
4778 ($ca =~ /:$/ || $cc =~ /^:/)) {
4782 # messages are ERROR, but ?: are CHK
4784 my $msg_level = \&ERROR;
4785 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4787 if (&{$msg_level}("SPACING",
4788 "spaces required around that '$op' $at\n" . $hereptr)) {
4789 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4790 if (defined $fix_elements[$n + 2]) {
4791 $fix_elements[$n + 2] =~ s/^\s+//;
4797 $off += length($elements[$n + 1]);
4799 ## print("n: <$n> GOOD: <$good>\n");
4801 $fixed_line = $fixed_line . $good;
4804 if (($#elements % 2) == 0) {
4805 $fixed_line = $fixed_line . $fix_elements[$#elements];
4808 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4809 $fixed[$fixlinenr] = $fixed_line;
4815 # check for whitespace before a non-naked semicolon
4816 if ($line =~ /^\+.*\S\s+;\s*$/) {
4818 "space prohibited before semicolon\n" . $herecurr) &&
4820 1 while $fixed[$fixlinenr] =~
4821 s/^(\+.*\S)\s+;/$1;/;
4825 # check for multiple assignments
4826 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4827 CHK("MULTIPLE_ASSIGNMENTS",
4828 "multiple assignments should be avoided\n" . $herecurr);
4831 ## # check for multiple declarations, allowing for a function declaration
4833 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4834 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4836 ## # Remove any bracketed sections to ensure we do not
4837 ## # falsly report the parameters of functions.
4839 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4841 ## if ($ln =~ /,/) {
4842 ## WARN("MULTIPLE_DECLARATION",
4843 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4847 #need space before brace following if, while, etc
4848 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4849 $line =~ /\b(?:else|do)\{/) {
4850 if (ERROR("SPACING",
4851 "space required before the open brace '{'\n" . $herecurr) &&
4853 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4857 ## # check for blank lines before declarations
4858 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4859 ## $prevrawline =~ /^.\s*$/) {
4861 ## "No blank lines before declarations\n" . $hereprev);
4865 # closing brace should have a space following it when it has anything
4867 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4868 if (ERROR("SPACING",
4869 "space required after that close brace '}'\n" . $herecurr) &&
4871 $fixed[$fixlinenr] =~
4872 s/}((?!(?:,|;|\)))\S)/} $1/;
4876 # check spacing on square brackets
4877 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4878 if (ERROR("SPACING",
4879 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4881 $fixed[$fixlinenr] =~
4885 if ($line =~ /\s\]/) {
4886 if (ERROR("SPACING",
4887 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4889 $fixed[$fixlinenr] =~
4894 # check spacing on parentheses
4895 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4896 $line !~ /for\s*\(\s+;/) {
4897 if (ERROR("SPACING",
4898 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4900 $fixed[$fixlinenr] =~
4904 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4905 $line !~ /for\s*\(.*;\s+\)/ &&
4906 $line !~ /:\s+\)/) {
4907 if (ERROR("SPACING",
4908 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4910 $fixed[$fixlinenr] =~
4915 # check unnecessary parentheses around addressof/dereference single $Lvals
4916 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4918 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4920 if (CHK("UNNECESSARY_PARENTHESES",
4921 "Unnecessary parentheses around $var\n" . $herecurr) &&
4923 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4927 # check for unnecessary parentheses around function pointer uses
4928 # ie: (foo->bar)(); should be foo->bar();
4929 # but not "if (foo->bar) (" to avoid some false positives
4930 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4932 if (CHK("UNNECESSARY_PARENTHESES",
4933 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4935 my $var2 = deparenthesize($var);
4937 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4941 # check for unnecessary parentheses around comparisons in if uses
4942 # when !drivers/staging or command-line uses --strict
4943 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4944 $perl_version_ok && defined($stat) &&
4945 $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4947 my $test = substr($2, 1, -1);
4949 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4951 # avoid parentheses around potential macro args
4952 next if ($match =~ /^\s*\w+\s*$/);
4953 if (!defined($herectx)) {
4954 $herectx = $here . "\n";
4955 my $cnt = statement_rawlines($if_stat);
4956 for (my $n = 0; $n < $cnt; $n++) {
4957 my $rl = raw_line($linenr, $n);
4958 $herectx .= $rl . "\n";
4959 last if $rl =~ /^[ \+].*\{/;
4962 CHK("UNNECESSARY_PARENTHESES",
4963 "Unnecessary parentheses around '$match'\n" . $herectx);
4967 #goto labels aren't indented, allow a single space however
4968 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4969 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4970 if (WARN("INDENTED_LABEL",
4971 "labels should not be indented\n" . $herecurr) &&
4973 $fixed[$fixlinenr] =~
4978 # check if a statement with a comma should be two statements like:
4979 # foo = bar(), /* comma should be semicolon */
4981 if (defined($stat) &&
4982 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
4983 my $cnt = statement_rawlines($stat);
4984 my $herectx = get_stat_here($linenr, $cnt, $here);
4985 WARN("SUSPECT_COMMA_SEMICOLON",
4986 "Possible comma where semicolon could be used\n" . $herectx);
4989 # return is not a function
4990 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4992 if ($perl_version_ok &&
4993 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4995 $value = deparenthesize($value);
4996 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4997 ERROR("RETURN_PARENTHESES",
4998 "return is not a function, parentheses are not required\n" . $herecurr);
5000 } elsif ($spacing !~ /\s+/) {
5002 "space required before the open parenthesis '('\n" . $herecurr);
5006 # unnecessary return in a void function
5007 # at end-of-function, with the previous line a single leading tab, then return;
5008 # and the line before that not a goto label target like "out:"
5009 if ($sline =~ /^[ \+]}\s*$/ &&
5010 $prevline =~ /^\+\treturn\s*;\s*$/ &&
5012 $lines[$linenr - 3] =~ /^[ +]/ &&
5013 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5015 "void function return statements are not generally useful\n" . $hereprev);
5018 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5019 if ($perl_version_ok &&
5020 $line =~ /\bif\s*((?:\(\s*){2,})/) {
5021 my $openparens = $1;
5022 my $count = $openparens =~ tr@\(@\(@;
5024 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5025 my $comp = $4; #Not $1 because of $LvalOrFunc
5026 $msg = " - maybe == should be = ?" if ($comp eq "==");
5027 WARN("UNNECESSARY_PARENTHESES",
5028 "Unnecessary parentheses$msg\n" . $herecurr);
5032 # comparisons with a constant or upper case identifier on the left
5033 # avoid cases like "foo + BAR < baz"
5034 # only fix matches surrounded by parentheses to avoid incorrect
5035 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5036 if ($perl_version_ok &&
5037 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5042 my $newcomp = $comp;
5043 if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5044 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5045 WARN("CONSTANT_COMPARISON",
5046 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5050 } elsif ($comp eq "<=") {
5052 } elsif ($comp eq ">") {
5054 } elsif ($comp eq ">=") {
5057 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5061 # Return of what appears to be an errno should normally be negative
5062 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5064 if ($name ne 'EOF' && $name ne 'ERROR') {
5065 WARN("USE_NEGATIVE_ERRNO",
5066 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5070 # Need a space before open parenthesis after if, while etc
5071 if ($line =~ /\b(if|while|for|switch)\(/) {
5072 if (ERROR("SPACING",
5073 "space required before the open parenthesis '('\n" . $herecurr) &&
5075 $fixed[$fixlinenr] =~
5076 s/\b(if|while|for|switch)\(/$1 \(/;
5080 # Check for illegal assignment in if conditional -- and check for trailing
5081 # statements after the conditional.
5082 if ($line =~ /do\s*(?!{)/) {
5083 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5084 ctx_statement_block($linenr, $realcnt, 0)
5085 if (!defined $stat);
5086 my ($stat_next) = ctx_statement_block($line_nr_next,
5087 $remain_next, $off_next);
5088 $stat_next =~ s/\n./\n /g;
5089 ##print "stat<$stat> stat_next<$stat_next>\n";
5091 if ($stat_next =~ /^\s*while\b/) {
5092 # If the statement carries leading newlines,
5093 # then count those as offsets.
5095 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5097 statement_rawlines($whitespace) - 1;
5099 $suppress_whiletrailers{$line_nr_next +
5103 if (!defined $suppress_whiletrailers{$linenr} &&
5104 defined($stat) && defined($cond) &&
5105 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5106 my ($s, $c) = ($stat, $cond);
5108 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5109 if (ERROR("ASSIGN_IN_IF",
5110 "do not use assignment in if condition\n" . $herecurr) &&
5111 $fix && $perl_version_ok) {
5112 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5120 fix_delete_line($fixlinenr, $rawline);
5121 fix_insert_line($fixlinenr, "$space$statement;");
5122 my $newline = "${space}if (";
5123 $newline .= '!' if defined($not);
5124 $newline .= '(' if (defined $not && defined($test) && defined($against));
5125 $newline .= "$assigned";
5126 $newline .= " $test $against" if (defined($test) && defined($against));
5127 $newline .= ')' if (defined $not && defined($test) && defined($against));
5129 $newline .= " {" if (defined($brace));
5130 fix_insert_line($fixlinenr + 1, $newline);
5135 # Find out what is on the end of the line after the
5137 substr($s, 0, length($c), '');
5139 $s =~ s/$;//g; # Remove any comments
5140 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5141 $c !~ /}\s*while\s*/)
5143 # Find out how long the conditional actually is.
5144 my @newlines = ($c =~ /\n/gs);
5145 my $cond_lines = 1 + $#newlines;
5148 $stat_real = raw_line($linenr, $cond_lines)
5149 . "\n" if ($cond_lines);
5150 if (defined($stat_real) && $cond_lines > 1) {
5151 $stat_real = "[...]\n$stat_real";
5154 ERROR("TRAILING_STATEMENTS",
5155 "trailing statements should be on next line\n" . $herecurr . $stat_real);
5159 # Check for bitwise tests written as boolean
5171 WARN("HEXADECIMAL_BOOLEAN_TEST",
5172 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5175 # if and else should not have general statements after it
5176 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5178 $s =~ s/$;//g; # Remove any comments
5179 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5180 ERROR("TRAILING_STATEMENTS",
5181 "trailing statements should be on next line\n" . $herecurr);
5184 # if should not continue a brace
5185 if ($line =~ /}\s*if\b/) {
5186 ERROR("TRAILING_STATEMENTS",
5187 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5190 # case and default should not have general statements after them
5191 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5193 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5197 ERROR("TRAILING_STATEMENTS",
5198 "trailing statements should be on next line\n" . $herecurr);
5201 # Check for }<nl>else {, these must be at the same
5202 # indent level to be relevant to each other.
5203 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5204 $previndent == $indent) {
5205 if (ERROR("ELSE_AFTER_BRACE",
5206 "else should follow close brace '}'\n" . $hereprev) &&
5207 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5208 fix_delete_line($fixlinenr - 1, $prevrawline);
5209 fix_delete_line($fixlinenr, $rawline);
5210 my $fixedline = $prevrawline;
5211 $fixedline =~ s/}\s*$//;
5212 if ($fixedline !~ /^\+\s*$/) {
5213 fix_insert_line($fixlinenr, $fixedline);
5215 $fixedline = $rawline;
5216 $fixedline =~ s/^(.\s*)else/$1} else/;
5217 fix_insert_line($fixlinenr, $fixedline);
5221 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5222 $previndent == $indent) {
5223 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5225 # Find out what is on the end of the line after the
5227 substr($s, 0, length($c), '');
5230 if ($s =~ /^\s*;/) {
5231 if (ERROR("WHILE_AFTER_BRACE",
5232 "while should follow close brace '}'\n" . $hereprev) &&
5233 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5234 fix_delete_line($fixlinenr - 1, $prevrawline);
5235 fix_delete_line($fixlinenr, $rawline);
5236 my $fixedline = $prevrawline;
5237 my $trailing = $rawline;
5238 $trailing =~ s/^\+//;
5239 $trailing = trim($trailing);
5240 $fixedline =~ s/}\s*$/} $trailing/;
5241 fix_insert_line($fixlinenr, $fixedline);
5246 #Specific variable tests
5247 while ($line =~ m{($Constant|$Lval)}g) {
5251 if ($var !~ /^$Constant$/ &&
5252 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5253 #Ignore Page<foo> variants
5254 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5255 #Ignore SI style variants like nS, mV and dB
5256 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5257 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5258 #Ignore some three character SI units explicitly, like MiB and KHz
5259 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5260 while ($var =~ m{($Ident)}g) {
5262 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5264 seed_camelcase_includes();
5265 if (!$file && !$camelcase_file_seeded) {
5266 seed_camelcase_file($realfile);
5267 $camelcase_file_seeded = 1;
5270 if (!defined $camelcase{$word}) {
5271 $camelcase{$word} = 1;
5273 "Avoid CamelCase: <$word>\n" . $herecurr);
5279 #no spaces allowed after \ in define
5280 if ($line =~ /\#\s*define.*\\\s+$/) {
5281 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5282 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5284 $fixed[$fixlinenr] =~ s/\s+$//;
5288 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5289 # itself <asm/foo.h> (uses RAW line)
5290 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5292 my $checkfile = "include/linux/$file";
5293 if (-f "$root/$checkfile" &&
5294 $realfile ne $checkfile &&
5295 $1 !~ /$allowed_asm_includes/)
5297 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5298 if ($asminclude > 0) {
5299 if ($realfile =~ m{^arch/}) {
5300 CHK("ARCH_INCLUDE_LINUX",
5301 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5303 WARN("INCLUDE_LINUX",
5304 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5310 # multi-statement macros should be enclosed in a do while loop, grab the
5311 # first statement and ensure its the whole macro if its not enclosed
5312 # in a known good container
5313 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5314 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5317 my ($off, $dstat, $dcond, $rest);
5319 my $has_flow_statement = 0;
5320 my $has_arg_concat = 0;
5321 ($dstat, $dcond, $ln, $cnt, $off) =
5322 ctx_statement_block($linenr, $realcnt, 0);
5324 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5325 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5327 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5328 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5330 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5331 my $define_args = $1;
5332 my $define_stmt = $dstat;
5335 if (defined $define_args && $define_args ne "") {
5336 $define_args = substr($define_args, 1, length($define_args) - 2);
5337 $define_args =~ s/\s*//g;
5338 $define_args =~ s/\\\+?//g;
5339 @def_args = split(",", $define_args);
5343 $dstat =~ s/\\\n.//g;
5344 $dstat =~ s/^\s*//s;
5345 $dstat =~ s/\s*$//s;
5347 # Flatten any parentheses and braces
5348 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5349 $dstat =~ s/\{[^\{\}]*\}/1/ ||
5350 $dstat =~ s/.\[[^\[\]]*\]/1/)
5354 # Flatten any obvious string concatenation.
5355 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5356 $dstat =~ s/$Ident\s*($String)/$1/)
5360 # Make asm volatile uses seem like a generic function
5361 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5363 my $exceptions = qr{
5376 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5379 my $stmt_cnt = statement_rawlines($ctx);
5380 my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5383 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
5384 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
5385 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5386 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
5387 $dstat !~ /$exceptions/ &&
5388 $dstat !~ /^\.$Ident\s*=/ && # .foo =
5389 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
5390 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
5391 $dstat !~ /^for\s*$Constant$/ && # for (...)
5392 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
5393 $dstat !~ /^do\s*{/ && # do {...
5394 $dstat !~ /^\(\{/ && # ({...
5395 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5397 if ($dstat =~ /^\s*if\b/) {
5398 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5399 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5400 } elsif ($dstat =~ /;/) {
5401 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5402 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5404 ERROR("COMPLEX_MACRO",
5405 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5410 # Make $define_stmt single line, comment-free, etc
5411 my @stmt_array = split('\n', $define_stmt);
5414 foreach my $l (@stmt_array) {
5419 } elsif ($l =~ /^[\+ ]/) {
5420 $define_stmt .= substr($l, 1);
5423 $define_stmt =~ s/$;//g;
5424 $define_stmt =~ s/\s+/ /g;
5425 $define_stmt = trim($define_stmt);
5427 # check if any macro arguments are reused (ignore '...' and 'type')
5428 foreach my $arg (@def_args) {
5429 next if ($arg =~ /\.\.\./);
5430 next if ($arg =~ /^type$/i);
5431 my $tmp_stmt = $define_stmt;
5432 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5433 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5434 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5435 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5437 CHK("MACRO_ARG_REUSE",
5438 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5440 # check if any macro arguments may have other precedence issues
5441 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5442 ((defined($1) && $1 ne ',') ||
5443 (defined($2) && $2 ne ','))) {
5444 CHK("MACRO_ARG_PRECEDENCE",
5445 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5449 # check for macros with flow control, but without ## concatenation
5450 # ## concatenation is commonly a macro that defines a function so ignore those
5451 if ($has_flow_statement && !$has_arg_concat) {
5452 my $cnt = statement_rawlines($ctx);
5453 my $herectx = get_stat_here($linenr, $cnt, $here);
5455 WARN("MACRO_WITH_FLOW_CONTROL",
5456 "Macros with flow control statements should be avoided\n" . "$herectx");
5459 # check for line continuations outside of #defines, preprocessor #, and asm
5462 if ($prevline !~ /^..*\\$/ &&
5463 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
5464 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
5465 $line =~ /^\+.*\\$/) {
5466 WARN("LINE_CONTINUATIONS",
5467 "Avoid unnecessary line continuations\n" . $herecurr);
5471 # do {} while (0) macro tests:
5472 # single-statement macros do not need to be enclosed in do while (0) loop,
5473 # macro should not end with a semicolon
5474 if ($perl_version_ok &&
5475 $realfile !~ m@/vmlinux.lds.h$@ &&
5476 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5479 my ($off, $dstat, $dcond, $rest);
5481 ($dstat, $dcond, $ln, $cnt, $off) =
5482 ctx_statement_block($linenr, $realcnt, 0);
5485 $dstat =~ s/\\\n.//g;
5488 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5493 my $cnt = statement_rawlines($ctx);
5494 my $herectx = get_stat_here($linenr, $cnt, $here);
5496 if (($stmts =~ tr/;/;/) == 1 &&
5497 $stmts !~ /^\s*(if|while|for|switch)\b/) {
5498 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5499 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5501 if (defined $semis && $semis ne "") {
5502 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5503 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5505 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5507 my $cnt = statement_rawlines($ctx);
5508 my $herectx = get_stat_here($linenr, $cnt, $here);
5510 WARN("TRAILING_SEMICOLON",
5511 "macros should not use a trailing semicolon\n" . "$herectx");
5515 # check for redundant bracing round if etc
5516 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5517 my ($level, $endln, @chunks) =
5518 ctx_statement_full($linenr, $realcnt, 1);
5519 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5520 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5521 if ($#chunks > 0 && $level == 0) {
5525 my $herectx = $here . "\n";
5526 my $ln = $linenr - 1;
5527 for my $chunk (@chunks) {
5528 my ($cond, $block) = @{$chunk};
5530 # If the condition carries leading newlines, then count those as offsets.
5531 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5532 my $offset = statement_rawlines($whitespace) - 1;
5534 $allowed[$allow] = 0;
5535 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5537 # We have looked at and allowed this specific line.
5538 $suppress_ifbraces{$ln + $offset} = 1;
5540 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5541 $ln += statement_rawlines($block) - 1;
5543 substr($block, 0, length($cond), '');
5545 $seen++ if ($block =~ /^\s*{/);
5547 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5548 if (statement_lines($cond) > 1) {
5549 #print "APW: ALLOWED: cond<$cond>\n";
5550 $allowed[$allow] = 1;
5552 if ($block =~/\b(?:if|for|while)\b/) {
5553 #print "APW: ALLOWED: block<$block>\n";
5554 $allowed[$allow] = 1;
5556 if (statement_block_size($block) > 1) {
5557 #print "APW: ALLOWED: lines block<$block>\n";
5558 $allowed[$allow] = 1;
5563 my $sum_allowed = 0;
5564 foreach (@allowed) {
5567 if ($sum_allowed == 0) {
5569 "braces {} are not necessary for any arm of this statement\n" . $herectx);
5570 } elsif ($sum_allowed != $allow &&
5573 "braces {} should be used on all arms of this statement\n" . $herectx);
5578 if (!defined $suppress_ifbraces{$linenr - 1} &&
5579 $line =~ /\b(if|while|for|else)\b/) {
5582 # Check the pre-context.
5583 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5584 #print "APW: ALLOWED: pre<$1>\n";
5588 my ($level, $endln, @chunks) =
5589 ctx_statement_full($linenr, $realcnt, $-[0]);
5591 # Check the condition.
5592 my ($cond, $block) = @{$chunks[0]};
5593 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5594 if (defined $cond) {
5595 substr($block, 0, length($cond), '');
5597 if (statement_lines($cond) > 1) {
5598 #print "APW: ALLOWED: cond<$cond>\n";
5601 if ($block =~/\b(?:if|for|while)\b/) {
5602 #print "APW: ALLOWED: block<$block>\n";
5605 if (statement_block_size($block) > 1) {
5606 #print "APW: ALLOWED: lines block<$block>\n";
5609 # Check the post-context.
5610 if (defined $chunks[1]) {
5611 my ($cond, $block) = @{$chunks[1]};
5612 if (defined $cond) {
5613 substr($block, 0, length($cond), '');
5615 if ($block =~ /^\s*\{/) {
5616 #print "APW: ALLOWED: chunk-1 block<$block>\n";
5620 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5621 my $cnt = statement_rawlines($block);
5622 my $herectx = get_stat_here($linenr, $cnt, $here);
5625 "braces {} are not necessary for single statement blocks\n" . $herectx);
5629 # check for single line unbalanced braces
5630 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5631 $sline =~ /^.\s*else\s*\{\s*$/) {
5632 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5635 # check for unnecessary blank lines around braces
5636 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5638 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5639 $fix && $prevrawline =~ /^\+/) {
5640 fix_delete_line($fixlinenr - 1, $prevrawline);
5643 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5645 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5647 fix_delete_line($fixlinenr, $rawline);
5651 # no volatiles please
5652 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5653 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5655 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5658 # Check for user-visible strings broken across lines, which breaks the ability
5659 # to grep for the string. Make exceptions when the previous string ends in a
5660 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5661 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5662 if ($line =~ /^\+\s*$String/ &&
5663 $prevline =~ /"\s*$/ &&
5664 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5665 if (WARN("SPLIT_STRING",
5666 "quoted string split across lines\n" . $hereprev) &&
5668 $prevrawline =~ /^\+.*"\s*$/ &&
5669 $last_coalesced_string_linenr != $linenr - 1) {
5670 my $extracted_string = get_quoted_string($line, $rawline);
5671 my $comma_close = "";
5672 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5676 fix_delete_line($fixlinenr - 1, $prevrawline);
5677 fix_delete_line($fixlinenr, $rawline);
5678 my $fixedline = $prevrawline;
5679 $fixedline =~ s/"\s*$//;
5680 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5681 fix_insert_line($fixlinenr - 1, $fixedline);
5682 $fixedline = $rawline;
5683 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5684 if ($fixedline !~ /\+\s*$/) {
5685 fix_insert_line($fixlinenr, $fixedline);
5687 $last_coalesced_string_linenr = $linenr;
5691 # check for missing a space in a string concatenation
5692 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5693 WARN('MISSING_SPACE',
5694 "break quoted strings at a space character\n" . $hereprev);
5697 # check for an embedded function name in a string when the function is known
5698 # This does not work very well for -f --file checking as it depends on patch
5699 # context providing the function name or a single line form for in-file
5700 # function declarations
5701 if ($line =~ /^\+.*$String/ &&
5702 defined($context_function) &&
5703 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5704 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5705 WARN("EMBEDDED_FUNCTION_NAME",
5706 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5709 # check for spaces before a quoted newline
5710 if ($rawline =~ /^.*\".*\s\\n/) {
5711 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5712 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5714 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5719 # concatenated string without spaces between elements
5720 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5721 if (CHK("CONCATENATED_STRING",
5722 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5724 while ($line =~ /($String)/g) {
5725 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5726 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5727 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5732 # uncoalesced string fragments
5733 if ($line =~ /$String\s*"/) {
5734 if (WARN("STRING_FRAGMENTS",
5735 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5737 while ($line =~ /($String)(?=\s*")/g) {
5738 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5739 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5744 # check for non-standard and hex prefixed decimal printf formats
5745 my $show_L = 1; #don't show the same defect twice
5747 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5748 my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5749 $string =~ s/%%/__/g;
5751 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5753 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5757 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5759 "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5762 # check for 0x<decimal>
5763 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5764 ERROR("PRINTF_0XDECIMAL",
5765 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5769 # check for line continuations in quoted strings with odd counts of "
5770 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5771 WARN("LINE_CONTINUATIONS",
5772 "Avoid line continuations in quoted strings\n" . $herecurr);
5776 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5778 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5782 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5784 "Consider removing the #if 1 and its #endif\n" . $herecurr);
5787 # check for needless "if (<foo>) fn(<foo>)" uses
5788 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5789 my $tested = quotemeta($1);
5790 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5791 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5793 if (WARN('NEEDLESS_IF',
5794 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5797 my $leading_tabs = "";
5798 my $new_leading_tabs = "";
5799 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5804 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5805 $new_leading_tabs = $1;
5806 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5813 fix_delete_line($fixlinenr - 1, $prevrawline);
5814 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5820 # check for unnecessary "Out of Memory" messages
5821 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5822 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5823 (defined $1 || defined $3) &&
5826 my $testline = $lines[$linenr - 3];
5828 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5829 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5831 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5832 $s !~ /\b__GFP_NOWARN\b/ ) {
5834 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5838 # check for logging functions with KERN_<LEVEL>
5839 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5840 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5842 if (WARN("UNNECESSARY_KERN_LEVEL",
5843 "Possible unnecessary $level\n" . $herecurr) &&
5845 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5849 # check for logging continuations
5850 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5851 WARN("LOGGING_CONTINUATION",
5852 "Avoid logging continuation uses where feasible\n" . $herecurr);
5855 # check for mask then right shift without a parentheses
5856 if ($perl_version_ok &&
5857 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5858 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5859 WARN("MASK_THEN_SHIFT",
5860 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5863 # check for pointer comparisons to NULL
5864 if ($perl_version_ok) {
5865 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5868 $equal = "" if ($4 eq "!=");
5869 if (CHK("COMPARISON_TO_NULL",
5870 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5872 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5877 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5878 if ($line =~ /(\b$InitAttribute\b)/) {
5880 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5883 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5884 ERROR("MISPLACED_INIT",
5885 "$attr should be placed after $var\n" . $herecurr)) ||
5886 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5887 WARN("MISPLACED_INIT",
5888 "$attr should be placed after $var\n" . $herecurr))) &&
5890 $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;
5895 # check for $InitAttributeData (ie: __initdata) with const
5896 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5898 $attr =~ /($InitAttributePrefix)(.*)/;
5899 my $attr_prefix = $1;
5901 if (ERROR("INIT_ATTRIBUTE",
5902 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5904 $fixed[$fixlinenr] =~
5905 s/$InitAttributeData/${attr_prefix}initconst/;
5909 # check for $InitAttributeConst (ie: __initconst) without const
5910 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5912 if (ERROR("INIT_ATTRIBUTE",
5913 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5915 my $lead = $fixed[$fixlinenr] =~
5916 /(^\+\s*(?:static\s+))/;
5918 $lead = "$lead " if ($lead !~ /^\+$/);
5919 $lead = "${lead}const ";
5920 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5924 # check for __read_mostly with const non-pointer (should just be const)
5925 if ($line =~ /\b__read_mostly\b/ &&
5926 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5927 if (ERROR("CONST_READ_MOSTLY",
5928 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5930 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5934 # don't use __constant_<foo> functions outside of include/uapi/
5935 if ($realfile !~ m@^include/uapi/@ &&
5936 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5937 my $constant_func = $1;
5938 my $func = $constant_func;
5939 $func =~ s/^__constant_//;
5940 if (WARN("CONSTANT_CONVERSION",
5941 "$constant_func should be $func\n" . $herecurr) &&
5943 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5947 # prefer usleep_range over udelay
5948 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5950 # ignore udelay's < 10, however
5951 if (! ($delay < 10) ) {
5953 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5955 if ($delay > 2000) {
5957 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5961 # warn about unexpectedly long msleep's
5962 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5965 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5969 # check for comparisons of jiffies
5970 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5971 WARN("JIFFIES_COMPARISON",
5972 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5975 # check for comparisons of get_jiffies_64()
5976 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5977 WARN("JIFFIES_COMPARISON",
5978 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5981 # warn about #ifdefs in C files
5982 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5983 # print "#ifdef in C files should be avoided\n";
5984 # print "$herecurr";
5988 # warn about spacing in #ifdefs
5989 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5990 if (ERROR("SPACING",
5991 "exactly one space required after that #$1\n" . $herecurr) &&
5993 $fixed[$fixlinenr] =~
5994 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5999 # check for spinlock_t definitions without a comment.
6000 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6001 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6003 if (!ctx_has_comment($first_line, $linenr)) {
6004 CHK("UNCOMMENTED_DEFINITION",
6005 "$1 definition without comment\n" . $herecurr);
6008 # check for memory barriers without a comment.
6015 my $barrier_stems = qr{
6023 my $all_barriers = qr{
6025 smp_(?:$barrier_stems)|
6026 virt_(?:$barrier_stems)
6029 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6030 if (!ctx_has_comment($first_line, $linenr)) {
6031 WARN("MEMORY_BARRIER",
6032 "memory barrier without comment\n" . $herecurr);
6036 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6038 if ($realfile !~ m@^include/asm-generic/@ &&
6039 $realfile !~ m@/barrier\.h$@ &&
6040 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6041 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6042 WARN("MEMORY_BARRIER",
6043 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6046 # check for waitqueue_active without a comment.
6047 if ($line =~ /\bwaitqueue_active\s*\(/) {
6048 if (!ctx_has_comment($first_line, $linenr)) {
6049 WARN("WAITQUEUE_ACTIVE",
6050 "waitqueue_active without comment\n" . $herecurr);
6054 # check for data_race without a comment.
6055 if ($line =~ /\bdata_race\s*\(/) {
6056 if (!ctx_has_comment($first_line, $linenr)) {
6058 "data_race without comment\n" . $herecurr);
6062 # check of hardware specific defines
6063 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6065 "architecture specific defines should be avoided\n" . $herecurr);
6068 # check that the storage class is not after a type
6069 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6070 WARN("STORAGE_CLASS",
6071 "storage class '$2' should be located before type '$1'\n" . $herecurr);
6073 # Check that the storage class is at the beginning of a declaration
6074 if ($line =~ /\b$Storage\b/ &&
6075 $line !~ /^.\s*$Storage/ &&
6076 $line =~ /^.\s*(.+?)\$Storage\s/ &&
6077 $1 !~ /[\,\)]\s*$/) {
6078 WARN("STORAGE_CLASS",
6079 "storage class should be at the beginning of the declaration\n" . $herecurr);
6082 # check the location of the inline attribute, that it is between
6083 # storage class and type.
6084 if ($line =~ /\b$Type\s+$Inline\b/ ||
6085 $line =~ /\b$Inline\s+$Storage\b/) {
6086 ERROR("INLINE_LOCATION",
6087 "inline keyword should sit between storage class and type\n" . $herecurr);
6090 # Check for __inline__ and __inline, prefer inline
6091 if ($realfile !~ m@\binclude/uapi/@ &&
6092 $line =~ /\b(__inline__|__inline)\b/) {
6094 "plain inline is preferred over $1\n" . $herecurr) &&
6096 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6101 # Check for __attribute__ packed, prefer __packed
6102 if ($realfile !~ m@\binclude/uapi/@ &&
6103 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
6104 WARN("PREFER_PACKED",
6105 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
6108 # Check for __attribute__ aligned, prefer __aligned
6109 if ($realfile !~ m@\binclude/uapi/@ &&
6110 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
6111 WARN("PREFER_ALIGNED",
6112 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
6115 # Check for __attribute__ section, prefer __section
6116 if ($realfile !~ m@\binclude/uapi/@ &&
6117 $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
6118 my $old = substr($rawline, $-[1], $+[1] - $-[1]);
6119 my $new = substr($old, 1, -1);
6120 if (WARN("PREFER_SECTION",
6121 "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
6123 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
6127 # Check for __attribute__ format(printf, prefer __printf
6128 if ($realfile !~ m@\binclude/uapi/@ &&
6129 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
6130 if (WARN("PREFER_PRINTF",
6131 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
6133 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
6138 # Check for __attribute__ format(scanf, prefer __scanf
6139 if ($realfile !~ m@\binclude/uapi/@ &&
6140 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
6141 if (WARN("PREFER_SCANF",
6142 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
6144 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
6148 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6149 if ($perl_version_ok &&
6150 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6151 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6152 $line =~ /\b__weak\b/)) {
6153 ERROR("WEAK_DECLARATION",
6154 "Using weak declarations can have unintended link defects\n" . $herecurr);
6157 # check for c99 types like uint8_t used outside of uapi/ and tools/
6158 if ($realfile !~ m@\binclude/uapi/@ &&
6159 $realfile !~ m@\btools/@ &&
6160 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6162 if ($type =~ /\b($typeC99Typedefs)\b/) {
6164 my $kernel_type = 'u';
6165 $kernel_type = 's' if ($type =~ /^_*[si]/);
6168 if (CHK("PREFER_KERNEL_TYPES",
6169 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6171 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6176 # check for cast of C90 native int or longer types constants
6177 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6180 if (WARN("TYPECAST_INT_CONSTANT",
6181 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6184 my $newconst = $const;
6185 $newconst =~ s/${Int_type}$//;
6186 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6187 if ($cast =~ /\blong\s+long\b/) {
6189 } elsif ($cast =~ /\blong\b/) {
6192 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6196 # check for sizeof(&)
6197 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6198 WARN("SIZEOF_ADDRESS",
6199 "sizeof(& should be avoided\n" . $herecurr);
6202 # check for sizeof without parenthesis
6203 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6204 if (WARN("SIZEOF_PARENTHESIS",
6205 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6207 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6211 # check for struct spinlock declarations
6212 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6213 WARN("USE_SPINLOCK_T",
6214 "struct spinlock should be spinlock_t\n" . $herecurr);
6217 # check for seq_printf uses that could be seq_puts
6218 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6219 my $fmt = get_quoted_string($line, $rawline);
6222 if (WARN("PREFER_SEQ_PUTS",
6223 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6225 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6230 # check for vsprintf extension %p<foo> misuses
6231 if ($perl_version_ok &&
6233 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6234 $1 !~ /^_*volatile_*$/) {
6237 my $lc = $stat =~ tr@\n@@;
6238 $lc = $lc + $linenr;
6239 for (my $count = $linenr; $count <= $lc; $count++) {
6243 my $bad_specifier = "";
6244 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6247 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6251 if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6252 ($extension eq "f" &&
6253 defined $qualifier && $qualifier !~ /^w/)) {
6254 $bad_specifier = $specifier;
6257 if ($extension eq "x" && !defined($stat_real)) {
6258 if (!defined($stat_real)) {
6259 $stat_real = get_stat_real($linenr, $lc);
6261 WARN("VSPRINTF_SPECIFIER_PX",
6262 "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");
6265 if ($bad_specifier ne "") {
6266 my $stat_real = get_stat_real($linenr, $lc);
6267 my $ext_type = "Invalid";
6269 if ($bad_specifier =~ /p[Ff]/) {
6270 $use = " - use %pS instead";
6271 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6274 WARN("VSPRINTF_POINTER_EXTENSION",
6275 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6280 # Check for misused memsets
6281 if ($perl_version_ok &&
6283 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6289 if ($ms_size =~ /^(0x|)0$/i) {
6291 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6292 } elsif ($ms_size =~ /^(0x|)1$/i) {
6294 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6298 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6299 # if ($perl_version_ok &&
6301 # $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6302 # if (WARN("PREFER_ETHER_ADDR_COPY",
6303 # "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6305 # $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6309 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6310 # if ($perl_version_ok &&
6312 # $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6313 # WARN("PREFER_ETHER_ADDR_EQUAL",
6314 # "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6317 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6318 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6319 # if ($perl_version_ok &&
6321 # $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6325 # if ($ms_val =~ /^(?:0x|)0+$/i) {
6326 # if (WARN("PREFER_ETH_ZERO_ADDR",
6327 # "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6329 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6331 # } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6332 # if (WARN("PREFER_ETH_BROADCAST_ADDR",
6333 # "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6335 # $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6340 # typecasts on min/max could be min_t/max_t
6341 if ($perl_version_ok &&
6343 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6344 if (defined $2 || defined $7) {
6346 my $cast1 = deparenthesize($2);
6348 my $cast2 = deparenthesize($7);
6352 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6353 $cast = "$cast1 or $cast2";
6354 } elsif ($cast1 ne "") {
6360 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6364 # check usleep_range arguments
6365 if ($perl_version_ok &&
6367 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6371 WARN("USLEEP_RANGE",
6372 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6373 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6375 WARN("USLEEP_RANGE",
6376 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6380 # check for naked sscanf
6381 if ($perl_version_ok &&
6383 $line =~ /\bsscanf\b/ &&
6384 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6385 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6386 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6387 my $lc = $stat =~ tr@\n@@;
6388 $lc = $lc + $linenr;
6389 my $stat_real = get_stat_real($linenr, $lc);
6390 WARN("NAKED_SSCANF",
6391 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6394 # check for simple sscanf that should be kstrto<foo>
6395 if ($perl_version_ok &&
6397 $line =~ /\bsscanf\b/) {
6398 my $lc = $stat =~ tr@\n@@;
6399 $lc = $lc + $linenr;
6400 my $stat_real = get_stat_real($linenr, $lc);
6401 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6403 my $count = $format =~ tr@%@%@;
6405 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6406 WARN("SSCANF_TO_KSTRTO",
6407 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6412 # check for new externs in .h files.
6413 if ($realfile =~ /\.h$/ &&
6414 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6415 if (CHK("AVOID_EXTERNS",
6416 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6418 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6422 # check for new externs in .c files.
6423 if ($realfile =~ /\.c$/ && defined $stat &&
6424 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6426 my $function_name = $1;
6427 my $paren_space = $2;
6430 if (defined $cond) {
6431 substr($s, 0, length($cond), '');
6435 WARN("AVOID_EXTERNS",
6436 "externs should be avoided in .c files\n" . $herecurr);
6439 if ($paren_space =~ /\n/) {
6440 WARN("FUNCTION_ARGUMENTS",
6441 "arguments for function declarations should follow identifier\n" . $herecurr);
6444 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6445 $stat =~ /^.\s*extern\s+/)
6447 WARN("AVOID_EXTERNS",
6448 "externs should be avoided in .c files\n" . $herecurr);
6451 # check for function declarations that have arguments without identifier names
6452 if (defined $stat &&
6453 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6455 my $args = trim($1);
6456 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6458 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6459 WARN("FUNCTION_ARGUMENTS",
6460 "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6465 # check for function definitions
6466 if ($perl_version_ok &&
6468 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6469 $context_function = $1;
6471 # check for multiline function definition with misplaced open brace
6473 my $cnt = statement_rawlines($stat);
6474 my $herectx = $here . "\n";
6475 for (my $n = 0; $n < $cnt; $n++) {
6476 my $rl = raw_line($linenr, $n);
6477 $herectx .= $rl . "\n";
6478 $ok = 1 if ($rl =~ /^[ \+]\{/);
6479 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6480 last if $rl =~ /^[ \+].*\{/;
6484 "open brace '{' following function definitions go on the next line\n" . $herectx);
6488 # checks for new __setup's
6489 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6492 if (!grep(/$name/, @setup_docs)) {
6493 CHK("UNDOCUMENTED_SETUP",
6494 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6498 # check for pointless casting of alloc functions
6499 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6500 WARN("UNNECESSARY_CASTS",
6501 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6505 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6506 if ($perl_version_ok &&
6507 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6508 CHK("ALLOC_SIZEOF_STRUCT",
6509 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6512 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6513 if ($perl_version_ok &&
6515 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6519 my $newfunc = "kmalloc_array";
6520 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6523 if ($a1 =~ /^sizeof\s*\S/) {
6527 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6528 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6529 my $cnt = statement_rawlines($stat);
6530 my $herectx = get_stat_here($linenr, $cnt, $here);
6532 if (WARN("ALLOC_WITH_MULTIPLY",
6533 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6536 $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;
6541 # check for krealloc arg reuse
6542 if ($perl_version_ok &&
6543 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6545 WARN("KREALLOC_ARG_REUSE",
6546 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6549 # check for alloc argument mismatch
6550 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6551 WARN("ALLOC_ARRAY_ARGS",
6552 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6555 # check for multiple semicolons
6556 if ($line =~ /;\s*;\s*$/) {
6557 if (WARN("ONE_SEMICOLON",
6558 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6560 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6564 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6565 if ($realfile !~ m@^include/uapi/@ &&
6566 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6568 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6569 if (CHK("BIT_MACRO",
6570 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6572 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6576 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6577 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6578 WARN("IS_ENABLED_CONFIG",
6579 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6582 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6583 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6585 if (WARN("PREFER_IS_ENABLED",
6586 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6588 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6592 # check for /* fallthrough */ like comment, prefer fallthrough;
6593 my @fallthroughs = (
6596 'lint -fallthrough[ \t]*',
6597 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6598 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6599 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6600 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6602 if ($raw_comment ne '') {
6603 foreach my $ft (@fallthroughs) {
6604 if ($raw_comment =~ /$ft/) {
6605 my $msg_level = \&WARN;
6606 $msg_level = \&CHK if ($file);
6607 &{$msg_level}("PREFER_FALLTHROUGH",
6608 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6614 # check for switch/default statements without a break;
6615 if ($perl_version_ok &&
6617 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6618 my $cnt = statement_rawlines($stat);
6619 my $herectx = get_stat_here($linenr, $cnt, $here);
6621 WARN("DEFAULT_NO_BREAK",
6622 "switch default: should use break\n" . $herectx);
6625 # check for gcc specific __FUNCTION__
6626 if ($line =~ /\b__FUNCTION__\b/) {
6627 if (WARN("USE_FUNC",
6628 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
6630 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6634 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6635 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6637 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6640 # check for use of yield()
6641 if ($line =~ /\byield\s*\(\s*\)/) {
6643 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
6646 # check for comparisons against true and false
6647 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6655 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6657 my $type = lc($otype);
6658 if ($type =~ /^(?:true|false)$/) {
6659 if (("$test" eq "==" && "$type" eq "true") ||
6660 ("$test" eq "!=" && "$type" eq "false")) {
6664 CHK("BOOL_COMPARISON",
6665 "Using comparison to $otype is error prone\n" . $herecurr);
6667 ## maybe suggesting a correct construct would better
6668 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6673 # check for semaphores initialized locked
6674 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6675 WARN("CONSIDER_COMPLETION",
6676 "consider using a completion\n" . $herecurr);
6679 # recommend kstrto* over simple_strto* and strict_strto*
6680 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6681 WARN("CONSIDER_KSTRTO",
6682 "$1 is obsolete, use k$3 instead\n" . $herecurr);
6685 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6686 if ($line =~ /^.\s*__initcall\s*\(/) {
6687 WARN("USE_DEVICE_INITCALL",
6688 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6691 # check for spin_is_locked(), suggest lockdep instead
6692 if ($line =~ /\bspin_is_locked\(/) {
6694 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6697 # check for deprecated apis
6698 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6699 my $deprecated_api = $1;
6700 my $new_api = $deprecated_apis{$deprecated_api};
6701 WARN("DEPRECATED_API",
6702 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6705 # check for various structs that are normally const (ops, kgdb, device_tree)
6706 # and avoid what seem like struct definitions 'struct foo {'
6707 if (defined($const_structs) &&
6708 $line !~ /\bconst\b/ &&
6709 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6710 WARN("CONST_STRUCT",
6711 "struct $1 should normally be const\n" . $herecurr);
6714 # use of NR_CPUS is usually wrong
6715 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6716 if ($line =~ /\bNR_CPUS\b/ &&
6717 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6718 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6719 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6720 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6721 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6724 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6727 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6728 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6729 ERROR("DEFINE_ARCH_HAS",
6730 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6733 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6734 if ($perl_version_ok &&
6735 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6736 WARN("LIKELY_MISUSE",
6737 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6740 # nested likely/unlikely calls
6741 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6742 WARN("LIKELY_MISUSE",
6743 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6746 # whine mightly about in_atomic
6747 if ($line =~ /\bin_atomic\s*\(/) {
6748 if ($realfile =~ m@^drivers/@) {
6750 "do not use in_atomic in drivers\n" . $herecurr);
6751 } elsif ($realfile !~ m@^kernel/@) {
6753 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6757 # check for mutex_trylock_recursive usage
6758 if ($line =~ /mutex_trylock_recursive/) {
6760 "recursive locking is bad, do not use this ever.\n" . $herecurr);
6763 # check for lockdep_set_novalidate_class
6764 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6765 $line =~ /__lockdep_no_validate__\s*\)/ ) {
6766 if ($realfile !~ m@^kernel/lockdep@ &&
6767 $realfile !~ m@^include/linux/lockdep@ &&
6768 $realfile !~ m@^drivers/base/core@) {
6770 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6774 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6775 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6776 WARN("EXPORTED_WORLD_WRITABLE",
6777 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6780 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6781 # and whether or not function naming is typical and if
6782 # DEVICE_ATTR permissions uses are unusual too
6783 if ($perl_version_ok &&
6785 $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*\)/) {
6790 my $octal_perms = perms_to_octal($perms);
6791 if ($show =~ /^${var}_show$/ &&
6792 $store =~ /^${var}_store$/ &&
6793 $octal_perms eq "0644") {
6794 if (WARN("DEVICE_ATTR_RW",
6795 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6797 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6799 } elsif ($show =~ /^${var}_show$/ &&
6800 $store =~ /^NULL$/ &&
6801 $octal_perms eq "0444") {
6802 if (WARN("DEVICE_ATTR_RO",
6803 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6805 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6807 } elsif ($show =~ /^NULL$/ &&
6808 $store =~ /^${var}_store$/ &&
6809 $octal_perms eq "0200") {
6810 if (WARN("DEVICE_ATTR_WO",
6811 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6813 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6815 } elsif ($octal_perms eq "0644" ||
6816 $octal_perms eq "0444" ||
6817 $octal_perms eq "0200") {
6818 my $newshow = "$show";
6819 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6820 my $newstore = $store;
6821 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6823 if ($show ne $newshow) {
6824 $rename .= " '$show' to '$newshow'";
6826 if ($store ne $newstore) {
6827 $rename .= " '$store' to '$newstore'";
6829 WARN("DEVICE_ATTR_FUNCTIONS",
6830 "Consider renaming function(s)$rename\n" . $herecurr);
6832 WARN("DEVICE_ATTR_PERMS",
6833 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6837 # Mode permission misuses where it seems decimal should be octal
6838 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6839 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6840 # specific definition of not visible in sysfs.
6841 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6842 # use the default permissions
6843 if ($perl_version_ok &&
6845 $line =~ /$mode_perms_search/) {
6846 foreach my $entry (@mode_permission_funcs) {
6847 my $func = $entry->[0];
6848 my $arg_pos = $entry->[1];
6850 my $lc = $stat =~ tr@\n@@;
6851 $lc = $lc + $linenr;
6852 my $stat_real = get_stat_real($linenr, $lc);
6857 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6859 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6860 if ($stat =~ /$test/) {
6862 $val = $6 if ($skip_args ne "");
6863 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6864 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6865 ($val =~ /^$Octal$/ && length($val) ne 4))) {
6866 ERROR("NON_OCTAL_PERMISSIONS",
6867 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6869 if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6870 ERROR("EXPORTED_WORLD_WRITABLE",
6871 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6877 # check for uses of S_<PERMS> that could be octal for readability
6878 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6880 my $octal = perms_to_octal($oval);
6881 if (WARN("SYMBOLIC_PERMS",
6882 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6884 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6888 # validate content of MODULE_LICENSE against list from include/linux/module.h
6889 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6890 my $extracted_string = get_quoted_string($line, $rawline);
6891 my $valid_licenses = qr{
6894 GPL\ and\ additional\ rights|
6900 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6901 WARN("MODULE_LICENSE",
6902 "unknown module license " . $extracted_string . "\n" . $herecurr);
6906 # check for sysctl duplicate constants
6907 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6908 WARN("DUPLICATED_SYSCTL_CONST",
6909 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6913 # If we have no input at all, then there is nothing to report on
6914 # so just keep quiet.
6915 if ($#rawlines == -1) {
6919 # In mailback mode only produce a report in the negative, for
6920 # things that appear to be patches.
6921 if ($mailback && ($clean == 1 || !$is_patch)) {
6925 # This is not a patch, and we are are in 'no-patch' mode so
6927 if (!$chk_patch && !$is_patch) {
6931 if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6932 ERROR("NOT_UNIFIED_DIFF",
6933 "Does not appear to be a unified-diff format patch\n");
6935 if ($is_patch && $has_commit_log && $chk_signoff) {
6936 if ($signoff == 0) {
6937 ERROR("MISSING_SIGN_OFF",
6938 "Missing Signed-off-by: line(s)\n");
6939 } elsif (!$authorsignoff) {
6940 WARN("NO_AUTHOR_SIGN_OFF",
6941 "Missing Signed-off-by: line by nominal patch author '$author'\n");
6945 print report_dump();
6946 if ($summary && !($clean == 1 && $quiet == 1)) {
6947 print "$filename " if ($summary_file);
6948 print "total: $cnt_error errors, $cnt_warn warnings, " .
6949 (($check)? "$cnt_chk checks, " : "") .
6950 "$cnt_lines lines checked\n";
6954 # If there were any defects found and not already fixing them
6955 if (!$clean and !$fix) {
6958 NOTE: For some of the reported defects, checkpatch may be able to
6959 mechanically convert to the typical style using --fix or --fix-inplace.
6962 # If there were whitespace errors which cleanpatch can fix
6963 # then suggest that.
6964 if ($rpt_cleaners) {
6968 NOTE: Whitespace errors detected.
6969 You may wish to use scripts/cleanpatch or scripts/cleanfile
6974 if ($clean == 0 && $fix &&
6975 ("@rawlines" ne "@fixed" ||
6976 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6977 my $newfile = $filename;
6978 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6982 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6984 open($f, '>', $newfile)
6985 or die "$P: Can't open $newfile for write\n";
6986 foreach my $fixed_line (@fixed) {
6989 if ($linecount > 3) {
6990 $fixed_line =~ s/^\+//;
6991 print $f $fixed_line . "\n";
6994 print $f $fixed_line . "\n";
7002 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7004 Do _NOT_ trust the results written to this file.
7005 Do _NOT_ submit these changes without inspecting them for correctness.
7007 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7008 No warranties, expressed or implied...
7016 print "$vname has no obvious style problems and is ready for submission.\n";
7018 print "$vname has style problems, please review.\n";