2 # (c) 2001, Dave Jones. (the file handling bit)
3 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6 # Licensed under the terms of the GNU GPL License version 2
12 use Term::ANSIColor qw(:constants);
14 use constant BEFORE_SHORTTEXT => 0;
15 use constant IN_SHORTTEXT_BLANKLINE => 1;
16 use constant IN_SHORTTEXT => 2;
17 use constant AFTER_SHORTTEXT => 3;
18 use constant CHECK_NEXT_SHORTTEXT => 4;
19 use constant SHORTTEXT_LIMIT => 75;
22 my $D = dirname(abs_path($P));
26 use Getopt::Long qw(:config no_auto_abbrev);
54 my $configuration_file = ".checkpatch.conf";
55 my $max_line_length = 80;
56 my $ignore_perl_version = 0;
57 my $minimum_perl_version = 5.10.0;
58 my $min_conf_desc_length = 4;
59 my $spelling_file = "$D/spelling.txt";
61 my $codespellfile = "/usr/share/codespell/dictionary.txt";
64 my $codeaurora_sign_off = 0;
70 Usage: $P [OPTION]... [FILE]...
75 --no-tree run without a kernel tree
76 --no-signoff do not check for 'Signed-off-by' line
77 --no-author do not check for unexpected authors
78 --patch treat FILE as patchfile (default)
79 --emacs emacs compile window format
80 --terse one line per report
81 --showfile emit diffed file position, not input file position
82 -f, --file treat FILE as regular source file
83 --subjective, --strict enable more subjective tests
84 --types TYPE(,TYPE2...) show only these comma separated message types
85 --ignore TYPE(,TYPE2...) ignore various comma separated message types
86 --max-line-length=n set the maximum line length, if exceeded, warn
87 --min-conf-desc-length=n set the min description length, if shorter, warn
88 --show-types show the message "types" in the output
89 --root=PATH PATH to the kernel tree root
90 --no-summary suppress the per-file summary
91 --mailback only produce a report in case of warnings/errors
92 --summary-file include the filename in summary
93 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
94 'values', 'possible', 'type', and 'attr' (default
96 --test-only=WORD report only warnings/errors containing WORD
98 --fix EXPERIMENTAL - may create horrible results
99 If correctable single-line errors exist, create
100 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
101 with potential errors corrected to the preferred
103 --fix-inplace EXPERIMENTAL - may create horrible results
104 Is the same as --fix, but overwrites the input
105 file. It's your fault if there's no backup or git
106 --ignore-perl-version override checking of perl version. expect
108 --codespell Use the codespell dictionary for spelling/typos
109 (default:/usr/share/codespell/dictionary.txt)
110 --codespellfile Use this codespell dictionary
111 --color Use colors when output is STDOUT (default: on)
112 -h, --help, --version display this help and exit
114 When FILE is - read standard input.
120 my $conf = which_conf($configuration_file);
123 open(my $conffile, '<', "$conf")
124 or warn "$P: Can't find a readable $configuration_file file $!\n";
126 while (<$conffile>) {
129 $line =~ s/\s*\n?$//g;
133 next if ($line =~ m/^\s*#/);
134 next if ($line =~ m/^\s*$/);
136 my @words = split(" ", $line);
137 foreach my $word (@words) {
138 last if ($word =~ m/^#/);
139 push (@conf_args, $word);
143 unshift(@ARGV, @conf_args) if @conf_args;
147 'q|quiet+' => \$quiet,
149 'signoff!' => \$chk_signoff,
150 'patch!' => \$chk_patch,
151 'author!' => \$chk_author,
154 'showfile!' => \$showfile,
156 'subjective!' => \$check,
157 'strict!' => \$check,
158 'ignore=s' => \@ignore,
160 'show-types!' => \$show_types,
161 'max-line-length=i' => \$max_line_length,
162 'min-conf-desc-length=i' => \$min_conf_desc_length,
164 'summary!' => \$summary,
165 'mailback!' => \$mailback,
166 'summary-file!' => \$summary_file,
168 'fix-inplace!' => \$fix_inplace,
169 'ignore-perl-version!' => \$ignore_perl_version,
170 'debug=s' => \%debug,
171 'test-only=s' => \$tst_only,
172 'codespell!' => \$codespell,
173 'codespellfile=s' => \$codespellfile,
181 $fix = 1 if ($fix_inplace);
182 $check_orig = $check;
186 if ($^V && $^V lt $minimum_perl_version) {
187 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
188 if (!$ignore_perl_version) {
194 print "$P: no input files\n";
198 sub hash_save_array_words {
199 my ($hashRef, $arrayRef) = @_;
201 my @array = split(/,/, join(',', @$arrayRef));
202 foreach my $word (@array) {
203 $word =~ s/\s*\n?$//g;
206 $word =~ tr/[a-z]/[A-Z]/;
208 next if ($word =~ m/^\s*#/);
209 next if ($word =~ m/^\s*$/);
215 sub hash_show_words {
216 my ($hashRef, $prefix) = @_;
218 if (keys %$hashRef) {
219 print "\nNOTE: $prefix message types:";
220 foreach my $word (sort keys %$hashRef) {
227 hash_save_array_words(\%ignore_type, \@ignore);
228 hash_save_array_words(\%use_type, \@use);
231 my $dbg_possible = 0;
234 for my $key (keys %debug) {
236 eval "\${dbg_$key} = '$debug{$key}';";
240 my $rpt_cleaners = 0;
249 if (!top_of_kernel_tree($root)) {
250 die "$P: $root: --root does not point at a valid tree\n";
253 if (top_of_kernel_tree('.')) {
255 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
256 top_of_kernel_tree($1)) {
261 if (!defined $root) {
262 print "Must be run from the top-level dir. of a kernel tree\n";
267 my $emitted_corrupt = 0;
270 [A-Za-z_][A-Za-z\d_]*
271 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
273 our $Storage = qr{extern|static|asmlinkage};
286 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
287 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
288 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
289 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
290 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
292 # Notes to $Attribute:
293 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
314 ____cacheline_aligned|
315 ____cacheline_aligned_in_smp|
316 ____cacheline_internodealigned_in_smp|
320 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
321 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
322 our $Lval = qr{$Ident(?:$Member)*};
324 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
325 our $Binary = qr{(?i)0b[01]+$Int_type?};
326 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
327 our $Int = qr{[0-9]+$Int_type?};
328 our $Octal = qr{0[0-7]+$Int_type?};
329 our $String = qr{"[X\t]*"};
330 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
331 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
332 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
333 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
334 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
335 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
336 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
337 our $Arithmetic = qr{\+|-|\*|\/|%};
341 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
344 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
348 our $NonptrTypeMisordered;
349 our $NonptrTypeWithAttr;
353 our $DeclareMisordered;
355 our $NON_ASCII_UTF8 = qr{
356 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
357 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
358 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
359 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
360 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
361 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
362 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
366 [\x09\x0A\x0D\x20-\x7E] # ASCII
370 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
371 our $typeOtherOSTypedefs = qr{(?x:
372 u_(?:char|short|int|long) | # bsd
373 u(?:nchar|short|int|long) # sysv
375 our $typeKernelTypedefs = qr{(?x:
376 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
379 our $typeTypedefs = qr{(?x:
381 $typeOtherOSTypedefs\b|
382 $typeKernelTypedefs\b
385 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
387 our $logFunctions = qr{(?x:
388 printk(?:_ratelimited|_once|)|
389 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
390 WARN(?:_RATELIMIT|_ONCE|)|
393 seq_vprintf|seq_printf|seq_puts
396 our $signature_tags = qr{(?xi:
407 our @typeListMisordered = (
408 qr{char\s+(?:un)?signed},
409 qr{int\s+(?:(?:un)?signed\s+)?short\s},
410 qr{int\s+short(?:\s+(?:un)?signed)},
411 qr{short\s+int(?:\s+(?:un)?signed)},
412 qr{(?:un)?signed\s+int\s+short},
413 qr{short\s+(?:un)?signed},
414 qr{long\s+int\s+(?:un)?signed},
415 qr{int\s+long\s+(?:un)?signed},
416 qr{long\s+(?:un)?signed\s+int},
417 qr{int\s+(?:un)?signed\s+long},
418 qr{int\s+(?:un)?signed},
419 qr{int\s+long\s+long\s+(?:un)?signed},
420 qr{long\s+long\s+int\s+(?:un)?signed},
421 qr{long\s+long\s+(?:un)?signed\s+int},
422 qr{long\s+long\s+(?:un)?signed},
423 qr{long\s+(?:un)?signed},
428 qr{(?:(?:un)?signed\s+)?char},
429 qr{(?:(?:un)?signed\s+)?short\s+int},
430 qr{(?:(?:un)?signed\s+)?short},
431 qr{(?:(?:un)?signed\s+)?int},
432 qr{(?:(?:un)?signed\s+)?long\s+int},
433 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
434 qr{(?:(?:un)?signed\s+)?long\s+long},
435 qr{(?:(?:un)?signed\s+)?long},
444 qr{${Ident}_handler},
445 qr{${Ident}_handler_fn},
448 our @typeListFile = ();
449 our @typeListWithAttr = (
451 qr{struct\s+$InitAttribute\s+$Ident},
452 qr{union\s+$InitAttribute\s+$Ident},
455 our @modifierList = (
458 our @modifierListFile = ();
460 our @mode_permission_funcs = (
462 ["module_param_(?:array|named|string)", 4],
463 ["module_param_array_named", 5],
464 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
465 ["proc_create(?:_data|)", 2],
466 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
469 #Create a search pattern for all these functions to speed up a loop below
470 our $mode_perms_search = "";
471 foreach my $entry (@mode_permission_funcs) {
472 $mode_perms_search .= '|' if ($mode_perms_search ne "");
473 $mode_perms_search .= $entry->[0];
476 our $mode_perms_world_writable = qr{
484 our $allowed_asm_includes = qr{(?x:
490 # memory.h: ARM has a custom one
492 # Load common spelling mistakes and build regular expression list.
496 if (open(my $spelling, '<', $spelling_file)) {
497 while (<$spelling>) {
500 $line =~ s/\s*\n?$//g;
503 next if ($line =~ m/^\s*#/);
504 next if ($line =~ m/^\s*$/);
506 my ($suspect, $fix) = split(/\|\|/, $line);
508 $spelling_fix{$suspect} = $fix;
512 warn "No typos will be found - file '$spelling_file': $!\n";
516 if (open(my $spelling, '<', $codespellfile)) {
517 while (<$spelling>) {
520 $line =~ s/\s*\n?$//g;
523 next if ($line =~ m/^\s*#/);
524 next if ($line =~ m/^\s*$/);
525 next if ($line =~ m/, disabled/i);
529 my ($suspect, $fix) = split(/->/, $line);
531 $spelling_fix{$suspect} = $fix;
535 warn "No codespell typos will be found - file '$codespellfile': $!\n";
539 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
542 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
543 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
544 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
545 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
546 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
552 (?:$Modifier\s+|const\s+)*
554 (?:typeof|__typeof__)\s*\([^\)]*\)|
558 (?:\s+$Modifier|\s+const)*
560 $NonptrTypeMisordered = qr{
561 (?:$Modifier\s+|const\s+)*
565 (?:\s+$Modifier|\s+const)*
567 $NonptrTypeWithAttr = qr{
568 (?:$Modifier\s+|const\s+)*
570 (?:typeof|__typeof__)\s*\([^\)]*\)|
574 (?:\s+$Modifier|\s+const)*
578 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
579 (?:\s+$Inline|\s+$Modifier)*
581 $TypeMisordered = qr{
582 $NonptrTypeMisordered
583 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
584 (?:\s+$Inline|\s+$Modifier)*
586 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
587 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
591 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
593 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
594 # requires at least perl version v5.10.0
595 # Any use must be runtime checked with $^V
597 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
598 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
599 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
601 our $declaration_macros = qr{(?x:
602 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
603 (?:$Storage\s+)?LIST_HEAD\s*\(|
604 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
609 return "" if (!defined($string));
611 while ($string =~ /^\s*\(.*\)\s*$/) {
612 $string =~ s@^\s*\(\s*@@;
613 $string =~ s@\s*\)\s*$@@;
616 $string =~ s@\s+@ @g;
621 sub seed_camelcase_file {
624 return if (!(-f $file));
628 open(my $include_file, '<', "$file")
629 or warn "$P: Can't read '$file' $!\n";
630 my $text = <$include_file>;
631 close($include_file);
633 my @lines = split('\n', $text);
635 foreach my $line (@lines) {
636 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
637 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
639 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
641 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
647 my $camelcase_seeded = 0;
648 sub seed_camelcase_includes {
649 return if ($camelcase_seeded);
652 my $camelcase_cache = "";
653 my @include_files = ();
655 $camelcase_seeded = 1;
658 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
659 chomp $git_last_include_commit;
660 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
662 my $last_mod_date = 0;
663 $files = `find $root/include -name "*.h"`;
664 @include_files = split('\n', $files);
665 foreach my $file (@include_files) {
666 my $date = POSIX::strftime("%Y%m%d%H%M",
667 localtime((stat $file)[9]));
668 $last_mod_date = $date if ($last_mod_date < $date);
670 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
673 if ($camelcase_cache ne "" && -f $camelcase_cache) {
674 open(my $camelcase_file, '<', "$camelcase_cache")
675 or warn "$P: Can't read '$camelcase_cache' $!\n";
676 while (<$camelcase_file>) {
680 close($camelcase_file);
686 $files = `git ls-files "include/*.h"`;
687 @include_files = split('\n', $files);
690 foreach my $file (@include_files) {
691 seed_camelcase_file($file);
694 if ($camelcase_cache ne "") {
695 unlink glob ".checkpatch-camelcase.*";
696 open(my $camelcase_file, '>', "$camelcase_cache")
697 or warn "$P: Can't write '$camelcase_cache' $!\n";
698 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
699 print $camelcase_file ("$_\n");
701 close($camelcase_file);
705 sub git_commit_info {
706 my ($commit, $id, $desc) = @_;
708 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
710 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
711 $output =~ s/^\s*//gm;
712 my @lines = split("\n", $output);
714 return ($id, $desc) if ($#lines < 0);
716 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
717 # Maybe one day convert this block of bash into something that returns
718 # all matching commit ids, but it's very slow...
720 # echo "checking commits $1..."
721 # git rev-list --remotes | grep -i "^$1" |
722 # while read line ; do
723 # git log --format='%H %s' -1 $line |
724 # echo "commit $(cut -c 1-12,41-)"
726 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
728 $id = substr($lines[0], 0, 12);
729 $desc = substr($lines[0], 41);
735 $chk_signoff = 0 if ($file);
740 my @fixed_inserted = ();
741 my @fixed_deleted = ();
745 for my $filename (@ARGV) {
748 open($FILE, '-|', "diff -u /dev/null $filename") ||
749 die "$P: $filename: diff failed - $!\n";
750 } elsif ($filename eq '-') {
751 open($FILE, '<&STDIN');
753 open($FILE, '<', "$filename") ||
754 die "$P: $filename: open failed - $!\n";
756 if ($filename eq '-') {
757 $vname = 'Your patch';
767 if ($#ARGV > 0 && $quiet == 0) {
768 print '-' x length($vname) . "\n";
770 print '-' x length($vname) . "\n";
773 if (!process($filename)) {
779 @fixed_inserted = ();
782 @modifierListFile = ();
788 hash_show_words(\%use_type, "Used");
789 hash_show_words(\%ignore_type, "Ignored");
794 NOTE: perl $^V is not modern enough to detect all possible issues.
795 An upgrade to at least perl v5.10.0 is suggested.
801 NOTE: If any of the errors are false positives, please report
802 them to the maintainer, see CHECKPATCH in MAINTAINERS.
809 sub top_of_kernel_tree {
813 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
814 "README", "Documentation", "arch", "include", "drivers",
815 "fs", "init", "ipc", "kernel", "lib", "scripts",
818 foreach my $check (@tree_check) {
819 if (! -e $root . '/' . $check) {
827 my ($formatted_email) = @_;
833 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
836 $comment = $3 if defined $3;
837 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
839 $comment = $2 if defined $2;
840 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
842 $comment = $2 if defined $2;
843 $formatted_email =~ s/$address.*$//;
844 $name = $formatted_email;
846 $name =~ s/^\"|\"$//g;
847 # If there's a name left after stripping spaces and
848 # leading quotes, and the address doesn't have both
849 # leading and trailing angle brackets, the address
851 # "joe smith joe@smith.com" bad
852 # "joe smith <joe@smith.com" bad
853 if ($name ne "" && $address !~ /^<[^>]+>$/) {
861 $name =~ s/^\"|\"$//g;
862 $address = trim($address);
863 $address =~ s/^\<|\>$//g;
865 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
866 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
870 return ($name, $address, $comment);
874 my ($name, $address) = @_;
879 $name =~ s/^\"|\"$//g;
880 $address = trim($address);
882 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
883 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
888 $formatted_email = "$address";
890 $formatted_email = "$name <$address>";
893 return $formatted_email;
899 foreach my $path (split(/:/, $ENV{PATH})) {
900 if (-e "$path/$bin") {
911 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
912 if (-e "$path/$conf") {
913 return "$path/$conf";
925 for my $c (split(//, $str)) {
929 for (; ($n % 8) != 0; $n++) {
941 (my $res = shift) =~ tr/\t/ /c;
948 # Drop the diff line leader and expand tabs
950 $line = expand_tabs($line);
952 # Pick the indent from the front of the line.
953 my ($white) = ($line =~ /^(\s*)/);
955 return (length($line), length($white));
958 my $sanitise_quote = '';
960 sub sanitise_line_reset {
961 my ($in_comment) = @_;
964 $sanitise_quote = '*/';
966 $sanitise_quote = '';
979 # Always copy over the diff marker.
980 $res = substr($line, 0, 1);
982 for ($off = 1; $off < length($line); $off++) {
983 $c = substr($line, $off, 1);
985 # Comments we are wacking completly including the begin
986 # and end, all to $;.
987 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
988 $sanitise_quote = '*/';
990 substr($res, $off, 2, "$;$;");
994 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
995 $sanitise_quote = '';
996 substr($res, $off, 2, "$;$;");
1000 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1001 $sanitise_quote = '//';
1003 substr($res, $off, 2, $sanitise_quote);
1008 # A \ in a string means ignore the next character.
1009 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1011 substr($res, $off, 2, 'XX');
1016 if ($c eq "'" || $c eq '"') {
1017 if ($sanitise_quote eq '') {
1018 $sanitise_quote = $c;
1020 substr($res, $off, 1, $c);
1022 } elsif ($sanitise_quote eq $c) {
1023 $sanitise_quote = '';
1027 #print "c<$c> SQ<$sanitise_quote>\n";
1028 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1029 substr($res, $off, 1, $;);
1030 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1031 substr($res, $off, 1, $;);
1032 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1033 substr($res, $off, 1, 'X');
1035 substr($res, $off, 1, $c);
1039 if ($sanitise_quote eq '//') {
1040 $sanitise_quote = '';
1043 # The pathname on a #include may be surrounded by '<' and '>'.
1044 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1045 my $clean = 'X' x length($1);
1046 $res =~ s@\<.*\>@<$clean>@;
1048 # The whole of a #error is a string.
1049 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1050 my $clean = 'X' x length($1);
1051 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1057 sub get_quoted_string {
1058 my ($line, $rawline) = @_;
1060 return "" if ($line !~ m/($String)/g);
1061 return substr($rawline, $-[0], $+[0] - $-[0]);
1064 sub ctx_statement_block {
1065 my ($linenr, $remain, $off) = @_;
1066 my $line = $linenr - 1;
1069 my $coff = $off - 1;
1083 @stack = (['', 0]) if ($#stack == -1);
1085 #warn "CSB: blk<$blk> remain<$remain>\n";
1086 # If we are about to drop off the end, pull in more
1089 for (; $remain > 0; $line++) {
1090 last if (!defined $lines[$line]);
1091 next if ($lines[$line] =~ /^-/);
1094 $blk .= $lines[$line] . "\n";
1095 $len = length($blk);
1099 # Bail if there is no further context.
1100 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1104 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1110 $c = substr($blk, $off, 1);
1111 $remainder = substr($blk, $off);
1113 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1115 # Handle nested #if/#else.
1116 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1117 push(@stack, [ $type, $level ]);
1118 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1119 ($type, $level) = @{$stack[$#stack - 1]};
1120 } elsif ($remainder =~ /^#\s*endif\b/) {
1121 ($type, $level) = @{pop(@stack)};
1124 # Statement ends at the ';' or a close '}' at the
1126 if ($level == 0 && $c eq ';') {
1130 # An else is really a conditional as long as its not else if
1131 if ($level == 0 && $coff_set == 0 &&
1132 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1133 $remainder =~ /^(else)(?:\s|{)/ &&
1134 $remainder !~ /^else\s+if\b/) {
1135 $coff = $off + length($1) - 1;
1137 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1138 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1141 if (($type eq '' || $type eq '(') && $c eq '(') {
1145 if ($type eq '(' && $c eq ')') {
1147 $type = ($level != 0)? '(' : '';
1149 if ($level == 0 && $coff < $soff) {
1152 #warn "CSB: mark coff<$coff>\n";
1155 if (($type eq '' || $type eq '{') && $c eq '{') {
1159 if ($type eq '{' && $c eq '}') {
1161 $type = ($level != 0)? '{' : '';
1164 if (substr($blk, $off + 1, 1) eq ';') {
1170 # Preprocessor commands end at the newline unless escaped.
1171 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1179 # We are truly at the end, so shuffle to the next line.
1186 my $statement = substr($blk, $soff, $off - $soff + 1);
1187 my $condition = substr($blk, $soff, $coff - $soff + 1);
1189 #warn "STATEMENT<$statement>\n";
1190 #warn "CONDITION<$condition>\n";
1192 #print "coff<$coff> soff<$off> loff<$loff>\n";
1194 return ($statement, $condition,
1195 $line, $remain + 1, $off - $loff + 1, $level);
1198 sub statement_lines {
1201 # Strip the diff line prefixes and rip blank lines at start and end.
1202 $stmt =~ s/(^|\n)./$1/g;
1206 my @stmt_lines = ($stmt =~ /\n/g);
1208 return $#stmt_lines + 2;
1211 sub statement_rawlines {
1214 my @stmt_lines = ($stmt =~ /\n/g);
1216 return $#stmt_lines + 2;
1219 sub statement_block_size {
1222 $stmt =~ s/(^|\n)./$1/g;
1228 my @stmt_lines = ($stmt =~ /\n/g);
1229 my @stmt_statements = ($stmt =~ /;/g);
1231 my $stmt_lines = $#stmt_lines + 2;
1232 my $stmt_statements = $#stmt_statements + 1;
1234 if ($stmt_lines > $stmt_statements) {
1237 return $stmt_statements;
1241 sub ctx_statement_full {
1242 my ($linenr, $remain, $off) = @_;
1243 my ($statement, $condition, $level);
1247 # Grab the first conditional/block pair.
1248 ($statement, $condition, $linenr, $remain, $off, $level) =
1249 ctx_statement_block($linenr, $remain, $off);
1250 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1251 push(@chunks, [ $condition, $statement ]);
1252 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1253 return ($level, $linenr, @chunks);
1256 # Pull in the following conditional/block pairs and see if they
1257 # could continue the statement.
1259 ($statement, $condition, $linenr, $remain, $off, $level) =
1260 ctx_statement_block($linenr, $remain, $off);
1261 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1262 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1264 push(@chunks, [ $condition, $statement ]);
1267 return ($level, $linenr, @chunks);
1271 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1273 my $start = $linenr - 1;
1280 my @stack = ($level);
1281 for ($line = $start; $remain > 0; $line++) {
1282 next if ($rawlines[$line] =~ /^-/);
1285 $blk .= $rawlines[$line];
1287 # Handle nested #if/#else.
1288 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1289 push(@stack, $level);
1290 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1291 $level = $stack[$#stack - 1];
1292 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1293 $level = pop(@stack);
1296 foreach my $c (split(//, $lines[$line])) {
1297 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1303 if ($c eq $close && $level > 0) {
1305 last if ($level == 0);
1306 } elsif ($c eq $open) {
1311 if (!$outer || $level <= 1) {
1312 push(@res, $rawlines[$line]);
1315 last if ($level == 0);
1318 return ($level, @res);
1320 sub ctx_block_outer {
1321 my ($linenr, $remain) = @_;
1323 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1327 my ($linenr, $remain) = @_;
1329 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1333 my ($linenr, $remain, $off) = @_;
1335 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1338 sub ctx_block_level {
1339 my ($linenr, $remain) = @_;
1341 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1343 sub ctx_statement_level {
1344 my ($linenr, $remain, $off) = @_;
1346 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1349 sub ctx_locate_comment {
1350 my ($first_line, $end_line) = @_;
1352 # Catch a comment on the end of the line itself.
1353 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1354 return $current_comment if (defined $current_comment);
1356 # Look through the context and try and figure out if there is a
1359 $current_comment = '';
1360 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1361 my $line = $rawlines[$linenr - 1];
1363 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1366 if ($line =~ m@/\*@) {
1369 if (!$in_comment && $current_comment ne '') {
1370 $current_comment = '';
1372 $current_comment .= $line . "\n" if ($in_comment);
1373 if ($line =~ m@\*/@) {
1378 chomp($current_comment);
1379 return($current_comment);
1381 sub ctx_has_comment {
1382 my ($first_line, $end_line) = @_;
1383 my $cmt = ctx_locate_comment($first_line, $end_line);
1385 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1386 ##print "CMMT: $cmt\n";
1388 return ($cmt ne '');
1392 my ($linenr, $cnt) = @_;
1394 my $offset = $linenr - 1;
1399 $line = $rawlines[$offset++];
1400 next if (defined($line) && $line =~ /^-/);
1412 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1415 $coded = sprintf("^%c", unpack('C', $2) + 64);
1424 my $av_preprocessor = 0;
1429 sub annotate_reset {
1430 $av_preprocessor = 0;
1432 @av_paren_type = ('E');
1433 $av_pend_colon = 'O';
1436 sub annotate_values {
1437 my ($stream, $type) = @_;
1440 my $var = '_' x length($stream);
1443 print "$stream\n" if ($dbg_values > 1);
1445 while (length($cur)) {
1446 @av_paren_type = ('E') if ($#av_paren_type < 0);
1447 print " <" . join('', @av_paren_type) .
1448 "> <$type> <$av_pending>" if ($dbg_values > 1);
1449 if ($cur =~ /^(\s+)/o) {
1450 print "WS($1)\n" if ($dbg_values > 1);
1451 if ($1 =~ /\n/ && $av_preprocessor) {
1452 $type = pop(@av_paren_type);
1453 $av_preprocessor = 0;
1456 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1457 print "CAST($1)\n" if ($dbg_values > 1);
1458 push(@av_paren_type, $type);
1461 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1462 print "DECLARE($1)\n" if ($dbg_values > 1);
1465 } elsif ($cur =~ /^($Modifier)\s*/) {
1466 print "MODIFIER($1)\n" if ($dbg_values > 1);
1469 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1470 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1471 $av_preprocessor = 1;
1472 push(@av_paren_type, $type);
1478 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1479 print "UNDEF($1)\n" if ($dbg_values > 1);
1480 $av_preprocessor = 1;
1481 push(@av_paren_type, $type);
1483 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1484 print "PRE_START($1)\n" if ($dbg_values > 1);
1485 $av_preprocessor = 1;
1487 push(@av_paren_type, $type);
1488 push(@av_paren_type, $type);
1491 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1492 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1493 $av_preprocessor = 1;
1495 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1499 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1500 print "PRE_END($1)\n" if ($dbg_values > 1);
1502 $av_preprocessor = 1;
1504 # Assume all arms of the conditional end as this
1505 # one does, and continue as if the #endif was not here.
1506 pop(@av_paren_type);
1507 push(@av_paren_type, $type);
1510 } elsif ($cur =~ /^(\\\n)/o) {
1511 print "PRECONT($1)\n" if ($dbg_values > 1);
1513 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1514 print "ATTR($1)\n" if ($dbg_values > 1);
1515 $av_pending = $type;
1518 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1519 print "SIZEOF($1)\n" if ($dbg_values > 1);
1525 } elsif ($cur =~ /^(if|while|for)\b/o) {
1526 print "COND($1)\n" if ($dbg_values > 1);
1530 } elsif ($cur =~/^(case)/o) {
1531 print "CASE($1)\n" if ($dbg_values > 1);
1532 $av_pend_colon = 'C';
1535 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1536 print "KEYWORD($1)\n" if ($dbg_values > 1);
1539 } elsif ($cur =~ /^(\()/o) {
1540 print "PAREN('$1')\n" if ($dbg_values > 1);
1541 push(@av_paren_type, $av_pending);
1545 } elsif ($cur =~ /^(\))/o) {
1546 my $new_type = pop(@av_paren_type);
1547 if ($new_type ne '_') {
1549 print "PAREN('$1') -> $type\n"
1550 if ($dbg_values > 1);
1552 print "PAREN('$1')\n" if ($dbg_values > 1);
1555 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1556 print "FUNC($1)\n" if ($dbg_values > 1);
1560 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1561 if (defined $2 && $type eq 'C' || $type eq 'T') {
1562 $av_pend_colon = 'B';
1563 } elsif ($type eq 'E') {
1564 $av_pend_colon = 'L';
1566 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1569 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1570 print "IDENT($1)\n" if ($dbg_values > 1);
1573 } elsif ($cur =~ /^($Assignment)/o) {
1574 print "ASSIGN($1)\n" if ($dbg_values > 1);
1577 } elsif ($cur =~/^(;|{|})/) {
1578 print "END($1)\n" if ($dbg_values > 1);
1580 $av_pend_colon = 'O';
1582 } elsif ($cur =~/^(,)/) {
1583 print "COMMA($1)\n" if ($dbg_values > 1);
1586 } elsif ($cur =~ /^(\?)/o) {
1587 print "QUESTION($1)\n" if ($dbg_values > 1);
1590 } elsif ($cur =~ /^(:)/o) {
1591 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1593 substr($var, length($res), 1, $av_pend_colon);
1594 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1599 $av_pend_colon = 'O';
1601 } elsif ($cur =~ /^(\[)/o) {
1602 print "CLOSE($1)\n" if ($dbg_values > 1);
1605 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1608 print "OPV($1)\n" if ($dbg_values > 1);
1615 substr($var, length($res), 1, $variant);
1618 } elsif ($cur =~ /^($Operators)/o) {
1619 print "OP($1)\n" if ($dbg_values > 1);
1620 if ($1 ne '++' && $1 ne '--') {
1624 } elsif ($cur =~ /(^.)/o) {
1625 print "C($1)\n" if ($dbg_values > 1);
1628 $cur = substr($cur, length($1));
1629 $res .= $type x length($1);
1633 return ($res, $var);
1637 my ($possible, $line) = @_;
1638 my $notPermitted = qr{(?:
1655 ^(?:typedef|struct|enum)\b
1657 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1658 if ($possible !~ $notPermitted) {
1659 # Check for modifiers.
1660 $possible =~ s/\s*$Storage\s*//g;
1661 $possible =~ s/\s*$Sparse\s*//g;
1662 if ($possible =~ /^\s*$/) {
1664 } elsif ($possible =~ /\s/) {
1665 $possible =~ s/\s*$Type\s*//g;
1666 for my $modifier (split(' ', $possible)) {
1667 if ($modifier !~ $notPermitted) {
1668 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1669 push(@modifierListFile, $modifier);
1674 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1675 push(@typeListFile, $possible);
1679 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1688 return defined $use_type{$type} if (scalar keys %use_type > 0);
1690 return !defined $ignore_type{$type};
1694 my ($level, $type, $msg) = @_;
1696 if (!show_type($type) ||
1697 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1701 if (-t STDOUT && $color) {
1702 if ($level eq 'ERROR') {
1704 } elsif ($level eq 'WARNING') {
1710 $output .= $prefix . $level . ':';
1712 $output .= BLUE if (-t STDOUT && $color);
1713 $output .= "$type:";
1715 $output .= RESET if (-t STDOUT && $color);
1716 $output .= ' ' . $msg . "\n";
1719 my @lines = split("\n", $output, -1);
1720 splice(@lines, 1, 1);
1721 $output = join("\n", @lines);
1723 $output = (split('\n', $output))[0] . "\n" if ($terse);
1725 push(our @report, $output);
1734 sub fixup_current_range {
1735 my ($lineRef, $offset, $length) = @_;
1737 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1740 my $no = $o + $offset;
1741 my $nl = $l + $length;
1742 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1746 sub fix_inserted_deleted_lines {
1747 my ($linesRef, $insertedRef, $deletedRef) = @_;
1749 my $range_last_linenr = 0;
1750 my $delta_offset = 0;
1755 my $next_insert = 0;
1756 my $next_delete = 0;
1760 my $inserted = @{$insertedRef}[$next_insert++];
1761 my $deleted = @{$deletedRef}[$next_delete++];
1763 foreach my $old_line (@{$linesRef}) {
1765 my $line = $old_line; #don't modify the array
1766 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
1768 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1769 $range_last_linenr = $new_linenr;
1770 fixup_current_range(\$line, $delta_offset, 0);
1773 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1774 $deleted = @{$deletedRef}[$next_delete++];
1776 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1779 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1780 push(@lines, ${$inserted}{'LINE'});
1781 $inserted = @{$insertedRef}[$next_insert++];
1783 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1787 push(@lines, $line);
1797 sub fix_insert_line {
1798 my ($linenr, $line) = @_;
1804 push(@fixed_inserted, $inserted);
1807 sub fix_delete_line {
1808 my ($linenr, $line) = @_;
1815 push(@fixed_deleted, $deleted);
1819 my ($type, $msg) = @_;
1821 if (report("ERROR", $type, $msg)) {
1829 my ($type, $msg) = @_;
1831 if (report("WARNING", $type, $msg)) {
1839 my ($type, $msg) = @_;
1841 if ($check && report("CHECK", $type, $msg)) {
1849 sub check_absolute_file {
1850 my ($absolute, $herecurr) = @_;
1851 my $file = $absolute;
1853 ##print "absolute<$absolute>\n";
1855 # See if any suffix of this path is a path within the tree.
1856 while ($file =~ s@^[^/]*/@@) {
1857 if (-f "$root/$file") {
1858 ##print "file<$file>\n";
1866 # It is, so see if the prefix is acceptable.
1867 my $prefix = $absolute;
1868 substr($prefix, -length($file)) = '';
1870 ##print "prefix<$prefix>\n";
1871 if ($prefix ne ".../") {
1872 WARN("USE_RELATIVE_PATH",
1873 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1880 $string =~ s/^\s+|\s+$//g;
1888 $string =~ s/^\s+//;
1896 $string =~ s/\s+$//;
1901 sub string_find_replace {
1902 my ($string, $find, $replace) = @_;
1904 $string =~ s/$find/$replace/g;
1912 my $source_indent = 8;
1913 my $max_spaces_before_tab = $source_indent - 1;
1914 my $spaces_to_tab = " " x $source_indent;
1916 #convert leading spaces to tabs
1917 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1918 #Remove spaces before a tab
1919 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1924 sub cleanup_continuation_headers {
1925 # Collapse any header-continuation lines into a single line so they
1926 # can be parsed meaningfully, as the parser only has one line
1927 # of context to work with.
1931 foreach my $n (0 .. scalar(@rawlines) - 2) {
1932 if ($rawlines[$n]=~/^\s*$/) {
1933 # A blank line means there's no more chance
1934 # of finding headers. Shortcut to done.
1937 if ($rawlines[$n]=~/^[\x21-\x39\x3b-\x7e]+:/ &&
1938 $rawlines[$n+1]=~/^\s+/) {
1939 # Continuation header. Collapse it.
1940 my $line = splice @rawlines, $n+1, 1;
1942 $rawlines[$n] .= $line;
1943 # We've 'destabilized' the list, so restart.
1951 sub pos_last_openparen {
1956 my $opens = $line =~ tr/\(/\(/;
1957 my $closes = $line =~ tr/\)/\)/;
1959 my $last_openparen = 0;
1961 if (($opens == 0) || ($closes >= $opens)) {
1965 my $len = length($line);
1967 for ($pos = 0; $pos < $len; $pos++) {
1968 my $string = substr($line, $pos);
1969 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1970 $pos += length($1) - 1;
1971 } elsif (substr($line, $pos, 1) eq '(') {
1972 $last_openparen = $pos;
1973 } elsif (index($string, '(') == -1) {
1978 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1982 my $filename = shift;
1988 my $stashrawline="";
2000 my $in_header_lines = $file ? 0 : 1;
2001 my $in_commit_log = 0; #Scanning lines before patch
2002 my $commit_log_possible_stack_dump = 0;
2003 my $commit_log_long_line = 0;
2004 my $commit_log_has_diff = 0;
2005 my $reported_maintainer_file = 0;
2006 my $non_utf8_charset = 0;
2008 my $last_blank_line = 0;
2009 my $last_coalesced_string_linenr = -1;
2017 # Trace the real file/line as we go.
2023 my $comment_edge = 0;
2027 my $prev_values = 'E';
2030 my %suppress_ifbraces;
2031 my %suppress_whiletrailers;
2032 my %suppress_export;
2033 my $suppress_statement = 0;
2035 my %signatures = ();
2037 # Pre-scan the patch sanitizing the lines.
2038 # Pre-scan the patch looking for any __setup documentation.
2040 my @setup_docs = ();
2043 my $camelcase_file_seeded = 0;
2044 my $shorttext = BEFORE_SHORTTEXT;
2045 my $shorttext_exspc = 0;
2046 my $commit_text_present = 0;
2048 sanitise_line_reset();
2049 cleanup_continuation_headers();
2052 foreach my $rawline (@rawlines) {
2056 push(@fixed, $rawline) if ($fix);
2058 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2060 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
2065 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2074 # Guestimate if this is a continuing comment. Run
2075 # the context looking for a comment "edge". If this
2076 # edge is a close comment then we must be in a comment
2080 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2081 next if (defined $rawlines[$ln - 1] &&
2082 $rawlines[$ln - 1] =~ /^-/);
2084 #print "RAW<$rawlines[$ln - 1]>\n";
2085 last if (!defined $rawlines[$ln - 1]);
2086 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2087 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2092 if (defined $edge && $edge eq '*/') {
2096 # Guestimate if this is a continuing comment. If this
2097 # is the start of a diff block and this line starts
2098 # ' *' then it is very likely a comment.
2099 if (!defined $edge &&
2100 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2105 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2106 sanitise_line_reset($in_comment);
2108 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2109 # Standardise the strings and chars within the input to
2110 # simplify matching -- only bother with positive lines.
2111 $line = sanitise_line($rawline);
2113 push(@lines, $line);
2116 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2121 #print "==>$rawline\n";
2122 #print "-->$line\n";
2124 if ($setup_docs && $line =~ /^\+/) {
2125 push(@setup_docs, $line);
2134 foreach my $line (@lines) {
2137 my $sline = $line; #copy of $line
2138 $sline =~ s/$;/ /g; #with comments as spaces
2140 my $rawline = $rawlines[$linenr - 1];
2142 #extract the line range in the file after the patch is applied
2143 if (!$in_commit_log &&
2144 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2146 $first_line = $linenr + 1;
2156 %suppress_ifbraces = ();
2157 %suppress_whiletrailers = ();
2158 %suppress_export = ();
2159 $suppress_statement = 0;
2162 # track the line number as we move through the hunk, note that
2163 # new versions of GNU diff omit the leading space on completely
2164 # blank context lines so we need to count that too.
2165 } elsif ($line =~ /^( |\+|$)/) {
2167 $realcnt-- if ($realcnt != 0);
2169 # Measure the line length and indent.
2170 ($length, $indent) = line_stats($rawline);
2172 # Track the previous line.
2173 ($prevline, $stashline) = ($stashline, $line);
2174 ($previndent, $stashindent) = ($stashindent, $indent);
2175 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2177 #warn "line<$line>\n";
2179 } elsif ($realcnt == 1) {
2183 my $hunk_line = ($realcnt != 0);
2185 $here = "#$linenr: " if (!$file);
2186 $here = "#$realline: " if ($file);
2189 # extract the filename as it passes
2190 if ($line =~ /^diff --git.*?(\S+)$/) {
2192 $realfile =~ s@^([^/]*)/@@ if (!$file);
2195 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2197 $realfile =~ s@^([^/]*)/@@ if (!$file);
2201 if (!$file && $tree && $p1_prefix ne '' &&
2202 -e "$root/$p1_prefix") {
2203 WARN("PATCH_PREFIX",
2204 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2207 if ($realfile =~ m@^include/asm/@) {
2208 ERROR("MODIFIED_INCLUDE_ASM",
2209 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2214 #make up the handle for any error we report on this line
2216 $prefix = "$realfile:$realline: "
2219 $prefix = "$filename:$realline: ";
2221 $prefix = "$filename:$linenr: ";
2226 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2229 $check = $check_orig;
2233 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2235 my $hereline = "$here\n$rawline\n";
2236 my $herecurr = "$here\n$rawline\n";
2237 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2239 if ($shorttext != AFTER_SHORTTEXT) {
2240 if ($shorttext == IN_SHORTTEXT_BLANKLINE && $line=~/\S/) {
2241 # the subject line was just processed,
2242 # a blank line must be next
2243 WARN("NONBLANK_AFTER_SUMMARY",
2244 "non-blank line after summary line\n" . $herecurr);
2245 $shorttext = IN_SHORTTEXT;
2246 # this non-blank line may or may not be commit text -
2247 # a warning has been generated so assume it is commit
2249 $commit_text_present = 1;
2250 # fall through and treat this line as IN_SHORTTEXT
2252 if ($shorttext == IN_SHORTTEXT) {
2253 if ($line=~/^---/ || $line=~/^diff.*/) {
2254 if ($commit_text_present == 0) {
2255 WARN("NO_COMMIT_TEXT",
2256 "please add commit text explaining " .
2257 "*why* the change is needed\n" .
2260 $shorttext = AFTER_SHORTTEXT;
2261 } elsif (length($line) > (SHORTTEXT_LIMIT +
2263 && $line !~ /^:([0-7]{6}\s){2}
2265 \s){2}\w+\s\w+/xms) {
2266 WARN("LONG_COMMIT_TEXT",
2267 "commit text line over " .
2269 " characters\n" . $herecurr);
2270 } elsif ($line=~/^\s*change-id:/i ||
2271 $line=~/^\s*signed-off-by:/i ||
2272 $line=~/^\s*crs-fixed:/i ||
2273 $line=~/^\s*acked-by:/i) {
2274 # this is a tag, there must be commit
2276 if ($commit_text_present == 0) {
2277 WARN("NO_COMMIT_TEXT",
2278 "please add commit text explaining " .
2279 "*why* the change is needed\n" .
2281 # prevent duplicate warnings
2282 $commit_text_present = 1;
2284 } elsif ($line=~/\S/) {
2285 $commit_text_present = 1;
2287 } elsif ($shorttext == IN_SHORTTEXT_BLANKLINE) {
2288 # case of non-blank line in this state handled above
2289 $shorttext = IN_SHORTTEXT;
2290 } elsif ($shorttext == CHECK_NEXT_SHORTTEXT) {
2291 # The Subject line doesn't have to be the last header in the patch.
2292 # Avoid moving to the IN_SHORTTEXT state until clear of all headers.
2293 # Per RFC5322, continuation lines must be folded, so any left-justified
2294 # text which looks like a header is definitely a header.
2295 if ($line!~/^[\x21-\x39\x3b-\x7e]+:/) {
2296 $shorttext = IN_SHORTTEXT;
2297 # Check for Subject line followed by a blank line.
2298 if (length($line) != 0) {
2299 WARN("NONBLANK_AFTER_SUMMARY",
2300 "non-blank line after " .
2302 $sublinenr . $here .
2303 "\n" . $subjectline .
2304 "\n" . $line . "\n");
2305 # this non-blank line may or may not
2306 # be commit text - a warning has been
2307 # generated so assume it is commit
2309 $commit_text_present = 1;
2312 # The next two cases are BEFORE_SHORTTEXT.
2313 } elsif ($line=~/^Subject: \[[^\]]*\] (.*)/) {
2314 # This is the subject line. Go to
2315 # CHECK_NEXT_SHORTTEXT to wait for the commit
2317 $shorttext = CHECK_NEXT_SHORTTEXT;
2318 $subjectline = $line;
2319 $sublinenr = "#$linenr & ";
2320 # Check for Subject line less than line limit
2321 if (length($1) > SHORTTEXT_LIMIT && !($1 =~ m/Revert\ \"/)) {
2322 WARN("LONG_SUMMARY_LINE",
2323 "summary line over " .
2325 " characters\n" . $herecurr);
2327 } elsif ($line=~/^ (.*)/) {
2328 # Indented format, this must be the summary
2329 # line (i.e. git show). There will be no more
2330 # headers so we are now in the shorttext.
2331 $shorttext = IN_SHORTTEXT_BLANKLINE;
2332 $shorttext_exspc = 4;
2333 if (length($1) > SHORTTEXT_LIMIT && !($1 =~ m/Revert\ \"/)) {
2334 WARN("LONG_SUMMARY_LINE",
2335 "summary line over " .
2337 " characters\n" . $herecurr);
2342 $cnt_lines++ if ($realcnt != 0);
2344 # Check if the commit log has what seems like a diff which can confuse patch
2345 if ($in_commit_log && !$commit_log_has_diff &&
2346 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2347 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2348 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2349 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2350 ERROR("DIFF_IN_COMMIT_MSG",
2351 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2352 $commit_log_has_diff = 1;
2355 # Check for incorrect file permissions
2356 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2357 my $permhere = $here . "FILE: $realfile\n";
2358 if ($realfile !~ m@scripts/@ &&
2359 $realfile !~ /\.(py|pl|awk|sh)$/) {
2360 ERROR("EXECUTE_PERMISSIONS",
2361 "do not set execute permissions for source files\n" . $permhere);
2365 # Check the patch for a signoff:
2366 if ($line =~ /^\s*signed-off-by:/i) {
2371 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2372 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2373 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2374 $reported_maintainer_file = 1;
2377 # Check signature styles
2378 if (!$in_header_lines &&
2379 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2380 my $space_before = $1;
2382 my $space_after = $3;
2384 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2386 if ($sign_off !~ /$signature_tags/) {
2387 WARN("BAD_SIGN_OFF",
2388 "Non-standard signature: $sign_off\n" . $herecurr);
2390 if (defined $space_before && $space_before ne "") {
2391 if (WARN("BAD_SIGN_OFF",
2392 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2394 $fixed[$fixlinenr] =
2395 "$ucfirst_sign_off $email";
2398 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2399 if (WARN("BAD_SIGN_OFF",
2400 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2402 $fixed[$fixlinenr] =
2403 "$ucfirst_sign_off $email";
2407 if (!defined $space_after || $space_after ne " ") {
2408 if (WARN("BAD_SIGN_OFF",
2409 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2411 $fixed[$fixlinenr] =
2412 "$ucfirst_sign_off $email";
2416 my ($email_name, $email_address, $comment) = parse_email($email);
2417 my $suggested_email = format_email(($email_name, $email_address));
2418 if ($suggested_email eq "") {
2419 ERROR("BAD_SIGN_OFF",
2420 "Unrecognized email address: '$email'\n" . $herecurr);
2422 my $dequoted = $suggested_email;
2423 $dequoted =~ s/^"//;
2424 $dequoted =~ s/" </ </;
2425 # Don't force email to have quotes
2426 # Allow just an angle bracketed address
2427 if ("$dequoted$comment" ne $email &&
2428 "<$email_address>$comment" ne $email &&
2429 "$suggested_email$comment" ne $email) {
2430 WARN("BAD_SIGN_OFF",
2431 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2435 if ($line =~ /^\s*signed-off-by:.*qca\.qualcomm\.com/i) {
2437 } elsif ($line =~ /^\s*signed-off-by:.*codeaurora\.org/i) {
2438 $codeaurora_sign_off = 1;
2439 } elsif ($line =~ /^\s*signed-off-by:.*(quicinc|qualcomm)\.com/i) {
2440 WARN("BAD_SIGN_OFF",
2441 "invalid Signed-off-by identity\n" . $line );
2445 # Check for duplicate signatures
2446 my $sig_nospace = $line;
2447 $sig_nospace =~ s/\s//g;
2448 $sig_nospace = lc($sig_nospace);
2449 if (defined $signatures{$sig_nospace}) {
2450 WARN("BAD_SIGN_OFF",
2451 "Duplicate signature\n" . $herecurr);
2453 $signatures{$sig_nospace} = 1;
2457 # Check email subject for common tools that don't need to be mentioned
2458 if ($in_header_lines &&
2459 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2460 WARN("EMAIL_SUBJECT",
2461 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2464 # Check for old stable address
2465 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2466 ERROR("STABLE_ADDRESS",
2467 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2470 # Check if the commit log is in a possible stack dump
2471 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2472 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2473 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2475 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2476 # stack dump address
2477 $commit_log_possible_stack_dump = 1;
2480 # Check for line lengths > 75 in commit log, warn once
2481 if ($in_commit_log && !$commit_log_long_line &&
2482 length($line) > 75 &&
2483 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2484 # file delta changes
2485 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2487 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2488 # A Fixes: or Link: line
2489 $commit_log_possible_stack_dump)) {
2490 WARN("COMMIT_LOG_LONG_LINE",
2491 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2492 $commit_log_long_line = 1;
2495 # Reset possible stack dump if a blank line is found
2496 if ($in_commit_log && $commit_log_possible_stack_dump &&
2498 $commit_log_possible_stack_dump = 0;
2501 # Check for git id commit length and improperly formed commit descriptions
2502 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2503 $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2504 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2505 ($line =~ /\b[0-9a-f]{12,40}\b/i &&
2506 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2507 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2508 my $init_char = "c";
2509 my $orig_commit = "";
2516 my $id = '0123456789ab';
2517 my $orig_desc = "commit description";
2518 my $description = "";
2520 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2522 $orig_commit = lc($2);
2523 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2524 $orig_commit = lc($1);
2527 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2528 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2529 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2530 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2531 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2534 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2535 defined $rawlines[$linenr] &&
2536 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2539 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2540 defined $rawlines[$linenr] &&
2541 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2542 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2544 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2545 $orig_desc .= " " . $1;
2549 ($id, $description) = git_commit_info($orig_commit,
2552 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2553 ERROR("GIT_COMMIT_ID",
2554 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2558 # Check for added, moved or deleted files
2559 if (!$reported_maintainer_file && !$in_commit_log &&
2560 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2561 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2562 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2563 (defined($1) || defined($2))))) {
2564 $reported_maintainer_file = 1;
2565 WARN("FILE_PATH_CHANGES",
2566 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2569 #check the patch for invalid author credentials
2570 if ($chk_author && !($line =~ /^From:.*qca\.qualcomm\.com/) &&
2571 $line =~ /^From:.*(quicinc|qualcomm)\.com/) {
2572 WARN("BAD_AUTHOR", "invalid author identity\n" . $line );
2575 # Check for wrappage within a valid hunk of the file
2576 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2577 ERROR("CORRUPTED_PATCH",
2578 "patch seems to be corrupt (line wrapped?)\n" .
2579 $herecurr) if (!$emitted_corrupt++);
2582 # Check for absolute kernel paths.
2584 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2587 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2588 check_absolute_file($1, $herecurr)) {
2591 check_absolute_file($file, $herecurr);
2596 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2597 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2598 $rawline !~ m/^$UTF8*$/) {
2599 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2601 my $blank = copy_spacing($rawline);
2602 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2603 my $hereptr = "$hereline$ptr\n";
2606 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2609 # Check if it's the start of a commit log
2610 # (not a header line and we haven't seen the patch filename)
2611 if ($in_header_lines && $realfile =~ /^$/ &&
2612 !($rawline =~ /^\s+\S/ ||
2613 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2614 $in_header_lines = 0;
2618 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2619 # declined it, i.e defined some charset where it is missing.
2620 if ($in_header_lines &&
2621 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2623 $non_utf8_charset = 1;
2626 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2627 $rawline =~ /$NON_ASCII_UTF8/) {
2628 WARN("UTF8_BEFORE_PATCH",
2629 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2632 # Check for various typo / spelling mistakes
2633 if (defined($misspellings) &&
2634 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2635 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2637 my $typo_fix = $spelling_fix{lc($typo)};
2638 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2639 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2640 my $msg_type = \&WARN;
2641 $msg_type = \&CHK if ($file);
2642 if (&{$msg_type}("TYPO_SPELLING",
2643 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2645 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2650 # ignore non-hunk lines and lines being removed
2651 next if (!$hunk_line || $line =~ /^-/);
2653 #trailing whitespace
2654 if ($line =~ /^\+.*\015/) {
2655 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2656 if (ERROR("DOS_LINE_ENDINGS",
2657 "DOS line endings\n" . $herevet) &&
2659 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2661 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2662 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2663 if (ERROR("TRAILING_WHITESPACE",
2664 "trailing whitespace\n" . $herevet) &&
2666 $fixed[$fixlinenr] =~ s/\s+$//;
2672 # Check for FSF mailing addresses.
2673 if ($rawline =~ /\bwrite to the Free/i ||
2674 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2675 $rawline =~ /\b51\s+Franklin\s+St/i) {
2676 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2677 my $msg_type = \&ERROR;
2678 $msg_type = \&CHK if ($file);
2679 &{$msg_type}("FSF_MAILING_ADDRESS",
2680 "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)
2683 # check for Kconfig help text having a real description
2684 # Only applies when adding the entry originally, after that we do not have
2685 # sufficient context to determine whether it is indeed long enough.
2686 if ($realfile =~ /Kconfig/ &&
2687 $line =~ /^\+\s*config\s+/) {
2690 my $ln = $linenr + 1;
2694 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2695 $f = $lines[$ln - 1];
2696 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2697 $is_end = $lines[$ln - 1] =~ /^\+/;
2699 next if ($f =~ /^-/);
2700 last if (!$file && $f =~ /^\@\@/);
2702 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2704 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2711 next if ($f =~ /^$/);
2712 if ($f =~ /^\s*config\s/) {
2718 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2719 WARN("CONFIG_DESCRIPTION",
2720 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2722 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2725 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2726 if ($realfile =~ /Kconfig/ &&
2727 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2728 WARN("CONFIG_EXPERIMENTAL",
2729 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2732 # discourage the use of boolean for type definition attributes of Kconfig options
2733 if ($realfile =~ /Kconfig/ &&
2734 $line =~ /^\+\s*\bboolean\b/) {
2735 WARN("CONFIG_TYPE_BOOLEAN",
2736 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2739 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2740 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2743 'EXTRA_AFLAGS' => 'asflags-y',
2744 'EXTRA_CFLAGS' => 'ccflags-y',
2745 'EXTRA_CPPFLAGS' => 'cppflags-y',
2746 'EXTRA_LDFLAGS' => 'ldflags-y',
2749 WARN("DEPRECATED_VARIABLE",
2750 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2753 # check for DT compatible documentation
2754 if (defined $root &&
2755 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2756 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2758 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2760 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2761 my $vp_file = $dt_path . "vendor-prefixes.txt";
2763 foreach my $compat (@compats) {
2764 my $compat2 = $compat;
2765 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2766 my $compat3 = $compat;
2767 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2768 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2770 WARN("UNDOCUMENTED_DT_STRING",
2771 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2774 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2776 `grep -Eq "^$vendor\\b" $vp_file`;
2778 WARN("UNDOCUMENTED_DT_STRING",
2779 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2784 # check we are in a valid source file if not then ignore this hunk
2785 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2787 # line length limit (with some exclusions)
2789 # There are a few types of lines that may extend beyond $max_line_length:
2790 # logging functions like pr_info that end in a string
2791 # lines with a single string
2792 # #defines that are a single string
2794 # There are 3 different line length message types:
2795 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_linelength
2796 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
2797 # LONG_LINE all other lines longer than $max_line_length
2799 # if LONG_LINE is ignored, the other 2 types are also ignored
2801 if ($line =~ /^\+/ && $length > $max_line_length && $realfile ne "scripts/checkpatch.pl") {
2802 my $msg_type = "LONG_LINE";
2804 # Check the allowed long line types first
2806 # logging functions that end in a string that starts
2807 # before $max_line_length
2808 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2809 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2812 # lines with only strings (w/ possible termination)
2813 # #defines with only strings
2814 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2815 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
2818 # Otherwise set the alternate message types
2820 # a comment starts before $max_line_length
2821 } elsif ($line =~ /($;[\s$;]*)$/ &&
2822 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2823 $msg_type = "LONG_LINE_COMMENT"
2825 # a quoted string starts before $max_line_length
2826 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
2827 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2828 $msg_type = "LONG_LINE_STRING"
2831 if ($msg_type ne "" &&
2832 (show_type("LONG_LINE") || show_type($msg_type))) {
2834 "line over $max_line_length characters\n" . $herecurr);
2838 # check for adding lines without a newline.
2839 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2840 WARN("MISSING_EOF_NEWLINE",
2841 "adding a line without newline at end of file\n" . $herecurr);
2844 # Blackfin: use hi/lo macros
2845 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2846 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2847 my $herevet = "$here\n" . cat_vet($line) . "\n";
2849 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2851 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2852 my $herevet = "$here\n" . cat_vet($line) . "\n";
2854 "use the HI() macro, not (... >> 16)\n" . $herevet);
2858 # check we are in a valid source file C or perl if not then ignore this hunk
2859 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2861 # at the beginning of a line any tabs must come first and anything
2862 # more than 8 must use tabs.
2863 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2864 $rawline =~ /^\+\s* \s*/) {
2865 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2867 if (ERROR("CODE_INDENT",
2868 "code indent should use tabs where possible\n" . $herevet) &&
2870 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2874 # check for space before tabs.
2875 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2876 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2877 if (WARN("SPACE_BEFORE_TAB",
2878 "please, no space before tabs\n" . $herevet) &&
2880 while ($fixed[$fixlinenr] =~
2881 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2882 while ($fixed[$fixlinenr] =~
2883 s/(^\+.*) +\t/$1\t/) {}
2887 # check for && or || at the start of a line
2888 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2889 CHK("LOGICAL_CONTINUATIONS",
2890 "Logical continuations should be on the previous line\n" . $hereprev);
2893 # check multi-line statement indentation matches previous line
2894 if ($^V && $^V ge 5.10.0 &&
2895 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2896 $prevline =~ /^\+(\t*)(.*)$/;
2900 my $pos = pos_last_openparen($rest);
2902 $line =~ /^(\+| )([ \t]*)/;
2905 my $goodtabindent = $oldindent .
2908 my $goodspaceindent = $oldindent . " " x $pos;
2910 if ($newindent ne $goodtabindent &&
2911 $newindent ne $goodspaceindent) {
2913 if (CHK("PARENTHESIS_ALIGNMENT",
2914 "Alignment should match open parenthesis\n" . $hereprev) &&
2915 $fix && $line =~ /^\+/) {
2916 $fixed[$fixlinenr] =~
2917 s/^\+[ \t]*/\+$goodtabindent/;
2923 # check for space after cast like "(int) foo" or "(struct foo) bar"
2924 # avoid checking a few false positives:
2925 # "sizeof(<type>)" or "__alignof__(<type>)"
2926 # function pointer declarations like "(*foo)(int) = bar;"
2927 # structure definitions like "(struct foo) { 0 };"
2928 # multiline macros that define functions
2929 # known attributes or the __attribute__ keyword
2930 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2931 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
2933 "No space is necessary after a cast\n" . $herecurr) &&
2935 $fixed[$fixlinenr] =~
2936 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2940 # Block comment styles
2941 # Networking with an initial /*
2942 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2943 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2944 $rawline =~ /^\+[ \t]*\*/ &&
2946 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2947 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2950 # Block comments use * on subsequent lines
2951 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2952 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
2953 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2954 $rawline =~ /^\+/ && #line is new
2955 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2956 WARN("BLOCK_COMMENT_STYLE",
2957 "Block comments use * on subsequent lines\n" . $hereprev);
2960 # Block comments use */ on trailing lines
2961 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2962 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2963 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2964 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2965 WARN("BLOCK_COMMENT_STYLE",
2966 "Block comments use a trailing */ on a separate line\n" . $herecurr);
2969 # check for missing blank lines after struct/union declarations
2970 # with exceptions for various attributes and macros
2971 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2973 !($line =~ /^\+\s*$/ ||
2974 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2975 $line =~ /^\+\s*MODULE_/i ||
2976 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2977 $line =~ /^\+[a-z_]*init/ ||
2978 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2979 $line =~ /^\+\s*DECLARE/ ||
2980 $line =~ /^\+\s*__setup/)) {
2981 if (CHK("LINE_SPACING",
2982 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2984 fix_insert_line($fixlinenr, "\+");
2988 # check for multiple consecutive blank lines
2989 if ($prevline =~ /^[\+ ]\s*$/ &&
2990 $line =~ /^\+\s*$/ &&
2991 $last_blank_line != ($linenr - 1)) {
2992 if (CHK("LINE_SPACING",
2993 "Please don't use multiple blank lines\n" . $hereprev) &&
2995 fix_delete_line($fixlinenr, $rawline);
2998 $last_blank_line = $linenr;
3001 # check for missing blank lines after declarations
3002 if ($sline =~ /^\+\s+\S/ && #Not at char 1
3003 # actual declarations
3004 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3005 # function pointer declarations
3006 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3007 # foo bar; where foo is some local typedef or #define
3008 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3009 # known declaration macros
3010 $prevline =~ /^\+\s+$declaration_macros/) &&
3011 # for "else if" which can look like "$Ident $Ident"
3012 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3013 # other possible extensions of declaration lines
3014 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3015 # not starting a section or a macro "\" extended line
3016 $prevline =~ /(?:\{\s*|\\)$/) &&
3017 # looks like a declaration
3018 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3019 # function pointer declarations
3020 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3021 # foo bar; where foo is some local typedef or #define
3022 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3023 # known declaration macros
3024 $sline =~ /^\+\s+$declaration_macros/ ||
3025 # start of struct or union or enum
3026 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3027 # start or end of block or continuation of declaration
3028 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3029 # bitfield continuation
3030 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3031 # other possible extensions of declaration lines
3032 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3033 # indentation of previous and current line are the same
3034 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3035 if (WARN("LINE_SPACING",
3036 "Missing a blank line after declarations\n" . $hereprev) &&
3038 fix_insert_line($fixlinenr, "\+");
3042 # check for spaces at the beginning of a line.
3044 # 1) within comments
3045 # 2) indented preprocessor commands
3047 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
3048 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3049 if (WARN("LEADING_SPACE",
3050 "please, no spaces at the start of a line\n" . $herevet) &&
3052 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3056 # check we are in a valid C source file if not then ignore this hunk
3057 next if ($realfile !~ /\.(h|c)$/);
3059 # check indentation of any line with a bare else
3060 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3061 # if the previous line is a break or return and is indented 1 tab more...
3062 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3063 my $tabs = length($1) + 1;
3064 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3065 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3066 defined $lines[$linenr] &&
3067 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3068 WARN("UNNECESSARY_ELSE",
3069 "else is not generally useful after a break or return\n" . $hereprev);
3073 # check indentation of a line with a break;
3074 # if the previous line is a goto or return and is indented the same # of tabs
3075 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3077 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3078 WARN("UNNECESSARY_BREAK",
3079 "break is not useful after a goto or return\n" . $hereprev);
3083 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
3084 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
3085 WARN("CONFIG_EXPERIMENTAL",
3086 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
3089 # check for RCS/CVS revision markers
3090 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3092 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3095 # Blackfin: don't use __builtin_bfin_[cs]sync
3096 if ($line =~ /__builtin_bfin_csync/) {
3097 my $herevet = "$here\n" . cat_vet($line) . "\n";
3099 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
3101 if ($line =~ /__builtin_bfin_ssync/) {
3102 my $herevet = "$here\n" . cat_vet($line) . "\n";
3104 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
3107 # check for old HOTPLUG __dev<foo> section markings
3108 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3109 WARN("HOTPLUG_SECTION",
3110 "Using $1 is unnecessary\n" . $herecurr);
3113 # Check for potential 'bare' types
3114 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3116 #print "LINE<$line>\n";
3117 if ($linenr >= $suppress_statement &&
3118 $realcnt && $sline =~ /.\s*\S/) {
3119 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3120 ctx_statement_block($linenr, $realcnt, 0);
3121 $stat =~ s/\n./\n /g;
3122 $cond =~ s/\n./\n /g;
3124 #print "linenr<$linenr> <$stat>\n";
3125 # If this statement has no statement boundaries within
3126 # it there is no point in retrying a statement scan
3127 # until we hit end of it.
3128 my $frag = $stat; $frag =~ s/;+\s*$//;
3129 if ($frag !~ /(?:{|;)/) {
3130 #print "skip<$line_nr_next>\n";
3131 $suppress_statement = $line_nr_next;
3134 # Find the real next line.
3135 $realline_next = $line_nr_next;
3136 if (defined $realline_next &&
3137 (!defined $lines[$realline_next - 1] ||
3138 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3145 # Ignore goto labels.
3146 if ($s =~ /$Ident:\*$/s) {
3148 # Ignore functions being called
3149 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3151 } elsif ($s =~ /^.\s*else\b/s) {
3153 # declarations always start with types
3154 } 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) {
3157 possible($type, "A:" . $s);
3159 # definitions in global scope can only start with types
3160 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3161 possible($1, "B:" . $s);
3164 # any (foo ... *) is a pointer cast, and foo is a type
3165 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3166 possible($1, "C:" . $s);
3169 # Check for any sort of function declaration.
3170 # int foo(something bar, other baz);
3171 # void (*store_gdt)(x86_descr_ptr *);
3172 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3173 my ($name_len) = length($1);
3176 substr($ctx, 0, $name_len + 1, '');
3177 $ctx =~ s/\)[^\)]*$//;
3179 for my $arg (split(/\s*,\s*/, $ctx)) {
3180 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3182 possible($1, "D:" . $s);
3190 # Checks which may be anchored in the context.
3193 # Check for switch () and associated case and default
3194 # statements should be at the same indent.
3195 if ($line=~/\bswitch\s*\(.*\)/) {
3198 my @ctx = ctx_block_outer($linenr, $realcnt);
3200 for my $ctx (@ctx) {
3201 my ($clen, $cindent) = line_stats($ctx);
3202 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3203 $indent != $cindent) {
3204 $err .= "$sep$ctx\n";
3211 ERROR("SWITCH_CASE_INDENT_LEVEL",
3212 "switch and case should be at the same indent\n$hereline$err");
3216 # if/while/etc brace do not go on next line, unless defining a do while loop,
3217 # or if that brace on the next line is for something else
3218 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3219 my $pre_ctx = "$1$2";
3221 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3223 if ($line =~ /^\+\t{6,}/) {
3224 WARN("DEEP_INDENTATION",
3225 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3228 my $ctx_cnt = $realcnt - $#ctx - 1;
3229 my $ctx = join("\n", @ctx);
3231 my $ctx_ln = $linenr;
3232 my $ctx_skip = $realcnt;
3234 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3235 defined $lines[$ctx_ln - 1] &&
3236 $lines[$ctx_ln - 1] =~ /^-/)) {
3237 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3238 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3242 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3243 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3245 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3247 "that open brace { should be on the previous line\n" .
3248 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3250 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3251 $ctx =~ /\)\s*\;\s*$/ &&
3252 defined $lines[$ctx_ln - 1])
3254 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3255 if ($nindent > $indent) {
3256 WARN("TRAILING_SEMICOLON",
3257 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3258 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3263 # Check relative indent for conditionals and blocks.
3264 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3265 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3266 ctx_statement_block($linenr, $realcnt, 0)
3267 if (!defined $stat);
3268 my ($s, $c) = ($stat, $cond);
3270 substr($s, 0, length($c), '');
3272 # remove inline comments
3276 # Find out how long the conditional actually is.
3277 my @newlines = ($c =~ /\n/gs);
3278 my $cond_lines = 1 + $#newlines;
3280 # Make sure we remove the line prefixes as we have
3281 # none on the first line, and are going to readd them
3284 while ($s =~ /\n\s+\\\n/) {
3285 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3288 # We want to check the first line inside the block
3289 # starting at the end of the conditional, so remove:
3290 # 1) any blank line termination
3291 # 2) any opening brace { on end of the line
3293 my $continuation = 0;
3295 $s =~ s/^.*\bdo\b//;
3297 if ($s =~ s/^\s*\\//) {
3300 if ($s =~ s/^\s*?\n//) {
3305 # Also ignore a loop construct at the end of a
3306 # preprocessor statement.
3307 if (($prevline =~ /^.\s*#\s*define\s/ ||
3308 $prevline =~ /\\\s*$/) && $continuation == 0) {
3314 while ($cond_ptr != $cond_lines) {
3315 $cond_ptr = $cond_lines;
3317 # If we see an #else/#elif then the code
3319 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3324 # 1) blank lines, they should be at 0,
3325 # 2) preprocessor lines, and
3327 if ($continuation ||
3329 $s =~ /^\s*#\s*?/ ||
3330 $s =~ /^\s*$Ident\s*:/) {
3331 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3332 if ($s =~ s/^.*?\n//) {
3338 my (undef, $sindent) = line_stats("+" . $s);
3339 my $stat_real = raw_line($linenr, $cond_lines);
3341 # Check if either of these lines are modified, else
3342 # this is not this patch's fault.
3343 if (!defined($stat_real) ||
3344 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3347 if (defined($stat_real) && $cond_lines > 1) {
3348 $stat_real = "[...]\n$stat_real";
3351 #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";
3353 if ($check && $s ne '' &&
3354 (($sindent % 8) != 0 ||
3355 ($sindent < $indent) ||
3356 ($sindent > $indent + 8))) {
3357 WARN("SUSPECT_CODE_INDENT",
3358 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3362 # Track the 'values' across context and added lines.
3363 my $opline = $line; $opline =~ s/^./ /;
3364 my ($curr_values, $curr_vars) =
3365 annotate_values($opline . "\n", $prev_values);
3366 $curr_values = $prev_values . $curr_values;
3368 my $outline = $opline; $outline =~ s/\t/ /g;
3369 print "$linenr > .$outline\n";
3370 print "$linenr > $curr_values\n";
3371 print "$linenr > $curr_vars\n";
3373 $prev_values = substr($curr_values, -1);
3375 #ignore lines not being added
3376 next if ($line =~ /^[^\+]/);
3378 # TEST: allow direct testing of the type matcher.
3380 if ($line =~ /^.\s*$Declare\s*$/) {
3382 "TEST: is type\n" . $herecurr);
3383 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3384 ERROR("TEST_NOT_TYPE",
3385 "TEST: is not type ($1 is)\n". $herecurr);
3389 # TEST: allow direct testing of the attribute matcher.
3391 if ($line =~ /^.\s*$Modifier\s*$/) {
3393 "TEST: is attr\n" . $herecurr);
3394 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3395 ERROR("TEST_NOT_ATTR",
3396 "TEST: is not attr ($1 is)\n". $herecurr);
3401 # check for initialisation to aggregates open brace on the next line
3402 if ($line =~ /^.\s*{/ &&
3403 $prevline =~ /(?:^|[^=])=\s*$/) {
3404 if (ERROR("OPEN_BRACE",
3405 "that open brace { should be on the previous line\n" . $hereprev) &&
3406 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3407 fix_delete_line($fixlinenr - 1, $prevrawline);
3408 fix_delete_line($fixlinenr, $rawline);
3409 my $fixedline = $prevrawline;
3410 $fixedline =~ s/\s*=\s*$/ = {/;
3411 fix_insert_line($fixlinenr, $fixedline);
3413 $fixedline =~ s/^(.\s*)\{\s*/$1/;
3414 fix_insert_line($fixlinenr, $fixedline);
3419 # Checks which are anchored on the added line.
3422 # check for malformed paths in #include statements (uses RAW line)
3423 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3425 if ($path =~ m{//}) {
3426 ERROR("MALFORMED_INCLUDE",
3427 "malformed #include filename\n" . $herecurr);
3429 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3430 ERROR("UAPI_INCLUDE",
3431 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3435 # no C99 // comments
3436 if ($line =~ m{//}) {
3437 if (ERROR("C99_COMMENTS",
3438 "do not use C99 // comments\n" . $herecurr) &&
3440 my $line = $fixed[$fixlinenr];
3441 if ($line =~ /\/\/(.*)$/) {
3442 my $comment = trim($1);
3443 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3447 # Remove C99 comments.
3449 $opline =~ s@//.*@@;
3451 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3452 # the whole statement.
3453 #print "APW <$lines[$realline_next - 1]>\n";
3454 if (defined $realline_next &&
3455 exists $lines[$realline_next - 1] &&
3456 !defined $suppress_export{$realline_next} &&
3457 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3458 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3459 # Handle definitions which produce identifiers with
3462 # EXPORT_SYMBOL(something_foo);
3464 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3465 $name =~ /^${Ident}_$2/) {
3466 #print "FOO C name<$name>\n";
3467 $suppress_export{$realline_next} = 1;
3469 } elsif ($stat !~ /(?:
3471 ^.DEFINE_$Ident\(\Q$name\E\)|
3472 ^.DECLARE_$Ident\(\Q$name\E\)|
3473 ^.LIST_HEAD\(\Q$name\E\)|
3474 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3475 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3477 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3478 $suppress_export{$realline_next} = 2;
3480 $suppress_export{$realline_next} = 1;
3483 if (!defined $suppress_export{$linenr} &&
3484 $prevline =~ /^.\s*$/ &&
3485 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3486 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3487 #print "FOO B <$lines[$linenr - 1]>\n";
3488 $suppress_export{$linenr} = 2;
3490 if (defined $suppress_export{$linenr} &&
3491 $suppress_export{$linenr} == 2) {
3492 WARN("EXPORT_SYMBOL",
3493 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3496 # check for global initialisers.
3497 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3498 if (ERROR("GLOBAL_INITIALISERS",
3499 "do not initialise globals to $1\n" . $herecurr) &&
3501 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3504 # check for static initialisers.
3505 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3506 if (ERROR("INITIALISED_STATIC",
3507 "do not initialise statics to $1\n" .
3510 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3514 # check for misordered declarations of char/short/int/long with signed/unsigned
3515 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3517 WARN("MISORDERED_TYPE",
3518 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3521 # check for static const char * arrays.
3522 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3523 WARN("STATIC_CONST_CHAR_ARRAY",
3524 "static const char * array should probably be static const char * const\n" .
3528 # check for static char foo[] = "bar" declarations.
3529 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3530 WARN("STATIC_CONST_CHAR_ARRAY",
3531 "static char array declaration should probably be static const char\n" .
3535 # check for const <foo> const where <foo> is not a pointer or array type
3536 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3538 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3540 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3541 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3543 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3547 # check for non-global char *foo[] = {"bar", ...} declarations.
3548 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3549 WARN("STATIC_CONST_CHAR_ARRAY",
3550 "char * array declaration might be better as static const\n" .
3554 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3555 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3557 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3559 if (WARN("ARRAY_SIZE",
3560 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3562 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3567 # check for function declarations without arguments like "int foo()"
3568 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3569 if (ERROR("FUNCTION_WITHOUT_ARGS",
3570 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3572 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3576 # check for uses of DEFINE_PCI_DEVICE_TABLE
3577 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3578 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3579 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3581 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3585 # check for new typedefs, only function parameters and sparse annotations
3587 if ($line =~ /\btypedef\s/ &&
3588 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3589 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3590 $line !~ /\b$typeTypedefs\b/ &&
3591 $line !~ /\b__bitwise(?:__|)\b/) {
3592 WARN("NEW_TYPEDEFS",
3593 "do not add new typedefs\n" . $herecurr);
3596 # * goes on variable not on type
3598 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3600 my ($ident, $from, $to) = ($1, $2, $2);
3602 # Should start with a space.
3603 $to =~ s/^(\S)/ $1/;
3604 # Should not end with a space.
3606 # '*'s should not have spaces between.
3607 while ($to =~ s/\*\s+\*/\*\*/) {
3610 ## print "1: from<$from> to<$to> ident<$ident>\n";
3612 if (ERROR("POINTER_LOCATION",
3613 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3615 my $sub_from = $ident;
3616 my $sub_to = $ident;
3617 $sub_to =~ s/\Q$from\E/$to/;
3618 $fixed[$fixlinenr] =~
3619 s@\Q$sub_from\E@$sub_to@;
3623 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3625 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3627 # Should start with a space.
3628 $to =~ s/^(\S)/ $1/;
3629 # Should not end with a space.
3631 # '*'s should not have spaces between.
3632 while ($to =~ s/\*\s+\*/\*\*/) {
3634 # Modifiers should have spaces.
3635 $to =~ s/(\b$Modifier$)/$1 /;
3637 ## print "2: from<$from> to<$to> ident<$ident>\n";
3638 if ($from ne $to && $ident !~ /^$Modifier$/) {
3639 if (ERROR("POINTER_LOCATION",
3640 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3643 my $sub_from = $match;
3644 my $sub_to = $match;
3645 $sub_to =~ s/\Q$from\E/$to/;
3646 $fixed[$fixlinenr] =~
3647 s@\Q$sub_from\E@$sub_to@;
3652 # avoid BUG() or BUG_ON()
3653 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3654 my $msg_type = \&WARN;
3655 $msg_type = \&CHK if ($file);
3656 &{$msg_type}("AVOID_BUG",
3657 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3660 # avoid LINUX_VERSION_CODE
3661 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3662 WARN("LINUX_VERSION_CODE",
3663 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3666 # check for uses of printk_ratelimit
3667 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3668 WARN("PRINTK_RATELIMITED",
3669 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3672 # printk should use KERN_* levels. Note that follow on printk's on the
3673 # same line do not need a level, so we use the current block context
3674 # to try and find and validate the current printk. In summary the current
3675 # printk includes all preceding printk's which have no newline on the end.
3676 # we assume the first bad printk is the one to report.
3677 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3679 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3680 #print "CHECK<$lines[$ln - 1]\n";
3681 # we have a preceding printk if it ends
3682 # with "\n" ignore it, else it is to blame
3683 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3684 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3691 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3692 "printk() should include KERN_ facility level\n" . $herecurr);
3696 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3698 my $level = lc($orig);
3699 $level = "warn" if ($level eq "warning");
3700 my $level2 = $level;
3701 $level2 = "dbg" if ($level eq "debug");
3702 WARN("PREFER_PR_LEVEL",
3703 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3706 if ($line =~ /\bpr_warning\s*\(/) {
3707 if (WARN("PREFER_PR_LEVEL",
3708 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3710 $fixed[$fixlinenr] =~
3711 s/\bpr_warning\b/pr_warn/;
3715 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3717 my $level = lc($orig);
3718 $level = "warn" if ($level eq "warning");
3719 $level = "dbg" if ($level eq "debug");
3720 WARN("PREFER_DEV_LEVEL",
3721 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3724 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
3725 # number of false positives, but assembly files are not checked, so at
3726 # least the arch entry code will not trigger this warning.
3727 if ($line =~ /\bENOSYS\b/) {
3729 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
3732 # function brace can't be on same line, except for #defines of do while,
3733 # or if closed on same line
3734 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3735 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
3736 if (ERROR("OPEN_BRACE",
3737 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3739 fix_delete_line($fixlinenr, $rawline);
3740 my $fixed_line = $rawline;
3741 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3744 fix_insert_line($fixlinenr, ltrim($line1));
3745 fix_insert_line($fixlinenr, "\+{");
3746 if ($line2 !~ /^\s*$/) {
3747 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3752 # open braces for enum, union and struct go on the same line.
3753 if ($line =~ /^.\s*{/ &&
3754 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3755 if (ERROR("OPEN_BRACE",
3756 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3757 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3758 fix_delete_line($fixlinenr - 1, $prevrawline);
3759 fix_delete_line($fixlinenr, $rawline);
3760 my $fixedline = rtrim($prevrawline) . " {";
3761 fix_insert_line($fixlinenr, $fixedline);
3762 $fixedline = $rawline;
3763 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
3764 if ($fixedline !~ /^\+\s*$/) {
3765 fix_insert_line($fixlinenr, $fixedline);
3770 # missing space after union, struct or enum definition
3771 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3773 "missing space after $1 definition\n" . $herecurr) &&
3775 $fixed[$fixlinenr] =~
3776 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3780 # Function pointer declarations
3781 # check spacing between type, funcptr, and args
3782 # canonical declaration is "type (*funcptr)(args...)"
3783 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3785 my $pre_pointer_space = $2;
3786 my $post_pointer_space = $3;
3788 my $post_funcname_space = $5;
3789 my $pre_args_space = $6;
3791 # the $Declare variable will capture all spaces after the type
3792 # so check it for a missing trailing missing space but pointer return types
3793 # don't need a space so don't warn for those.
3794 my $post_declare_space = "";
3795 if ($declare =~ /(\s+)$/) {
3796 $post_declare_space = $1;
3797 $declare = rtrim($declare);
3799 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3801 "missing space after return type\n" . $herecurr);
3802 $post_declare_space = " ";
3805 # unnecessary space "type (*funcptr)(args...)"
3806 # This test is not currently implemented because these declarations are
3808 # int foo(int bar, ...)
3809 # and this is form shouldn't/doesn't generate a checkpatch warning.
3811 # elsif ($declare =~ /\s{2,}$/) {
3813 # "Multiple spaces after return type\n" . $herecurr);
3816 # unnecessary space "type ( *funcptr)(args...)"
3817 if (defined $pre_pointer_space &&
3818 $pre_pointer_space =~ /^\s/) {
3820 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3823 # unnecessary space "type (* funcptr)(args...)"
3824 if (defined $post_pointer_space &&
3825 $post_pointer_space =~ /^\s/) {
3827 "Unnecessary space before function pointer name\n" . $herecurr);
3830 # unnecessary space "type (*funcptr )(args...)"
3831 if (defined $post_funcname_space &&
3832 $post_funcname_space =~ /^\s/) {
3834 "Unnecessary space after function pointer name\n" . $herecurr);
3837 # unnecessary space "type (*funcptr) (args...)"
3838 if (defined $pre_args_space &&
3839 $pre_args_space =~ /^\s/) {
3841 "Unnecessary space before function pointer arguments\n" . $herecurr);
3844 if (show_type("SPACING") && $fix) {
3845 $fixed[$fixlinenr] =~
3846 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3850 # check for spacing round square brackets; allowed:
3851 # 1. with a type on the left -- int [] a;
3852 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3853 # 3. inside a curly brace -- = { [0...10] = 5 }
3854 while ($line =~ /(.*?\s)\[/g) {
3855 my ($where, $prefix) = ($-[1], $1);
3856 if ($prefix !~ /$Type\s+$/ &&
3857 ($where != 0 || $prefix !~ /^.\s+$/) &&
3858 $prefix !~ /[{,]\s+$/) {
3859 if (ERROR("BRACKET_SPACE",
3860 "space prohibited before open square bracket '['\n" . $herecurr) &&
3862 $fixed[$fixlinenr] =~
3863 s/^(\+.*?)\s+\[/$1\[/;
3868 # check for spaces between functions and their parentheses.
3869 while ($line =~ /($Ident)\s+\(/g) {
3871 my $ctx_before = substr($line, 0, $-[1]);
3872 my $ctx = "$ctx_before$name";
3874 # Ignore those directives where spaces _are_ permitted.
3876 if|for|while|switch|return|case|
3877 volatile|__volatile__|
3878 __attribute__|format|__extension__|
3881 # cpp #define statements have non-optional spaces, ie
3882 # if there is a space between the name and the open
3883 # parenthesis it is simply not a parameter group.
3884 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3886 # cpp #elif statement condition may start with a (
3887 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3889 # If this whole things ends with a type its most
3890 # likely a typedef for a function.
3891 } elsif ($ctx =~ /$Type$/) {
3895 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3897 $fixed[$fixlinenr] =~
3898 s/\b$name\s+\(/$name\(/;
3903 # Check operator spacing.
3904 if (!($line=~/\#\s*include/)) {
3905 my $fixed_line = "";
3909 <<=|>>=|<=|>=|==|!=|
3910 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3911 =>|->|<<|>>|<|>|=|!|~|
3912 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3915 my @elements = split(/($ops|;)/, $opline);
3917 ## print("element count: <" . $#elements . ">\n");
3918 ## foreach my $el (@elements) {
3919 ## print("el: <$el>\n");
3922 my @fix_elements = ();
3925 foreach my $el (@elements) {
3926 push(@fix_elements, substr($rawline, $off, length($el)));
3927 $off += length($el);
3932 my $blank = copy_spacing($opline);
3933 my $last_after = -1;
3935 for (my $n = 0; $n < $#elements; $n += 2) {
3937 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3939 ## print("n: <$n> good: <$good>\n");
3941 $off += length($elements[$n]);
3943 # Pick up the preceding and succeeding characters.
3944 my $ca = substr($opline, 0, $off);
3946 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3947 $cc = substr($opline, $off + length($elements[$n + 1]));
3949 my $cb = "$ca$;$cc";
3952 $a = 'V' if ($elements[$n] ne '');
3953 $a = 'W' if ($elements[$n] =~ /\s$/);
3954 $a = 'C' if ($elements[$n] =~ /$;$/);
3955 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3956 $a = 'O' if ($elements[$n] eq '');
3957 $a = 'E' if ($ca =~ /^\s*$/);
3959 my $op = $elements[$n + 1];
3962 if (defined $elements[$n + 2]) {
3963 $c = 'V' if ($elements[$n + 2] ne '');
3964 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3965 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3966 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3967 $c = 'O' if ($elements[$n + 2] eq '');
3968 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3973 my $ctx = "${a}x${c}";
3975 my $at = "(ctx:$ctx)";
3977 my $ptr = substr($blank, 0, $off) . "^";
3978 my $hereptr = "$hereline$ptr\n";
3980 # Pull out the value of this operator.
3981 my $op_type = substr($curr_values, $off + 1, 1);
3983 # Get the full operator variant.
3984 my $opv = $op . substr($curr_vars, $off, 1);
3986 # Ignore operators passed as parameters.
3987 if ($op_type ne 'V' &&
3988 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
3991 # } elsif ($op =~ /^$;+$/) {
3993 # ; should have either the end of line or a space or \ after it
3994 } elsif ($op eq ';') {
3995 if ($ctx !~ /.x[WEBC]/ &&
3996 $cc !~ /^\\/ && $cc !~ /^;/) {
3997 if (ERROR("SPACING",
3998 "space required after that '$op' $at\n" . $hereptr)) {
3999 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4005 } elsif ($op eq '//') {
4007 # : when part of a bitfield
4008 } elsif ($opv eq ':B') {
4009 # skip the bitfield test for now
4013 } elsif ($op eq '->') {
4014 if ($ctx =~ /Wx.|.xW/) {
4015 if (ERROR("SPACING",
4016 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4017 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4018 if (defined $fix_elements[$n + 2]) {
4019 $fix_elements[$n + 2] =~ s/^\s+//;
4025 # , must not have a space before and must have a space on the right.
4026 } elsif ($op eq ',') {
4027 my $rtrim_before = 0;
4028 my $space_after = 0;
4029 if ($ctx =~ /Wx./) {
4030 if (ERROR("SPACING",
4031 "space prohibited before that '$op' $at\n" . $hereptr)) {
4036 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4037 if (ERROR("SPACING",
4038 "space required after that '$op' $at\n" . $hereptr)) {
4044 if ($rtrim_before || $space_after) {
4045 if ($rtrim_before) {
4046 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4048 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4055 # '*' as part of a type definition -- reported already.
4056 } elsif ($opv eq '*_') {
4057 #warn "'*' is part of type\n";
4059 # unary operators should have a space before and
4060 # none after. May be left adjacent to another
4061 # unary operator, or a cast
4062 } elsif ($op eq '!' || $op eq '~' ||
4063 $opv eq '*U' || $opv eq '-U' ||
4064 $opv eq '&U' || $opv eq '&&U') {
4065 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4066 if (ERROR("SPACING",
4067 "space required before that '$op' $at\n" . $hereptr)) {
4068 if ($n != $last_after + 2) {
4069 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4074 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4075 # A unary '*' may be const
4077 } elsif ($ctx =~ /.xW/) {
4078 if (ERROR("SPACING",
4079 "space prohibited after that '$op' $at\n" . $hereptr)) {
4080 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4081 if (defined $fix_elements[$n + 2]) {
4082 $fix_elements[$n + 2] =~ s/^\s+//;
4088 # unary ++ and unary -- are allowed no space on one side.
4089 } elsif ($op eq '++' or $op eq '--') {
4090 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4091 if (ERROR("SPACING",
4092 "space required one side of that '$op' $at\n" . $hereptr)) {
4093 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4097 if ($ctx =~ /Wx[BE]/ ||
4098 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4099 if (ERROR("SPACING",
4100 "space prohibited before that '$op' $at\n" . $hereptr)) {
4101 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4105 if ($ctx =~ /ExW/) {
4106 if (ERROR("SPACING",
4107 "space prohibited after that '$op' $at\n" . $hereptr)) {
4108 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4109 if (defined $fix_elements[$n + 2]) {
4110 $fix_elements[$n + 2] =~ s/^\s+//;
4116 # << and >> may either have or not have spaces both sides
4117 } elsif ($op eq '<<' or $op eq '>>' or
4118 $op eq '&' or $op eq '^' or $op eq '|' or
4119 $op eq '+' or $op eq '-' or
4120 $op eq '*' or $op eq '/' or
4124 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4126 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4127 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4128 $fix_elements[$n + 2] =~ s/^\s+//;
4131 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4133 "space preferred before that '$op' $at\n" . $hereptr)) {
4134 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4138 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4139 if (ERROR("SPACING",
4140 "need consistent spacing around '$op' $at\n" . $hereptr)) {
4141 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4142 if (defined $fix_elements[$n + 2]) {
4143 $fix_elements[$n + 2] =~ s/^\s+//;
4149 # A colon needs no spaces before when it is
4150 # terminating a case value or a label.
4151 } elsif ($opv eq ':C' || $opv eq ':L') {
4152 if ($ctx =~ /Wx./) {
4153 if (ERROR("SPACING",
4154 "space prohibited before that '$op' $at\n" . $hereptr)) {
4155 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4160 # All the others need spaces both sides.
4161 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4164 # Ignore email addresses <foo@bar>
4166 $cc =~ /^\S+\@\S+>/) ||
4168 $ca =~ /<\S+\@\S+$/))
4173 # for asm volatile statements
4174 # ignore a colon with another
4175 # colon immediately before or after
4177 ($ca =~ /:$/ || $cc =~ /^:/)) {
4181 # messages are ERROR, but ?: are CHK
4183 my $msg_type = \&ERROR;
4184 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4186 if (&{$msg_type}("SPACING",
4187 "spaces required around that '$op' $at\n" . $hereptr)) {
4188 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4189 if (defined $fix_elements[$n + 2]) {
4190 $fix_elements[$n + 2] =~ s/^\s+//;
4196 $off += length($elements[$n + 1]);
4198 ## print("n: <$n> GOOD: <$good>\n");
4200 $fixed_line = $fixed_line . $good;
4203 if (($#elements % 2) == 0) {
4204 $fixed_line = $fixed_line . $fix_elements[$#elements];
4207 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4208 $fixed[$fixlinenr] = $fixed_line;
4214 # check for whitespace before a non-naked semicolon
4215 if ($line =~ /^\+.*\S\s+;\s*$/) {
4217 "space prohibited before semicolon\n" . $herecurr) &&
4219 1 while $fixed[$fixlinenr] =~
4220 s/^(\+.*\S)\s+;/$1;/;
4224 # check for multiple assignments
4225 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4226 CHK("MULTIPLE_ASSIGNMENTS",
4227 "multiple assignments should be avoided\n" . $herecurr);
4230 ## # check for multiple declarations, allowing for a function declaration
4232 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4233 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4235 ## # Remove any bracketed sections to ensure we do not
4236 ## # falsly report the parameters of functions.
4238 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4240 ## if ($ln =~ /,/) {
4241 ## WARN("MULTIPLE_DECLARATION",
4242 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4246 #need space before brace following if, while, etc
4247 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\){/) ||
4249 if (ERROR("SPACING",
4250 "space required before the open brace '{'\n" . $herecurr) &&
4252 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\)))\{/$1 {/;
4256 ## # check for blank lines before declarations
4257 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4258 ## $prevrawline =~ /^.\s*$/) {
4260 ## "No blank lines before declarations\n" . $hereprev);
4264 # closing brace should have a space following it when it has anything
4266 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4267 if (ERROR("SPACING",
4268 "space required after that close brace '}'\n" . $herecurr) &&
4270 $fixed[$fixlinenr] =~
4271 s/}((?!(?:,|;|\)))\S)/} $1/;
4275 # check spacing on square brackets
4276 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4277 if (ERROR("SPACING",
4278 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4280 $fixed[$fixlinenr] =~
4284 if ($line =~ /\s\]/) {
4285 if (ERROR("SPACING",
4286 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4288 $fixed[$fixlinenr] =~
4293 # check spacing on parentheses
4294 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4295 $line !~ /for\s*\(\s+;/ && $line !~ /^\+\s*[A-Z_][A-Z\d_]*\(\s*\d+(\,.*)?\)\,?$/) {
4296 if (ERROR("SPACING",
4297 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4299 $fixed[$fixlinenr] =~
4303 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4304 $line !~ /for\s*\(.*;\s+\)/ &&
4305 $line !~ /:\s+\)/) {
4306 if (ERROR("SPACING",
4307 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4309 $fixed[$fixlinenr] =~
4314 # check unnecessary parentheses around addressof/dereference single $Lvals
4315 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4317 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4319 if (CHK("UNNECESSARY_PARENTHESES",
4320 "Unnecessary parentheses around $var\n" . $herecurr) &&
4322 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4326 # check for unnecessary parentheses around function pointer uses
4327 # ie: (foo->bar)(); should be foo->bar();
4328 # but not "if (foo->bar) (" to avoid some false positives
4329 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4331 if (CHK("UNNECESSARY_PARENTHESES",
4332 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4334 my $var2 = deparenthesize($var);
4336 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4340 #goto labels aren't indented, allow a single space however
4341 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4342 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4343 if (WARN("INDENTED_LABEL",
4344 "labels should not be indented\n" . $herecurr) &&
4346 $fixed[$fixlinenr] =~
4351 # return is not a function
4352 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4354 if ($^V && $^V ge 5.10.0 &&
4355 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4357 $value = deparenthesize($value);
4358 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4359 ERROR("RETURN_PARENTHESES",
4360 "return is not a function, parentheses are not required\n" . $herecurr);
4362 } elsif ($spacing !~ /\s+/) {
4364 "space required before the open parenthesis '('\n" . $herecurr);
4368 # unnecessary return in a void function
4369 # at end-of-function, with the previous line a single leading tab, then return;
4370 # and the line before that not a goto label target like "out:"
4371 if ($sline =~ /^[ \+]}\s*$/ &&
4372 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4374 $lines[$linenr - 3] =~ /^[ +]/ &&
4375 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4377 "void function return statements are not generally useful\n" . $hereprev);
4380 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4381 if ($^V && $^V ge 5.10.0 &&
4382 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4383 my $openparens = $1;
4384 my $count = $openparens =~ tr@\(@\(@;
4386 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4387 my $comp = $4; #Not $1 because of $LvalOrFunc
4388 $msg = " - maybe == should be = ?" if ($comp eq "==");
4389 WARN("UNNECESSARY_PARENTHESES",
4390 "Unnecessary parentheses$msg\n" . $herecurr);
4394 # comparisons with a constant or upper case identifier on the left
4395 # avoid cases like "foo + BAR < baz"
4396 # only fix matches surrounded by parentheses to avoid incorrect
4397 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4398 if ($^V && $^V ge 5.10.0 &&
4399 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4404 my $newcomp = $comp;
4405 if ($lead !~ /$Operators\s*$/ &&
4406 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4407 WARN("CONSTANT_COMPARISON",
4408 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4412 } elsif ($comp eq "<=") {
4414 } elsif ($comp eq ">") {
4416 } elsif ($comp eq ">=") {
4419 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4423 # Return of what appears to be an errno should normally be negative
4424 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4426 if ($name ne 'EOF' && $name ne 'ERROR') {
4427 WARN("USE_NEGATIVE_ERRNO",
4428 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4432 # Need a space before open parenthesis after if, while etc
4433 if ($line =~ /\b(if|while|for|switch)\(/) {
4434 if (ERROR("SPACING",
4435 "space required before the open parenthesis '('\n" . $herecurr) &&
4437 $fixed[$fixlinenr] =~
4438 s/\b(if|while|for|switch)\(/$1 \(/;
4442 # Check for illegal assignment in if conditional -- and check for trailing
4443 # statements after the conditional.
4444 if ($line =~ /do\s*(?!{)/) {
4445 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4446 ctx_statement_block($linenr, $realcnt, 0)
4447 if (!defined $stat);
4448 my ($stat_next) = ctx_statement_block($line_nr_next,
4449 $remain_next, $off_next);
4450 $stat_next =~ s/\n./\n /g;
4451 ##print "stat<$stat> stat_next<$stat_next>\n";
4453 if ($stat_next =~ /^\s*while\b/) {
4454 # If the statement carries leading newlines,
4455 # then count those as offsets.
4457 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4459 statement_rawlines($whitespace) - 1;
4461 $suppress_whiletrailers{$line_nr_next +
4465 if (!defined $suppress_whiletrailers{$linenr} &&
4466 defined($stat) && defined($cond) &&
4467 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4468 my ($s, $c) = ($stat, $cond);
4470 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4471 ERROR("ASSIGN_IN_IF",
4472 "do not use assignment in if condition\n" . $herecurr);
4475 # Find out what is on the end of the line after the
4477 substr($s, 0, length($c), '');
4479 $s =~ s/$;//g; # Remove any comments
4480 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4481 $c !~ /}\s*while\s*/)
4483 # Find out how long the conditional actually is.
4484 my @newlines = ($c =~ /\n/gs);
4485 my $cond_lines = 1 + $#newlines;
4488 $stat_real = raw_line($linenr, $cond_lines)
4489 . "\n" if ($cond_lines);
4490 if (defined($stat_real) && $cond_lines > 1) {
4491 $stat_real = "[...]\n$stat_real";
4494 ERROR("TRAILING_STATEMENTS",
4495 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4499 # Check for bitwise tests written as boolean
4511 WARN("HEXADECIMAL_BOOLEAN_TEST",
4512 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4515 # if and else should not have general statements after it
4516 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4518 $s =~ s/$;//g; # Remove any comments
4519 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4520 ERROR("TRAILING_STATEMENTS",
4521 "trailing statements should be on next line\n" . $herecurr);
4524 # if should not continue a brace
4525 if ($line =~ /}\s*if\b/) {
4526 ERROR("TRAILING_STATEMENTS",
4527 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4530 # case and default should not have general statements after them
4531 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4533 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4537 ERROR("TRAILING_STATEMENTS",
4538 "trailing statements should be on next line\n" . $herecurr);
4541 # Check for }<nl>else {, these must be at the same
4542 # indent level to be relevant to each other.
4543 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4544 $previndent == $indent) {
4545 if (ERROR("ELSE_AFTER_BRACE",
4546 "else should follow close brace '}'\n" . $hereprev) &&
4547 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4548 fix_delete_line($fixlinenr - 1, $prevrawline);
4549 fix_delete_line($fixlinenr, $rawline);
4550 my $fixedline = $prevrawline;
4551 $fixedline =~ s/}\s*$//;
4552 if ($fixedline !~ /^\+\s*$/) {
4553 fix_insert_line($fixlinenr, $fixedline);
4555 $fixedline = $rawline;
4556 $fixedline =~ s/^(.\s*)else/$1} else/;
4557 fix_insert_line($fixlinenr, $fixedline);
4561 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4562 $previndent == $indent) {
4563 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4565 # Find out what is on the end of the line after the
4567 substr($s, 0, length($c), '');
4570 if ($s =~ /^\s*;/) {
4571 if (ERROR("WHILE_AFTER_BRACE",
4572 "while should follow close brace '}'\n" . $hereprev) &&
4573 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4574 fix_delete_line($fixlinenr - 1, $prevrawline);
4575 fix_delete_line($fixlinenr, $rawline);
4576 my $fixedline = $prevrawline;
4577 my $trailing = $rawline;
4578 $trailing =~ s/^\+//;
4579 $trailing = trim($trailing);
4580 $fixedline =~ s/}\s*$/} $trailing/;
4581 fix_insert_line($fixlinenr, $fixedline);
4586 #Specific variable tests
4587 while ($line =~ m{($Constant|$Lval)}g) {
4590 #gcc binary extension
4591 if ($var =~ /^$Binary$/) {
4592 if (WARN("GCC_BINARY_CONSTANT",
4593 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4595 my $hexval = sprintf("0x%x", oct($var));
4596 $fixed[$fixlinenr] =~
4597 s/\b$var\b/$hexval/;
4602 if ($var !~ /^$Constant$/ &&
4603 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4604 #Ignore Page<foo> variants
4605 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4606 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4607 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4608 #Ignore some three character SI units explicitly, like MiB and KHz
4609 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4610 while ($var =~ m{($Ident)}g) {
4612 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4614 seed_camelcase_includes();
4615 if (!$file && !$camelcase_file_seeded) {
4616 seed_camelcase_file($realfile);
4617 $camelcase_file_seeded = 1;
4620 if (!defined $camelcase{$word}) {
4621 $camelcase{$word} = 1;
4623 "Avoid CamelCase: <$word>\n" . $herecurr);
4629 #no spaces allowed after \ in define
4630 if ($line =~ /\#\s*define.*\\\s+$/) {
4631 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4632 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4634 $fixed[$fixlinenr] =~ s/\s+$//;
4638 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4639 # itself <asm/foo.h> (uses RAW line)
4640 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4642 my $checkfile = "include/linux/$file";
4643 if (-f "$root/$checkfile" &&
4644 $realfile ne $checkfile &&
4645 $1 !~ /$allowed_asm_includes/)
4647 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4648 if ($asminclude > 0) {
4649 if ($realfile =~ m{^arch/}) {
4650 CHK("ARCH_INCLUDE_LINUX",
4651 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4653 WARN("INCLUDE_LINUX",
4654 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4660 # multi-statement macros should be enclosed in a do while loop, grab the
4661 # first statement and ensure its the whole macro if its not enclosed
4662 # in a known good container
4663 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4664 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4666 my $cnt = $realcnt - 1;
4667 my ($off, $dstat, $dcond, $rest);
4669 my $has_flow_statement = 0;
4670 my $has_arg_concat = 0;
4671 ($dstat, $dcond, $ln, $cnt, $off) =
4672 ctx_statement_block($linenr, $realcnt, 0);
4674 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4675 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4677 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4678 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4680 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4682 $dstat =~ s/\\\n.//g;
4683 $dstat =~ s/^\s*//s;
4684 $dstat =~ s/\s*$//s;
4686 # Flatten any parentheses and braces
4687 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4688 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4689 $dstat =~ s/\[[^\[\]]*\]/1/)
4693 # Extremely long macros may fall off the end of the
4694 # available context without closing. Give a dangling
4695 # backslash the benefit of the doubt and allow it
4696 # to gobble any hanging open-parens.
4697 $dstat =~ s/\(.+\\$/1/;
4699 # Flatten any obvious string concatentation.
4700 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
4701 $dstat =~ s/$Ident\s*($String)/$1/)
4705 my $exceptions = qr{
4718 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4720 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4721 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4722 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4723 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4724 $dstat !~ /$exceptions/ &&
4725 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4726 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4727 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4728 $dstat !~ /^for\s*$Constant$/ && # for (...)
4729 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4730 $dstat !~ /^do\s*{/ && # do {...
4731 $dstat !~ /^\(\{/ && # ({...
4732 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4735 my $herectx = $here . "\n";
4736 my $cnt = statement_rawlines($ctx);
4738 for (my $n = 0; $n < $cnt; $n++) {
4739 $herectx .= raw_line($linenr, $n) . "\n";
4742 if ($dstat =~ /;/) {
4743 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4744 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4746 ERROR("COMPLEX_MACRO",
4747 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4751 # check for macros with flow control, but without ## concatenation
4752 # ## concatenation is commonly a macro that defines a function so ignore those
4753 if ($has_flow_statement && !$has_arg_concat) {
4754 my $herectx = $here . "\n";
4755 my $cnt = statement_rawlines($ctx);
4757 for (my $n = 0; $n < $cnt; $n++) {
4758 $herectx .= raw_line($linenr, $n) . "\n";
4760 WARN("MACRO_WITH_FLOW_CONTROL",
4761 "Macros with flow control statements should be avoided\n" . "$herectx");
4764 # check for line continuations outside of #defines, preprocessor #, and asm
4767 if ($prevline !~ /^..*\\$/ &&
4768 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4769 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4770 $line =~ /^\+.*\\$/) {
4771 WARN("LINE_CONTINUATIONS",
4772 "Avoid unnecessary line continuations\n" . $herecurr);
4776 # do {} while (0) macro tests:
4777 # single-statement macros do not need to be enclosed in do while (0) loop,
4778 # macro should not end with a semicolon
4779 if ($^V && $^V ge 5.10.0 &&
4780 $realfile !~ m@/vmlinux.lds.h$@ &&
4781 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4784 my ($off, $dstat, $dcond, $rest);
4786 ($dstat, $dcond, $ln, $cnt, $off) =
4787 ctx_statement_block($linenr, $realcnt, 0);
4790 $dstat =~ s/\\\n.//g;
4793 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4798 my $cnt = statement_rawlines($ctx);
4799 my $herectx = $here . "\n";
4801 for (my $n = 0; $n < $cnt; $n++) {
4802 $herectx .= raw_line($linenr, $n) . "\n";
4805 if (($stmts =~ tr/;/;/) == 1 &&
4806 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4807 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4808 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4810 if (defined $semis && $semis ne "") {
4811 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4812 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4814 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4816 my $cnt = statement_rawlines($ctx);
4817 my $herectx = $here . "\n";
4819 for (my $n = 0; $n < $cnt; $n++) {
4820 $herectx .= raw_line($linenr, $n) . "\n";
4823 WARN("TRAILING_SEMICOLON",
4824 "macros should not use a trailing semicolon\n" . "$herectx");
4828 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4829 # all assignments may have only one of the following with an assignment:
4832 # VMLINUX_SYMBOL(...)
4833 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4834 WARN("MISSING_VMLINUX_SYMBOL",
4835 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4838 # check for redundant bracing round if etc
4839 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4840 my ($level, $endln, @chunks) =
4841 ctx_statement_full($linenr, $realcnt, 1);
4842 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4843 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4844 if ($#chunks > 0 && $level == 0) {
4848 my $herectx = $here . "\n";
4849 my $ln = $linenr - 1;
4850 for my $chunk (@chunks) {
4851 my ($cond, $block) = @{$chunk};
4853 # If the condition carries leading newlines, then count those as offsets.
4854 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4855 my $offset = statement_rawlines($whitespace) - 1;
4857 $allowed[$allow] = 0;
4858 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4860 # We have looked at and allowed this specific line.
4861 $suppress_ifbraces{$ln + $offset} = 1;
4863 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4864 $ln += statement_rawlines($block) - 1;
4866 substr($block, 0, length($cond), '');
4868 $seen++ if ($block =~ /^\s*{/);
4870 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4871 if (statement_lines($cond) > 1) {
4872 #print "APW: ALLOWED: cond<$cond>\n";
4873 $allowed[$allow] = 1;
4875 if ($block =~/\b(?:if|for|while)\b/) {
4876 #print "APW: ALLOWED: block<$block>\n";
4877 $allowed[$allow] = 1;
4879 if (statement_block_size($block) > 1) {
4880 #print "APW: ALLOWED: lines block<$block>\n";
4881 $allowed[$allow] = 1;
4886 my $sum_allowed = 0;
4887 foreach (@allowed) {
4890 if ($sum_allowed == 0) {
4892 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4893 } elsif ($sum_allowed != $allow &&
4896 "braces {} should be used on all arms of this statement\n" . $herectx);
4901 if (!defined $suppress_ifbraces{$linenr - 1} &&
4902 $line =~ /\b(if|while|for|else)\b/) {
4905 # Check the pre-context.
4906 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4907 #print "APW: ALLOWED: pre<$1>\n";
4911 my ($level, $endln, @chunks) =
4912 ctx_statement_full($linenr, $realcnt, $-[0]);
4914 # Check the condition.
4915 my ($cond, $block) = @{$chunks[0]};
4916 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4917 if (defined $cond) {
4918 substr($block, 0, length($cond), '');
4920 if (statement_lines($cond) > 1) {
4921 #print "APW: ALLOWED: cond<$cond>\n";
4924 if ($block =~/\b(?:if|for|while)\b/) {
4925 #print "APW: ALLOWED: block<$block>\n";
4928 if (statement_block_size($block) > 1) {
4929 #print "APW: ALLOWED: lines block<$block>\n";
4932 # Check the post-context.
4933 if (defined $chunks[1]) {
4934 my ($cond, $block) = @{$chunks[1]};
4935 if (defined $cond) {
4936 substr($block, 0, length($cond), '');
4938 if ($block =~ /^\s*\{/) {
4939 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4943 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4944 my $herectx = $here . "\n";
4945 my $cnt = statement_rawlines($block);
4947 for (my $n = 0; $n < $cnt; $n++) {
4948 $herectx .= raw_line($linenr, $n) . "\n";
4952 "braces {} are not necessary for single statement blocks\n" . $herectx);
4956 # check for unnecessary blank lines around braces
4957 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4959 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4960 $fix && $prevrawline =~ /^\+/) {
4961 fix_delete_line($fixlinenr - 1, $prevrawline);
4964 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4966 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4968 fix_delete_line($fixlinenr, $rawline);
4972 # no volatiles please
4973 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4974 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4976 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4979 # Check for user-visible strings broken across lines, which breaks the ability
4980 # to grep for the string. Make exceptions when the previous string ends in a
4981 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4982 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4983 if ($line =~ /^\+\s*$String/ &&
4984 $prevline =~ /"\s*$/ &&
4985 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4986 if (WARN("SPLIT_STRING",
4987 "quoted string split across lines\n" . $hereprev) &&
4989 $prevrawline =~ /^\+.*"\s*$/ &&
4990 $last_coalesced_string_linenr != $linenr - 1) {
4991 my $extracted_string = get_quoted_string($line, $rawline);
4992 my $comma_close = "";
4993 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4997 fix_delete_line($fixlinenr - 1, $prevrawline);
4998 fix_delete_line($fixlinenr, $rawline);
4999 my $fixedline = $prevrawline;
5000 $fixedline =~ s/"\s*$//;
5001 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5002 fix_insert_line($fixlinenr - 1, $fixedline);
5003 $fixedline = $rawline;
5004 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5005 if ($fixedline !~ /\+\s*$/) {
5006 fix_insert_line($fixlinenr, $fixedline);
5008 $last_coalesced_string_linenr = $linenr;
5012 # check for missing a space in a string concatenation
5013 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5014 WARN('MISSING_SPACE',
5015 "break quoted strings at a space character\n" . $hereprev);
5018 # check for spaces before a quoted newline
5019 if ($rawline =~ /^.*\".*\s\\n/) {
5020 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5021 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5023 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5028 # concatenated string without spaces between elements
5029 if ($line =~ /$String[A-Z_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5030 CHK("CONCATENATED_STRING",
5031 "Concatenated strings should use spaces between elements\n" . $herecurr);
5034 # uncoalesced string fragments
5035 if ($line =~ /$String\s*"/) {
5036 WARN("STRING_FRAGMENTS",
5037 "Consecutive strings are generally better as a single string\n" . $herecurr);
5040 # check for %L{u,d,i} and 0x%[udi] in strings
5042 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5043 $string = substr($rawline, $-[1], $+[1] - $-[1]);
5044 $string =~ s/%%/__/g;
5045 if ($string =~ /(?<!%)%[\*\d\.\$]*L[udi]/) {
5047 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
5050 if ($string =~ /0x%[\*\d\.\$\Llzth]*[udi]/) {
5051 ERROR("PRINTF_0xDECIMAL",
5052 "Prefixing 0x with decimal output is defective\n" . $herecurr);
5056 # check for line continuations in quoted strings with odd counts of "
5057 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
5058 WARN("LINE_CONTINUATIONS",
5059 "Avoid line continuations in quoted strings\n" . $herecurr);
5062 # sys_open/read/write/close are not allowed in the kernel
5063 if ($line =~ /\b(sys_(?:open|read|write|close))\b/) {
5065 "$1 is inappropriate in kernel code.\n" .
5069 # filp_open is a backdoor for sys_open
5070 if ($line =~ /\b(filp_open)\b/) {
5072 "$1 is inappropriate in kernel code.\n" .
5076 # read[bwl] & write[bwl] use too many barriers, use the _relaxed variants
5077 if ($line =~ /\b((?:read|write)[bwl])\b/) {
5078 ERROR("NON_RELAXED_IO",
5079 "Use of $1 is deprecated: use $1_relaxed\n\t" .
5080 "with appropriate memory barriers instead.\n" .
5084 # likewise, in/out[bwl] should be __raw_read/write[bwl]...
5085 if ($line =~ /\b((in|out)([bwl]))\b/) {
5086 my ($all, $pref, $suf) = ($1, $2, $3);
5087 $pref =~ s/in/read/;
5088 $pref =~ s/out/write/;
5089 ERROR("NON_RELAXED_IO",
5090 "Use of $all is deprecated: use " .
5091 "__raw_$pref$suf\n\t" .
5092 "with appropriate memory barriers instead.\n" .
5096 # dsb is too ARMish, and should usually be mb.
5097 if ($line =~ /[^-_>*\.]\bdsb\b[^-_\.;]/) {
5099 "Use of dsb is discouranged: prefer mb.\n" .
5103 # MSM - check if a non board-gpiomux file has any gpiomux declarations
5104 if ($realfile =~ /\/mach-msm\/board-[0-9]+/ &&
5105 $realfile !~ /camera/ && $realfile !~ /gpiomux/ &&
5106 $line =~ /\s*struct msm_gpiomux_config\s*/ ) {
5107 WARN("GPIOMUX_IN_BOARD",
5108 "Non gpiomux board file cannot have a gpiomux config declarations. Please declare gpiomux configs in board-*-gpiomux.c file.\n" . $herecurr);
5111 # MSM - check if vreg_xxx function are used
5112 if ($line =~ /\b(vreg_(get|put|set_level|enable|disable))\b/) {
5113 WARN("DEPRECATED_VREG_APIS",
5114 "Use of $1 API is deprecated: " .
5115 "use regulator APIs\n" . $herecurr);
5118 # unbounded string functions are overflow risks
5120 "sprintf" => "snprintf",
5121 "strcpy" => "strlcpy",
5122 "strncpy" => "strlcpy",
5123 "strcat" => "strlcat",
5124 "strncat" => "strlcat",
5125 "vsprintf" => "vsnprintf",
5126 "strchr" => "strnchr",
5127 "strstr" => "strnstr",
5129 foreach my $k (keys %str_fns) {
5130 if ($line =~ /\b$k\b/) {
5131 ERROR("UNBOUNDED_STRING_FNS",
5132 "Use of $k is deprecated: " .
5133 "use $str_fns{$k} instead.\n" .
5139 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5141 "if this code is redundant consider removing it\n"
5146 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5148 "if this code is required consider removing"
5149 . " #if 1\n" . $herecurr);
5152 # check for needless "if (<foo>) fn(<foo>)" uses
5153 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5154 my $tested = quotemeta($1);
5155 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5156 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5158 if (WARN('NEEDLESS_IF',
5159 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5162 my $leading_tabs = "";
5163 my $new_leading_tabs = "";
5164 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5169 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5170 $new_leading_tabs = $1;
5171 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5178 fix_delete_line($fixlinenr - 1, $prevrawline);
5179 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5185 # check for unnecessary "Out of Memory" messages
5186 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5187 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5188 (defined $1 || defined $3) &&
5191 my $testline = $lines[$linenr - 3];
5193 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5194 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5196 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
5198 "Possible unnecessary 'out of memory' message\n" . $hereprev);
5202 # check for logging functions with KERN_<LEVEL>
5203 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5204 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5206 if (WARN("UNNECESSARY_KERN_LEVEL",
5207 "Possible unnecessary $level\n" . $herecurr) &&
5209 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5213 # check for mask then right shift without a parentheses
5214 if ($^V && $^V ge 5.10.0 &&
5215 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5216 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5217 WARN("MASK_THEN_SHIFT",
5218 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5221 # check for pointer comparisons to NULL
5222 if ($^V && $^V ge 5.10.0) {
5223 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5226 $equal = "" if ($4 eq "!=");
5227 if (CHK("COMPARISON_TO_NULL",
5228 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5230 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5235 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5236 if ($line =~ /(\b$InitAttribute\b)/) {
5238 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5241 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5242 ERROR("MISPLACED_INIT",
5243 "$attr should be placed after $var\n" . $herecurr)) ||
5244 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5245 WARN("MISPLACED_INIT",
5246 "$attr should be placed after $var\n" . $herecurr))) &&
5248 $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;
5253 # check for $InitAttributeData (ie: __initdata) with const
5254 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5256 $attr =~ /($InitAttributePrefix)(.*)/;
5257 my $attr_prefix = $1;
5259 if (ERROR("INIT_ATTRIBUTE",
5260 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5262 $fixed[$fixlinenr] =~
5263 s/$InitAttributeData/${attr_prefix}initconst/;
5267 # check for $InitAttributeConst (ie: __initconst) without const
5268 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5270 if (ERROR("INIT_ATTRIBUTE",
5271 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5273 my $lead = $fixed[$fixlinenr] =~
5274 /(^\+\s*(?:static\s+))/;
5276 $lead = "$lead " if ($lead !~ /^\+$/);
5277 $lead = "${lead}const ";
5278 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5282 # check for __read_mostly with const non-pointer (should just be const)
5283 if ($line =~ /\b__read_mostly\b/ &&
5284 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5285 if (ERROR("CONST_READ_MOSTLY",
5286 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5288 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5292 # don't use __constant_<foo> functions outside of include/uapi/
5293 if ($realfile !~ m@^include/uapi/@ &&
5294 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5295 my $constant_func = $1;
5296 my $func = $constant_func;
5297 $func =~ s/^__constant_//;
5298 if (WARN("CONSTANT_CONVERSION",
5299 "$constant_func should be $func\n" . $herecurr) &&
5301 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5305 # prefer usleep_range over udelay
5306 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5308 # ignore udelay's < 10, however
5309 if (! ($delay < 10) ) {
5311 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5313 if ($delay > 2000) {
5315 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5319 # warn about unexpectedly long msleep's
5320 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5323 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5327 # check for comparisons of jiffies
5328 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5329 WARN("JIFFIES_COMPARISON",
5330 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5333 # check for comparisons of get_jiffies_64()
5334 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5335 WARN("JIFFIES_COMPARISON",
5336 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5339 # check the patch for use of mdelay
5340 if ($line =~ /\bmdelay\s*\(/) {
5342 "use of mdelay() found: msleep() is the preferred API.\n" . $herecurr );
5345 # warn about #ifdefs in C files
5346 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5347 # print "#ifdef in C files should be avoided\n";
5348 # print "$herecurr";
5352 # warn about spacing in #ifdefs
5353 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5354 if (ERROR("SPACING",
5355 "exactly one space required after that #$1\n" . $herecurr) &&
5357 $fixed[$fixlinenr] =~
5358 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5363 # check for spinlock_t definitions without a comment.
5364 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5365 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5367 if (!ctx_has_comment($first_line, $linenr)) {
5368 CHK("UNCOMMENTED_DEFINITION",
5369 "$1 definition without comment\n" . $herecurr);
5372 # check for memory barriers without a comment.
5373 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
5374 if (!ctx_has_comment($first_line, $linenr)) {
5375 WARN("MEMORY_BARRIER",
5376 "memory barrier without comment\n" . $herecurr);
5380 # check for waitqueue_active without a comment.
5381 if ($line =~ /\bwaitqueue_active\s*\(/) {
5382 if (!ctx_has_comment($first_line, $linenr)) {
5383 WARN("WAITQUEUE_ACTIVE",
5384 "waitqueue_active without comment\n" . $herecurr);
5388 # Check for expedited grace periods that interrupt non-idle non-nohz
5389 # online CPUs. These expedited can therefore degrade real-time response
5390 # if used carelessly, and should be avoided where not absolutely
5391 # needed. It is always OK to use synchronize_rcu_expedited() and
5392 # synchronize_sched_expedited() at boot time (before real-time applications
5393 # start) and in error situations where real-time response is compromised in
5394 # any case. Note that synchronize_srcu_expedited() does -not- interrupt
5395 # other CPUs, so don't warn on uses of synchronize_srcu_expedited().
5396 # Of course, nothing comes for free, and srcu_read_lock() and
5397 # srcu_read_unlock() do contain full memory barriers in payment for
5398 # synchronize_srcu_expedited() non-interruption properties.
5399 if ($line =~ /\b(synchronize_rcu_expedited|synchronize_sched_expedited)\(/) {
5400 WARN("EXPEDITED_RCU_GRACE_PERIOD",
5401 "expedited RCU grace periods should be avoided where they can degrade real-time response\n" . $herecurr);
5405 # check of hardware specific defines
5406 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5408 "architecture specific defines should be avoided\n" . $herecurr);
5411 # Check that the storage class is at the beginning of a declaration
5412 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
5413 WARN("STORAGE_CLASS",
5414 "storage class should be at the beginning of the declaration\n" . $herecurr)
5417 # check the location of the inline attribute, that it is between
5418 # storage class and type.
5419 if ($line =~ /\b$Type\s+$Inline\b/ ||
5420 $line =~ /\b$Inline\s+$Storage\b/) {
5421 ERROR("INLINE_LOCATION",
5422 "inline keyword should sit between storage class and type\n" . $herecurr);
5425 # Check for __inline__ and __inline, prefer inline
5426 if ($realfile !~ m@\binclude/uapi/@ &&
5427 $line =~ /\b(__inline__|__inline)\b/) {
5429 "plain inline is preferred over $1\n" . $herecurr) &&
5431 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5436 # Check for __attribute__ packed, prefer __packed
5437 if ($realfile !~ m@\binclude/uapi/@ &&
5438 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5439 WARN("PREFER_PACKED",
5440 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5443 # Check for __attribute__ aligned, prefer __aligned
5444 if ($realfile !~ m@\binclude/uapi/@ &&
5445 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5446 WARN("PREFER_ALIGNED",
5447 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5450 # Check for __attribute__ format(printf, prefer __printf
5451 if ($realfile !~ m@\binclude/uapi/@ &&
5452 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5453 if (WARN("PREFER_PRINTF",
5454 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5456 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5461 # Check for __attribute__ format(scanf, prefer __scanf
5462 if ($realfile !~ m@\binclude/uapi/@ &&
5463 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5464 if (WARN("PREFER_SCANF",
5465 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5467 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5471 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5472 if ($^V && $^V ge 5.10.0 &&
5473 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5474 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5475 $line =~ /\b__weak\b/)) {
5476 ERROR("WEAK_DECLARATION",
5477 "Using weak declarations can have unintended link defects\n" . $herecurr);
5480 # check for c99 types like uint8_t used outside of uapi/
5481 if ($realfile !~ m@\binclude/uapi/@ &&
5482 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5484 if ($type =~ /\b($typeC99Typedefs)\b/) {
5486 my $kernel_type = 'u';
5487 $kernel_type = 's' if ($type =~ /^_*[si]/);
5490 if (CHK("PREFER_KERNEL_TYPES",
5491 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5493 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5498 # check for sizeof(&)
5499 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5500 WARN("SIZEOF_ADDRESS",
5501 "sizeof(& should be avoided\n" . $herecurr);
5504 # check for sizeof without parenthesis
5505 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5506 if (WARN("SIZEOF_PARENTHESIS",
5507 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5509 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5513 # check for struct spinlock declarations
5514 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5515 WARN("USE_SPINLOCK_T",
5516 "struct spinlock should be spinlock_t\n" . $herecurr);
5519 # check for seq_printf uses that could be seq_puts
5520 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5521 my $fmt = get_quoted_string($line, $rawline);
5524 if (WARN("PREFER_SEQ_PUTS",
5525 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5527 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5532 # Check for misused memsets
5533 if ($^V && $^V ge 5.10.0 &&
5535 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5541 if ($ms_size =~ /^(0x|)0$/i) {
5543 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5544 } elsif ($ms_size =~ /^(0x|)1$/i) {
5546 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5550 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5551 if ($^V && $^V ge 5.10.0 &&
5553 $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5554 if (WARN("PREFER_ETHER_ADDR_COPY",
5555 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5557 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5561 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5562 if ($^V && $^V ge 5.10.0 &&
5564 $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5565 WARN("PREFER_ETHER_ADDR_EQUAL",
5566 "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5569 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5570 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5571 if ($^V && $^V ge 5.10.0 &&
5573 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5577 if ($ms_val =~ /^(?:0x|)0+$/i) {
5578 if (WARN("PREFER_ETH_ZERO_ADDR",
5579 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5581 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5583 } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5584 if (WARN("PREFER_ETH_BROADCAST_ADDR",
5585 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
5587 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
5592 # typecasts on min/max could be min_t/max_t
5593 if ($^V && $^V ge 5.10.0 &&
5595 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5596 if (defined $2 || defined $7) {
5598 my $cast1 = deparenthesize($2);
5600 my $cast2 = deparenthesize($7);
5604 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5605 $cast = "$cast1 or $cast2";
5606 } elsif ($cast1 ne "") {
5612 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5616 # check usleep_range arguments
5617 if ($^V && $^V ge 5.10.0 &&
5619 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5623 WARN("USLEEP_RANGE",
5624 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5625 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5627 WARN("USLEEP_RANGE",
5628 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5632 # check for naked sscanf
5633 if ($^V && $^V ge 5.10.0 &&
5635 $line =~ /\bsscanf\b/ &&
5636 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5637 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5638 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5639 my $lc = $stat =~ tr@\n@@;
5640 $lc = $lc + $linenr;
5641 my $stat_real = raw_line($linenr, 0);
5642 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5643 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5645 WARN("NAKED_SSCANF",
5646 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5649 # check for simple sscanf that should be kstrto<foo>
5650 if ($^V && $^V ge 5.10.0 &&
5652 $line =~ /\bsscanf\b/) {
5653 my $lc = $stat =~ tr@\n@@;
5654 $lc = $lc + $linenr;
5655 my $stat_real = raw_line($linenr, 0);
5656 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5657 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5659 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5661 my $count = $format =~ tr@%@%@;
5663 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5664 WARN("SSCANF_TO_KSTRTO",
5665 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5670 # check for new externs in .h files.
5671 if ($realfile =~ /\.h$/ &&
5672 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5673 if (CHK("AVOID_EXTERNS",
5674 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5676 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5680 # check for new externs in .c files.
5681 if ($realfile =~ /\.c$/ && defined $stat &&
5682 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5684 my $function_name = $1;
5685 my $paren_space = $2;
5688 if (defined $cond) {
5689 substr($s, 0, length($cond), '');
5691 if ($s =~ /^\s*;/ &&
5692 $function_name ne 'uninitialized_var')
5694 WARN("AVOID_EXTERNS",
5695 "externs should be avoided in .c files\n" . $herecurr);
5698 if ($paren_space =~ /\n/) {
5699 WARN("FUNCTION_ARGUMENTS",
5700 "arguments for function declarations should follow identifier\n" . $herecurr);
5703 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5704 $stat =~ /^.\s*extern\s+/)
5706 WARN("AVOID_EXTERNS",
5707 "externs should be avoided in .c files\n" . $herecurr);
5710 # checks for new __setup's
5711 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5714 if (!grep(/$name/, @setup_docs)) {
5715 CHK("UNDOCUMENTED_SETUP",
5716 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5720 # check for pointless casting of kmalloc return
5721 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5722 WARN("UNNECESSARY_CASTS",
5723 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5727 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5728 if ($^V && $^V ge 5.10.0 &&
5729 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5730 CHK("ALLOC_SIZEOF_STRUCT",
5731 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5734 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5735 if ($^V && $^V ge 5.10.0 &&
5736 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5740 my $newfunc = "kmalloc_array";
5741 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5744 if ($a1 =~ /^sizeof\s*\S/) {
5748 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5749 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5750 if (WARN("ALLOC_WITH_MULTIPLY",
5751 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5753 $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;
5759 # check for krealloc arg reuse
5760 if ($^V && $^V ge 5.10.0 &&
5761 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5762 WARN("KREALLOC_ARG_REUSE",
5763 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5766 # check for alloc argument mismatch
5767 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5768 WARN("ALLOC_ARRAY_ARGS",
5769 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5772 # check for multiple semicolons
5773 if ($line =~ /;\s*;\s*$/) {
5774 if (WARN("ONE_SEMICOLON",
5775 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5777 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5781 # check for #defines like: 1 << <digit> that could be BIT(digit)
5782 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5784 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5785 if (CHK("BIT_MACRO",
5786 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5788 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5792 # check for case / default statements not preceded by break/fallthrough/switch
5793 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5795 my $has_statement = 0;
5797 my $prevline = $linenr;
5798 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5800 my $rline = $rawlines[$prevline - 1];
5801 my $fline = $lines[$prevline - 1];
5802 last if ($fline =~ /^\@\@/);
5803 next if ($fline =~ /^\-/);
5804 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5805 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5806 next if ($fline =~ /^.[\s$;]*$/);
5809 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5811 if (!$has_break && $has_statement) {
5812 WARN("MISSING_BREAK",
5813 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5817 # check for switch/default statements without a break;
5818 if ($^V && $^V ge 5.10.0 &&
5820 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5822 my $herectx = $here . "\n";
5823 my $cnt = statement_rawlines($stat);
5824 for (my $n = 0; $n < $cnt; $n++) {
5825 $herectx .= raw_line($linenr, $n) . "\n";
5827 WARN("DEFAULT_NO_BREAK",
5828 "switch default: should use break\n" . $herectx);
5831 # check for return codes on error paths
5832 if ($line =~ /\breturn\s+-\d+/) {
5833 ERROR("NO_ERROR_CODE",
5834 "illegal return value, please use an error code\n" . $herecurr);
5837 # check for gcc specific __FUNCTION__
5838 if ($line =~ /\b__FUNCTION__\b/) {
5839 if (WARN("USE_FUNC",
5840 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5842 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5846 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5847 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5849 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5852 # check for use of yield()
5853 if ($line =~ /\byield\s*\(\s*\)/) {
5855 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5858 # check for comparisons against true and false
5859 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5867 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5869 my $type = lc($otype);
5870 if ($type =~ /^(?:true|false)$/) {
5871 if (("$test" eq "==" && "$type" eq "true") ||
5872 ("$test" eq "!=" && "$type" eq "false")) {
5876 CHK("BOOL_COMPARISON",
5877 "Using comparison to $otype is error prone\n" . $herecurr);
5879 ## maybe suggesting a correct construct would better
5880 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5885 # check for semaphores initialized locked
5886 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5887 WARN("CONSIDER_COMPLETION",
5888 "consider using a completion\n" . $herecurr);
5891 # recommend kstrto* over simple_strto* and strict_strto*
5892 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5893 WARN("CONSIDER_KSTRTO",
5894 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5897 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5898 if ($line =~ /^.\s*__initcall\s*\(/) {
5899 WARN("USE_DEVICE_INITCALL",
5900 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5903 # check for various structs that are normally const (ops, kgdb, device_tree)
5904 my $const_structs = qr{
5906 address_space_operations|
5908 block_device_operations|
5913 file_lock_operations|
5923 lock_manager_operations|
5930 pipe_buf_operations|
5931 platform_hibernation_ops|
5932 platform_suspend_ops|
5937 soc_pcmcia_socket_ops|
5944 if ($line !~ /\bconst\b/ &&
5945 $line =~ /\bstruct\s+($const_structs)\b/) {
5946 WARN("CONST_STRUCT",
5947 "struct $1 should normally be const\n" .
5951 # use of NR_CPUS is usually wrong
5952 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5953 if ($line =~ /\bNR_CPUS\b/ &&
5954 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5955 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5956 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5957 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5958 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5961 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5964 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5965 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5966 ERROR("DEFINE_ARCH_HAS",
5967 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5970 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5971 if ($^V && $^V ge 5.10.0 &&
5972 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5973 WARN("LIKELY_MISUSE",
5974 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5977 # whine mightly about in_atomic
5978 if ($line =~ /\bin_atomic\s*\(/) {
5979 if ($realfile =~ m@^drivers/@) {
5981 "do not use in_atomic in drivers\n" . $herecurr);
5982 } elsif ($realfile !~ m@^kernel/@) {
5984 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5988 # check for lockdep_set_novalidate_class
5989 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5990 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5991 if ($realfile !~ m@^kernel/lockdep@ &&
5992 $realfile !~ m@^include/linux/lockdep@ &&
5993 $realfile !~ m@^drivers/base/core@) {
5995 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5999 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6000 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6001 WARN("EXPORTED_WORLD_WRITABLE",
6002 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6005 # Mode permission misuses where it seems decimal should be octal
6006 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6007 if ($^V && $^V ge 5.10.0 &&
6008 $line =~ /$mode_perms_search/) {
6009 foreach my $entry (@mode_permission_funcs) {
6010 my $func = $entry->[0];
6011 my $arg_pos = $entry->[1];
6016 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6018 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
6019 if ($line =~ /$test/) {
6021 $val = $6 if ($skip_args ne "");
6023 if ($val !~ /^0$/ &&
6024 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6025 length($val) ne 4)) {
6026 ERROR("NON_OCTAL_PERMISSIONS",
6027 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
6028 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6029 ERROR("EXPORTED_WORLD_WRITABLE",
6030 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6036 # validate content of MODULE_LICENSE against list from include/linux/module.h
6037 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6038 my $extracted_string = get_quoted_string($line, $rawline);
6039 my $valid_licenses = qr{
6042 GPL\ and\ additional\ rights|
6048 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6049 WARN("MODULE_LICENSE",
6050 "unknown module license " . $extracted_string . "\n" . $herecurr);
6055 if ($chk_author && $qca_sign_off && !$codeaurora_sign_off) {
6056 WARN("BAD_SIGN_OFF",
6057 "QCA Signed-off-by requires CODEAURORA Signed-off-by\n" . $line );
6060 # If we have no input at all, then there is nothing to report on
6061 # so just keep quiet.
6062 if ($#rawlines == -1) {
6066 # In mailback mode only produce a report in the negative, for
6067 # things that appear to be patches.
6068 if ($mailback && ($clean == 1 || !$is_patch)) {
6072 # This is not a patch, and we are are in 'no-patch' mode so
6074 if (!$chk_patch && !$is_patch) {
6078 if (!$is_patch && $file !~ /cover-letter\.patch$/) {
6079 ERROR("NOT_UNIFIED_DIFF",
6080 "Does not appear to be a unified-diff format patch\n");
6082 if ($is_patch && $filename ne '-' && $chk_signoff && $signoff == 0) {
6083 ERROR("MISSING_SIGN_OFF",
6084 "Missing Signed-off-by: line(s)\n");
6087 print report_dump();
6088 if ($summary && !($clean == 1 && $quiet == 1)) {
6089 print "$filename " if ($summary_file);
6090 print "total: $cnt_error errors, $cnt_warn warnings, " .
6091 (($check)? "$cnt_chk checks, " : "") .
6092 "$cnt_lines lines checked\n";
6096 # If there were whitespace errors which cleanpatch can fix
6097 # then suggest that.
6098 if ($rpt_cleaners) {
6102 NOTE: Whitespace errors detected.
6103 You may wish to use scripts/cleanpatch or scripts/cleanfile
6108 if ($clean == 0 && $fix &&
6109 ("@rawlines" ne "@fixed" ||
6110 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6111 my $newfile = $filename;
6112 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6116 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6118 open($f, '>', $newfile)
6119 or die "$P: Can't open $newfile for write\n";
6120 foreach my $fixed_line (@fixed) {
6123 if ($linecount > 3) {
6124 $fixed_line =~ s/^\+//;
6125 print $f $fixed_line . "\n";
6128 print $f $fixed_line . "\n";
6136 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6138 Do _NOT_ trust the results written to this file.
6139 Do _NOT_ submit these changes without inspecting them for correctness.
6141 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6142 No warranties, expressed or implied...
6150 print "$vname has no obvious style problems and is ready for submission.\n";
6152 print "$vname has style problems, please review.\n";