1#!/usr/bin/env perl 2# SPDX-License-Identifier: GPL-2.0 3# 4# (c) 2001, Dave Jones. (the file handling bit) 5# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit) 6# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite) 7# (c) 2008-2010 Andy Whitcroft <apw@canonical.com> 8# (c) 2010-2018 Joe Perches <joe@perches.com> 9 10use strict; 11use warnings; 12use POSIX; 13use File::Basename; 14use Cwd 'abs_path'; 15use Term::ANSIColor qw(:constants); 16use Encode qw(decode encode); 17 18my $P = $0; 19my $D = dirname(abs_path($P)); 20 21my $V = '0.32'; 22 23use Getopt::Long qw(:config no_auto_abbrev); 24 25my $quiet = 0; 26my $verbose = 0; 27my %verbose_messages = (); 28my %verbose_emitted = (); 29my $tree = 1; 30my $chk_signoff = 1; 31my $chk_patch = 1; 32my $tst_only; 33my $emacs = 0; 34my $terse = 0; 35my $showfile = 0; 36my $file = 0; 37my $git = 0; 38my %git_commits = (); 39my $check = 0; 40my $check_orig = 0; 41my $summary = 1; 42my $mailback = 0; 43my $summary_file = 0; 44my $show_types = 0; 45my $list_types = 0; 46my $fix = 0; 47my $fix_inplace = 0; 48my $root; 49my $gitroot = $ENV{'GIT_DIR'}; 50$gitroot = ".git" if !defined($gitroot); 51my %debug; 52my %camelcase = (); 53my %use_type = (); 54my @use = (); 55my %ignore_type = (); 56my @ignore = (); 57my $help = 0; 58my $configuration_file = ".checkpatch.conf"; 59my $max_line_length = 100; 60my $ignore_perl_version = 0; 61my $minimum_perl_version = 5.10.0; 62my $min_conf_desc_length = 4; 63my $spelling_file = "$D/spelling.txt"; 64my $codespell = 0; 65my $codespellfile = "/usr/share/codespell/dictionary.txt"; 66my $user_codespellfile = ""; 67my $conststructsfile = "$D/const_structs.checkpatch"; 68my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst"; 69my $typedefsfile; 70my $color = "auto"; 71my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE 72# git output parsing needs US English output, so first set backtick child process LANGUAGE 73my $git_command ='export LANGUAGE=en_US.UTF-8; git'; 74my $tabsize = 8; 75my ${CONFIG_} = "CONFIG_"; 76 77sub help { 78 my ($exitcode) = @_; 79 80 print << "EOM"; 81Usage: $P [OPTION]... [FILE]... 82Version: $V 83 84Options: 85 -q, --quiet quiet 86 -v, --verbose verbose mode 87 --no-tree run without a kernel tree 88 --no-signoff do not check for 'Signed-off-by' line 89 --patch treat FILE as patchfile (default) 90 --emacs emacs compile window format 91 --terse one line per report 92 --showfile emit diffed file position, not input file position 93 -g, --git treat FILE as a single commit or git revision range 94 single git commit with: 95 <rev> 96 <rev>^ 97 <rev>~n 98 multiple git commits with: 99 <rev1>..<rev2> 100 <rev1>...<rev2> 101 <rev>-<count> 102 git merges are ignored 103 -f, --file treat FILE as regular source file 104 --subjective, --strict enable more subjective tests 105 --list-types list the possible message types 106 --types TYPE(,TYPE2...) show only these comma separated message types 107 --ignore TYPE(,TYPE2...) ignore various comma separated message types 108 --show-types show the specific message type in the output 109 --max-line-length=n set the maximum line length, (default $max_line_length) 110 if exceeded, warn on patches 111 requires --strict for use with --file 112 --min-conf-desc-length=n set the min description length, if shorter, warn 113 --tab-size=n set the number of spaces for tab (default $tabsize) 114 --root=PATH PATH to the kernel tree root 115 --no-summary suppress the per-file summary 116 --mailback only produce a report in case of warnings/errors 117 --summary-file include the filename in summary 118 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of 119 'values', 'possible', 'type', and 'attr' (default 120 is all off) 121 --test-only=WORD report only warnings/errors containing WORD 122 literally 123 --fix EXPERIMENTAL - may create horrible results 124 If correctable single-line errors exist, create 125 "<inputfile>.EXPERIMENTAL-checkpatch-fixes" 126 with potential errors corrected to the preferred 127 checkpatch style 128 --fix-inplace EXPERIMENTAL - may create horrible results 129 Is the same as --fix, but overwrites the input 130 file. It's your fault if there's no backup or git 131 --ignore-perl-version override checking of perl version. expect 132 runtime errors. 133 --codespell Use the codespell dictionary for spelling/typos 134 (default:$codespellfile) 135 --codespellfile Use this codespell dictionary 136 --typedefsfile Read additional types from this file 137 --color[=WHEN] Use colors 'always', 'never', or only when output 138 is a terminal ('auto'). Default is 'auto'. 139 --kconfig-prefix=WORD use WORD as a prefix for Kconfig symbols (default 140 ${CONFIG_}) 141 -h, --help, --version display this help and exit 142 143When FILE is - read standard input. 144EOM 145 146 exit($exitcode); 147} 148 149sub uniq { 150 my %seen; 151 return grep { !$seen{$_}++ } @_; 152} 153 154sub list_types { 155 my ($exitcode) = @_; 156 157 my $count = 0; 158 159 local $/ = undef; 160 161 open(my $script, '<', abs_path($P)) or 162 die "$P: Can't read '$P' $!\n"; 163 164 my $text = <$script>; 165 close($script); 166 167 my %types = (); 168 # Also catch when type or level is passed through a variable 169 while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) { 170 if (defined($1)) { 171 if (exists($types{$2})) { 172 $types{$2} .= ",$1" if ($types{$2} ne $1); 173 } else { 174 $types{$2} = $1; 175 } 176 } else { 177 $types{$2} = "UNDETERMINED"; 178 } 179 } 180 181 print("#\tMessage type\n\n"); 182 if ($color) { 183 print(" ( Color coding: "); 184 print(RED . "ERROR" . RESET); 185 print(" | "); 186 print(YELLOW . "WARNING" . RESET); 187 print(" | "); 188 print(GREEN . "CHECK" . RESET); 189 print(" | "); 190 print("Multiple levels / Undetermined"); 191 print(" )\n\n"); 192 } 193 194 foreach my $type (sort keys %types) { 195 my $orig_type = $type; 196 if ($color) { 197 my $level = $types{$type}; 198 if ($level eq "ERROR") { 199 $type = RED . $type . RESET; 200 } elsif ($level eq "WARN") { 201 $type = YELLOW . $type . RESET; 202 } elsif ($level eq "CHK") { 203 $type = GREEN . $type . RESET; 204 } 205 } 206 print(++$count . "\t" . $type . "\n"); 207 if ($verbose && exists($verbose_messages{$orig_type})) { 208 my $message = $verbose_messages{$orig_type}; 209 $message =~ s/\n/\n\t/g; 210 print("\t" . $message . "\n\n"); 211 } 212 } 213 214 exit($exitcode); 215} 216 217my $conf = which_conf($configuration_file); 218if (-f $conf) { 219 my @conf_args; 220 open(my $conffile, '<', "$conf") 221 or warn "$P: Can't find a readable $configuration_file file $!\n"; 222 223 while (<$conffile>) { 224 my $line = $_; 225 226 $line =~ s/\s*\n?$//g; 227 $line =~ s/^\s*//g; 228 $line =~ s/\s+/ /g; 229 230 next if ($line =~ m/^\s*#/); 231 next if ($line =~ m/^\s*$/); 232 233 my @words = split(" ", $line); 234 foreach my $word (@words) { 235 last if ($word =~ m/^#/); 236 push (@conf_args, $word); 237 } 238 } 239 close($conffile); 240 unshift(@ARGV, @conf_args) if @conf_args; 241} 242 243sub load_docs { 244 open(my $docs, '<', "$docsfile") 245 or warn "$P: Can't read the documentation file $docsfile $!\n"; 246 247 my $type = ''; 248 my $desc = ''; 249 my $in_desc = 0; 250 251 while (<$docs>) { 252 chomp; 253 my $line = $_; 254 $line =~ s/\s+$//; 255 256 if ($line =~ /^\s*\*\*(.+)\*\*$/) { 257 if ($desc ne '') { 258 $verbose_messages{$type} = trim($desc); 259 } 260 $type = $1; 261 $desc = ''; 262 $in_desc = 1; 263 } elsif ($in_desc) { 264 if ($line =~ /^(?:\s{4,}|$)/) { 265 $line =~ s/^\s{4}//; 266 $desc .= $line; 267 $desc .= "\n"; 268 } else { 269 $verbose_messages{$type} = trim($desc); 270 $type = ''; 271 $desc = ''; 272 $in_desc = 0; 273 } 274 } 275 } 276 277 if ($desc ne '') { 278 $verbose_messages{$type} = trim($desc); 279 } 280 close($docs); 281} 282 283# Perl's Getopt::Long allows options to take optional arguments after a space. 284# Prevent --color by itself from consuming other arguments 285foreach (@ARGV) { 286 if ($_ eq "--color" || $_ eq "-color") { 287 $_ = "--color=$color"; 288 } 289} 290 291GetOptions( 292 'q|quiet+' => \$quiet, 293 'v|verbose!' => \$verbose, 294 'tree!' => \$tree, 295 'signoff!' => \$chk_signoff, 296 'patch!' => \$chk_patch, 297 'emacs!' => \$emacs, 298 'terse!' => \$terse, 299 'showfile!' => \$showfile, 300 'f|file!' => \$file, 301 'g|git!' => \$git, 302 'subjective!' => \$check, 303 'strict!' => \$check, 304 'ignore=s' => \@ignore, 305 'types=s' => \@use, 306 'show-types!' => \$show_types, 307 'list-types!' => \$list_types, 308 'max-line-length=i' => \$max_line_length, 309 'min-conf-desc-length=i' => \$min_conf_desc_length, 310 'tab-size=i' => \$tabsize, 311 'root=s' => \$root, 312 'summary!' => \$summary, 313 'mailback!' => \$mailback, 314 'summary-file!' => \$summary_file, 315 'fix!' => \$fix, 316 'fix-inplace!' => \$fix_inplace, 317 'ignore-perl-version!' => \$ignore_perl_version, 318 'debug=s' => \%debug, 319 'test-only=s' => \$tst_only, 320 'codespell!' => \$codespell, 321 'codespellfile=s' => \$user_codespellfile, 322 'typedefsfile=s' => \$typedefsfile, 323 'color=s' => \$color, 324 'no-color' => \$color, #keep old behaviors of -nocolor 325 'nocolor' => \$color, #keep old behaviors of -nocolor 326 'kconfig-prefix=s' => \${CONFIG_}, 327 'h|help' => \$help, 328 'version' => \$help 329) or $help = 2; 330 331if ($user_codespellfile) { 332 # Use the user provided codespell file unconditionally 333 $codespellfile = $user_codespellfile; 334} elsif (!(-f $codespellfile)) { 335 # If /usr/share/codespell/dictionary.txt is not present, try to find it 336 # under codespell's install directory: <codespell_root>/data/dictionary.txt 337 if (($codespell || $help) && which("python3") ne "") { 338 my $python_codespell_dict = << "EOF"; 339 340import os.path as op 341import codespell_lib 342codespell_dir = op.dirname(codespell_lib.__file__) 343codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt') 344print(codespell_file, end='') 345EOF 346 347 my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`; 348 $codespellfile = $codespell_dict if (-f $codespell_dict); 349 } 350} 351 352# $help is 1 if either -h, --help or --version is passed as option - exitcode: 0 353# $help is 2 if invalid option is passed - exitcode: 1 354help($help - 1) if ($help); 355 356die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix)); 357die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse); 358 359if ($color =~ /^[01]$/) { 360 $color = !$color; 361} elsif ($color =~ /^always$/i) { 362 $color = 1; 363} elsif ($color =~ /^never$/i) { 364 $color = 0; 365} elsif ($color =~ /^auto$/i) { 366 $color = (-t STDOUT); 367} else { 368 die "$P: Invalid color mode: $color\n"; 369} 370 371load_docs() if ($verbose); 372list_types(0) if ($list_types); 373 374$fix = 1 if ($fix_inplace); 375$check_orig = $check; 376 377my $exit = 0; 378 379my $perl_version_ok = 1; 380if ($^V && $^V lt $minimum_perl_version) { 381 $perl_version_ok = 0; 382 printf "$P: requires at least perl version %vd\n", $minimum_perl_version; 383 exit(1) if (!$ignore_perl_version); 384} 385 386#if no filenames are given, push '-' to read patch from stdin 387if ($#ARGV < 0) { 388 push(@ARGV, '-'); 389} 390 391# skip TAB size 1 to avoid additional checks on $tabsize - 1 392die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2); 393 394sub hash_save_array_words { 395 my ($hashRef, $arrayRef) = @_; 396 397 my @array = split(/,/, join(',', @$arrayRef)); 398 foreach my $word (@array) { 399 $word =~ s/\s*\n?$//g; 400 $word =~ s/^\s*//g; 401 $word =~ s/\s+/ /g; 402 $word =~ tr/[a-z]/[A-Z]/; 403 404 next if ($word =~ m/^\s*#/); 405 next if ($word =~ m/^\s*$/); 406 407 $hashRef->{$word}++; 408 } 409} 410 411sub hash_show_words { 412 my ($hashRef, $prefix) = @_; 413 414 if (keys %$hashRef) { 415 print "\nNOTE: $prefix message types:"; 416 foreach my $word (sort keys %$hashRef) { 417 print " $word"; 418 } 419 print "\n"; 420 } 421} 422 423hash_save_array_words(\%ignore_type, \@ignore); 424hash_save_array_words(\%use_type, \@use); 425 426my $dbg_values = 0; 427my $dbg_possible = 0; 428my $dbg_type = 0; 429my $dbg_attr = 0; 430for my $key (keys %debug) { 431 ## no critic 432 eval "\${dbg_$key} = '$debug{$key}';"; 433 die "$@" if ($@); 434} 435 436my $rpt_cleaners = 0; 437 438if ($terse) { 439 $emacs = 1; 440 $quiet++; 441} 442 443if ($tree) { 444 if (defined $root) { 445 if (!top_of_kernel_tree($root)) { 446 die "$P: $root: --root does not point at a valid tree\n"; 447 } 448 } else { 449 if (top_of_kernel_tree('.')) { 450 $root = '.'; 451 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ && 452 top_of_kernel_tree($1)) { 453 $root = $1; 454 } 455 } 456 457 if (!defined $root) { 458 print "Must be run from the top-level dir. of a kernel tree\n"; 459 exit(2); 460 } 461} 462 463my $emitted_corrupt = 0; 464 465our $Ident = qr{ 466 [A-Za-z_][A-Za-z\d_]* 467 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)* 468 }x; 469our $Storage = qr{extern|static|asmlinkage}; 470our $Sparse = qr{ 471 __user| 472 __kernel| 473 __force| 474 __iomem| 475 __must_check| 476 __kprobes| 477 __ref| 478 __refconst| 479 __refdata| 480 __rcu| 481 __private 482 }x; 483our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)}; 484our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)}; 485our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)}; 486our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)}; 487our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit}; 488 489# Notes to $Attribute: 490# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check 491our $Attribute = qr{ 492 const| 493 volatile| 494 __percpu| 495 __nocast| 496 __safe| 497 __bitwise| 498 __packed__| 499 __packed2__| 500 __naked| 501 __maybe_unused| 502 __always_unused| 503 __noreturn| 504 __used| 505 __cold| 506 __pure| 507 __noclone| 508 __deprecated| 509 __read_mostly| 510 __ro_after_init| 511 __kprobes| 512 $InitAttribute| 513 ____cacheline_aligned| 514 ____cacheline_aligned_in_smp| 515 ____cacheline_internodealigned_in_smp| 516 __weak| 517 __alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\) 518 }x; 519our $Modifier; 520our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__}; 521our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]}; 522our $Lval = qr{$Ident(?:$Member)*}; 523 524our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u}; 525our $Binary = qr{(?i)0b[01]+$Int_type?}; 526our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?}; 527our $Int = qr{[0-9]+$Int_type?}; 528our $Octal = qr{0[0-7]+$Int_type?}; 529our $String = qr{(?:\b[Lu])?"[X\t]*"}; 530our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?}; 531our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?}; 532our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?}; 533our $Float = qr{$Float_hex|$Float_dec|$Float_int}; 534our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int}; 535our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=}; 536our $Compare = qr{<=|>=|==|!=|<|(?<!-)>}; 537our $Arithmetic = qr{\+|-|\*|\/|%}; 538our $Operators = qr{ 539 <=|>=|==|!=| 540 =>|->|<<|>>|<|>|!|~| 541 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic 542 }x; 543 544our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x; 545 546our $BasicType; 547our $NonptrType; 548our $NonptrTypeMisordered; 549our $NonptrTypeWithAttr; 550our $Type; 551our $TypeMisordered; 552our $Declare; 553our $DeclareMisordered; 554 555our $NON_ASCII_UTF8 = qr{ 556 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte 557 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs 558 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte 559 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates 560 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 561 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 562 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 563}x; 564 565our $UTF8 = qr{ 566 [\x09\x0A\x0D\x20-\x7E] # ASCII 567 | $NON_ASCII_UTF8 568}x; 569 570our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t}; 571our $typeOtherOSTypedefs = qr{(?x: 572 u_(?:char|short|int|long) | # bsd 573 u(?:nchar|short|int|long) # sysv 574)}; 575our $typeKernelTypedefs = qr{(?x: 576 (?:__)?(?:u|s|be|le)(?:8|16|32|64)| 577 atomic_t 578)}; 579our $typeStdioTypedefs = qr{(?x: 580 FILE 581)}; 582our $typeTypedefs = qr{(?x: 583 $typeC99Typedefs\b| 584 $typeOtherOSTypedefs\b| 585 $typeKernelTypedefs\b| 586 $typeStdioTypedefs\b 587)}; 588 589our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b}; 590 591our $logFunctions = qr{(?x: 592 printk(?:_ratelimited|_once|_deferred_once|_deferred|)| 593 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)| 594 TP_printk| 595 WARN(?:_RATELIMIT|_ONCE|)| 596 panic| 597 MODULE_[A-Z_]+| 598 seq_vprintf|seq_printf|seq_puts 599)}; 600 601our $allocFunctions = qr{(?x: 602 (?:(?:devm_)? 603 (?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? | 604 kstrdup(?:_const)? | 605 kmemdup(?:_nul)?) | 606 (?:\w+)?alloc_skb(?:_ip_align)? | 607 # dev_alloc_skb/netdev_alloc_skb, et al 608 dma_alloc_coherent 609)}; 610 611our $signature_tags = qr{(?xi: 612 Signed-off-by:| 613 Co-developed-by:| 614 Acked-by:| 615 Tested-by:| 616 Reviewed-by:| 617 Reported-by:| 618 Suggested-by:| 619 To:| 620 Cc: 621)}; 622 623our $tracing_logging_tags = qr{(?xi: 624 [=-]*> | 625 <[=-]* | 626 \[ | 627 \] | 628 start | 629 called | 630 entered | 631 entry | 632 enter | 633 in | 634 inside | 635 here | 636 begin | 637 exit | 638 end | 639 done | 640 leave | 641 completed | 642 out | 643 return | 644 [\.\!:\s]* 645)}; 646 647sub edit_distance_min { 648 my (@arr) = @_; 649 my $len = scalar @arr; 650 if ((scalar @arr) < 1) { 651 # if underflow, return 652 return; 653 } 654 my $min = $arr[0]; 655 for my $i (0 .. ($len-1)) { 656 if ($arr[$i] < $min) { 657 $min = $arr[$i]; 658 } 659 } 660 return $min; 661} 662 663sub get_edit_distance { 664 my ($str1, $str2) = @_; 665 $str1 = lc($str1); 666 $str2 = lc($str2); 667 $str1 =~ s/-//g; 668 $str2 =~ s/-//g; 669 my $len1 = length($str1); 670 my $len2 = length($str2); 671 # two dimensional array storing minimum edit distance 672 my @distance; 673 for my $i (0 .. $len1) { 674 for my $j (0 .. $len2) { 675 if ($i == 0) { 676 $distance[$i][$j] = $j; 677 } elsif ($j == 0) { 678 $distance[$i][$j] = $i; 679 } elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) { 680 $distance[$i][$j] = $distance[$i - 1][$j - 1]; 681 } else { 682 my $dist1 = $distance[$i][$j - 1]; #insert distance 683 my $dist2 = $distance[$i - 1][$j]; # remove 684 my $dist3 = $distance[$i - 1][$j - 1]; #replace 685 $distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3); 686 } 687 } 688 } 689 return $distance[$len1][$len2]; 690} 691 692sub find_standard_signature { 693 my ($sign_off) = @_; 694 my @standard_signature_tags = ( 695 'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:', 696 'Reviewed-by:', 'Reported-by:', 'Suggested-by:' 697 ); 698 foreach my $signature (@standard_signature_tags) { 699 return $signature if (get_edit_distance($sign_off, $signature) <= 2); 700 } 701 702 return ""; 703} 704 705our @typeListMisordered = ( 706 qr{char\s+(?:un)?signed}, 707 qr{int\s+(?:(?:un)?signed\s+)?short\s}, 708 qr{int\s+short(?:\s+(?:un)?signed)}, 709 qr{short\s+int(?:\s+(?:un)?signed)}, 710 qr{(?:un)?signed\s+int\s+short}, 711 qr{short\s+(?:un)?signed}, 712 qr{long\s+int\s+(?:un)?signed}, 713 qr{int\s+long\s+(?:un)?signed}, 714 qr{long\s+(?:un)?signed\s+int}, 715 qr{int\s+(?:un)?signed\s+long}, 716 qr{int\s+(?:un)?signed}, 717 qr{int\s+long\s+long\s+(?:un)?signed}, 718 qr{long\s+long\s+int\s+(?:un)?signed}, 719 qr{long\s+long\s+(?:un)?signed\s+int}, 720 qr{long\s+long\s+(?:un)?signed}, 721 qr{long\s+(?:un)?signed}, 722); 723 724our @typeList = ( 725 qr{void}, 726 qr{(?:(?:un)?signed\s+)?char}, 727 qr{(?:(?:un)?signed\s+)?short\s+int}, 728 qr{(?:(?:un)?signed\s+)?short}, 729 qr{(?:(?:un)?signed\s+)?int}, 730 qr{(?:(?:un)?signed\s+)?long\s+int}, 731 qr{(?:(?:un)?signed\s+)?long\s+long\s+int}, 732 qr{(?:(?:un)?signed\s+)?long\s+long}, 733 qr{(?:(?:un)?signed\s+)?long}, 734 qr{(?:un)?signed}, 735 qr{float}, 736 qr{double}, 737 qr{bool}, 738 qr{struct\s+$Ident}, 739 qr{union\s+$Ident}, 740 qr{enum\s+$Ident}, 741 qr{${Ident}_t}, 742 qr{${Ident}_handler}, 743 qr{${Ident}_handler_fn}, 744 @typeListMisordered, 745); 746 747our $C90_int_types = qr{(?x: 748 long\s+long\s+int\s+(?:un)?signed| 749 long\s+long\s+(?:un)?signed\s+int| 750 long\s+long\s+(?:un)?signed| 751 (?:(?:un)?signed\s+)?long\s+long\s+int| 752 (?:(?:un)?signed\s+)?long\s+long| 753 int\s+long\s+long\s+(?:un)?signed| 754 int\s+(?:(?:un)?signed\s+)?long\s+long| 755 756 long\s+int\s+(?:un)?signed| 757 long\s+(?:un)?signed\s+int| 758 long\s+(?:un)?signed| 759 (?:(?:un)?signed\s+)?long\s+int| 760 (?:(?:un)?signed\s+)?long| 761 int\s+long\s+(?:un)?signed| 762 int\s+(?:(?:un)?signed\s+)?long| 763 764 int\s+(?:un)?signed| 765 (?:(?:un)?signed\s+)?int 766)}; 767 768our @typeListFile = (); 769our @typeListWithAttr = ( 770 @typeList, 771 qr{struct\s+$InitAttribute\s+$Ident}, 772 qr{union\s+$InitAttribute\s+$Ident}, 773); 774 775our @modifierList = ( 776 qr{fastcall}, 777); 778our @modifierListFile = (); 779 780our @mode_permission_funcs = ( 781 ["module_param", 3], 782 ["module_param_(?:array|named|string)", 4], 783 ["module_param_array_named", 5], 784 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2], 785 ["proc_create(?:_data|)", 2], 786 ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2], 787 ["IIO_DEV_ATTR_[A-Z_]+", 1], 788 ["SENSOR_(?:DEVICE_|)ATTR_2", 2], 789 ["SENSOR_TEMPLATE(?:_2|)", 3], 790 ["__ATTR", 2], 791); 792 793my $word_pattern = '\b[A-Z]?[a-z]{2,}\b'; 794 795#Create a search pattern for all these functions to speed up a loop below 796our $mode_perms_search = ""; 797foreach my $entry (@mode_permission_funcs) { 798 $mode_perms_search .= '|' if ($mode_perms_search ne ""); 799 $mode_perms_search .= $entry->[0]; 800} 801$mode_perms_search = "(?:${mode_perms_search})"; 802 803our %deprecated_apis = ( 804 "synchronize_rcu_bh" => "synchronize_rcu", 805 "synchronize_rcu_bh_expedited" => "synchronize_rcu_expedited", 806 "call_rcu_bh" => "call_rcu", 807 "rcu_barrier_bh" => "rcu_barrier", 808 "synchronize_sched" => "synchronize_rcu", 809 "synchronize_sched_expedited" => "synchronize_rcu_expedited", 810 "call_rcu_sched" => "call_rcu", 811 "rcu_barrier_sched" => "rcu_barrier", 812 "get_state_synchronize_sched" => "get_state_synchronize_rcu", 813 "cond_synchronize_sched" => "cond_synchronize_rcu", 814 "kmap" => "kmap_local_page", 815 "kmap_atomic" => "kmap_local_page", 816); 817 818#Create a search pattern for all these strings to speed up a loop below 819our $deprecated_apis_search = ""; 820foreach my $entry (keys %deprecated_apis) { 821 $deprecated_apis_search .= '|' if ($deprecated_apis_search ne ""); 822 $deprecated_apis_search .= $entry; 823} 824$deprecated_apis_search = "(?:${deprecated_apis_search})"; 825 826our $mode_perms_world_writable = qr{ 827 S_IWUGO | 828 S_IWOTH | 829 S_IRWXUGO | 830 S_IALLUGO | 831 0[0-7][0-7][2367] 832}x; 833 834our %mode_permission_string_types = ( 835 "S_IRWXU" => 0700, 836 "S_IRUSR" => 0400, 837 "S_IWUSR" => 0200, 838 "S_IXUSR" => 0100, 839 "S_IRWXG" => 0070, 840 "S_IRGRP" => 0040, 841 "S_IWGRP" => 0020, 842 "S_IXGRP" => 0010, 843 "S_IRWXO" => 0007, 844 "S_IROTH" => 0004, 845 "S_IWOTH" => 0002, 846 "S_IXOTH" => 0001, 847 "S_IRWXUGO" => 0777, 848 "S_IRUGO" => 0444, 849 "S_IWUGO" => 0222, 850 "S_IXUGO" => 0111, 851); 852 853#Create a search pattern for all these strings to speed up a loop below 854our $mode_perms_string_search = ""; 855foreach my $entry (keys %mode_permission_string_types) { 856 $mode_perms_string_search .= '|' if ($mode_perms_string_search ne ""); 857 $mode_perms_string_search .= $entry; 858} 859our $single_mode_perms_string_search = "(?:${mode_perms_string_search})"; 860our $multi_mode_perms_string_search = qr{ 861 ${single_mode_perms_string_search} 862 (?:\s*\|\s*${single_mode_perms_string_search})* 863}x; 864 865sub perms_to_octal { 866 my ($string) = @_; 867 868 return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/); 869 870 my $val = ""; 871 my $oval = ""; 872 my $to = 0; 873 my $curpos = 0; 874 my $lastpos = 0; 875 while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) { 876 $curpos = pos($string); 877 my $match = $2; 878 my $omatch = $1; 879 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos)); 880 $lastpos = $curpos; 881 $to |= $mode_permission_string_types{$match}; 882 $val .= '\s*\|\s*' if ($val ne ""); 883 $val .= $match; 884 $oval .= $omatch; 885 } 886 $oval =~ s/^\s*\|\s*//; 887 $oval =~ s/\s*\|\s*$//; 888 return sprintf("%04o", $to); 889} 890 891our $allowed_asm_includes = qr{(?x: 892 irq| 893 memory| 894 time| 895 reboot 896)}; 897# memory.h: ARM has a custom one 898 899# Load common spelling mistakes and build regular expression list. 900my $misspellings; 901my %spelling_fix; 902 903if (open(my $spelling, '<', $spelling_file)) { 904 while (<$spelling>) { 905 my $line = $_; 906 907 $line =~ s/\s*\n?$//g; 908 $line =~ s/^\s*//g; 909 910 next if ($line =~ m/^\s*#/); 911 next if ($line =~ m/^\s*$/); 912 913 my ($suspect, $fix) = split(/\|\|/, $line); 914 915 $spelling_fix{$suspect} = $fix; 916 } 917 close($spelling); 918} else { 919 warn "No typos will be found - file '$spelling_file': $!\n"; 920} 921 922if ($codespell) { 923 if (open(my $spelling, '<', $codespellfile)) { 924 while (<$spelling>) { 925 my $line = $_; 926 927 $line =~ s/\s*\n?$//g; 928 $line =~ s/^\s*//g; 929 930 next if ($line =~ m/^\s*#/); 931 next if ($line =~ m/^\s*$/); 932 next if ($line =~ m/, disabled/i); 933 934 $line =~ s/,.*$//; 935 936 my ($suspect, $fix) = split(/->/, $line); 937 938 $spelling_fix{$suspect} = $fix; 939 } 940 close($spelling); 941 } else { 942 warn "No codespell typos will be found - file '$codespellfile': $!\n"; 943 } 944} 945 946$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix; 947 948sub read_words { 949 my ($wordsRef, $file) = @_; 950 951 if (open(my $words, '<', $file)) { 952 while (<$words>) { 953 my $line = $_; 954 955 $line =~ s/\s*\n?$//g; 956 $line =~ s/^\s*//g; 957 958 next if ($line =~ m/^\s*#/); 959 next if ($line =~ m/^\s*$/); 960 if ($line =~ /\s/) { 961 print("$file: '$line' invalid - ignored\n"); 962 next; 963 } 964 965 $$wordsRef .= '|' if (defined $$wordsRef); 966 $$wordsRef .= $line; 967 } 968 close($file); 969 return 1; 970 } 971 972 return 0; 973} 974 975my $const_structs; 976if (show_type("CONST_STRUCT")) { 977 read_words(\$const_structs, $conststructsfile) 978 or warn "No structs that should be const will be found - file '$conststructsfile': $!\n"; 979} 980 981if (defined($typedefsfile)) { 982 my $typeOtherTypedefs; 983 read_words(\$typeOtherTypedefs, $typedefsfile) 984 or warn "No additional types will be considered - file '$typedefsfile': $!\n"; 985 $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs); 986} 987 988sub build_types { 989 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)"; 990 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)"; 991 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)"; 992 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)"; 993 $Modifier = qr{(?:$Attribute|$Sparse|$mods)}; 994 $BasicType = qr{ 995 (?:$typeTypedefs\b)| 996 (?:${all}\b) 997 }x; 998 $NonptrType = qr{ 999 (?:$Modifier\s+|const\s+)* 1000 (?: 1001 (?:typeof|__typeof__)\s*\([^\)]*\)| 1002 (?:$typeTypedefs\b)| 1003 (?:${all}\b) 1004 ) 1005 (?:\s+$Modifier|\s+const)* 1006 }x; 1007 $NonptrTypeMisordered = qr{ 1008 (?:$Modifier\s+|const\s+)* 1009 (?: 1010 (?:${Misordered}\b) 1011 ) 1012 (?:\s+$Modifier|\s+const)* 1013 }x; 1014 $NonptrTypeWithAttr = qr{ 1015 (?:$Modifier\s+|const\s+)* 1016 (?: 1017 (?:typeof|__typeof__)\s*\([^\)]*\)| 1018 (?:$typeTypedefs\b)| 1019 (?:${allWithAttr}\b) 1020 ) 1021 (?:\s+$Modifier|\s+const)* 1022 }x; 1023 $Type = qr{ 1024 $NonptrType 1025 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4} 1026 (?:\s+$Inline|\s+$Modifier)* 1027 }x; 1028 $TypeMisordered = qr{ 1029 $NonptrTypeMisordered 1030 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4} 1031 (?:\s+$Inline|\s+$Modifier)* 1032 }x; 1033 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type}; 1034 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered}; 1035} 1036build_types(); 1037 1038our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*}; 1039 1040# Using $balanced_parens, $LvalOrFunc, or $FuncArg 1041# requires at least perl version v5.10.0 1042# Any use must be runtime checked with $^V 1043 1044our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/; 1045our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*}; 1046our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)}; 1047 1048our $declaration_macros = qr{(?x: 1049 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(| 1050 (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(| 1051 (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(| 1052 (?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\( 1053)}; 1054 1055our %allow_repeated_words = ( 1056 add => '', 1057 added => '', 1058 bad => '', 1059 be => '', 1060); 1061 1062sub deparenthesize { 1063 my ($string) = @_; 1064 return "" if (!defined($string)); 1065 1066 while ($string =~ /^\s*\(.*\)\s*$/) { 1067 $string =~ s@^\s*\(\s*@@; 1068 $string =~ s@\s*\)\s*$@@; 1069 } 1070 1071 $string =~ s@\s+@ @g; 1072 1073 return $string; 1074} 1075 1076sub seed_camelcase_file { 1077 my ($file) = @_; 1078 1079 return if (!(-f $file)); 1080 1081 local $/; 1082 1083 open(my $include_file, '<', "$file") 1084 or warn "$P: Can't read '$file' $!\n"; 1085 my $text = <$include_file>; 1086 close($include_file); 1087 1088 my @lines = split('\n', $text); 1089 1090 foreach my $line (@lines) { 1091 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/); 1092 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) { 1093 $camelcase{$1} = 1; 1094 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) { 1095 $camelcase{$1} = 1; 1096 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) { 1097 $camelcase{$1} = 1; 1098 } 1099 } 1100} 1101 1102our %maintained_status = (); 1103 1104sub is_maintained_obsolete { 1105 my ($filename) = @_; 1106 1107 return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl")); 1108 1109 if (!exists($maintained_status{$filename})) { 1110 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`; 1111 } 1112 1113 return $maintained_status{$filename} =~ /obsolete/i; 1114} 1115 1116sub is_SPDX_License_valid { 1117 my ($license) = @_; 1118 1119 return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot")); 1120 1121 my $root_path = abs_path($root); 1122 my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`; 1123 return 0 if ($status ne ""); 1124 return 1; 1125} 1126 1127my $camelcase_seeded = 0; 1128sub seed_camelcase_includes { 1129 return if ($camelcase_seeded); 1130 1131 my $files; 1132 my $camelcase_cache = ""; 1133 my @include_files = (); 1134 1135 $camelcase_seeded = 1; 1136 1137 if (-e "$gitroot") { 1138 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`; 1139 chomp $git_last_include_commit; 1140 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit"; 1141 } else { 1142 my $last_mod_date = 0; 1143 $files = `find $root/include -name "*.h"`; 1144 @include_files = split('\n', $files); 1145 foreach my $file (@include_files) { 1146 my $date = POSIX::strftime("%Y%m%d%H%M", 1147 localtime((stat $file)[9])); 1148 $last_mod_date = $date if ($last_mod_date < $date); 1149 } 1150 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date"; 1151 } 1152 1153 if ($camelcase_cache ne "" && -f $camelcase_cache) { 1154 open(my $camelcase_file, '<', "$camelcase_cache") 1155 or warn "$P: Can't read '$camelcase_cache' $!\n"; 1156 while (<$camelcase_file>) { 1157 chomp; 1158 $camelcase{$_} = 1; 1159 } 1160 close($camelcase_file); 1161 1162 return; 1163 } 1164 1165 if (-e "$gitroot") { 1166 $files = `${git_command} ls-files "include/*.h"`; 1167 @include_files = split('\n', $files); 1168 } 1169 1170 foreach my $file (@include_files) { 1171 seed_camelcase_file($file); 1172 } 1173 1174 if ($camelcase_cache ne "") { 1175 unlink glob ".checkpatch-camelcase.*"; 1176 open(my $camelcase_file, '>', "$camelcase_cache") 1177 or warn "$P: Can't write '$camelcase_cache' $!\n"; 1178 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) { 1179 print $camelcase_file ("$_\n"); 1180 } 1181 close($camelcase_file); 1182 } 1183} 1184 1185sub git_is_single_file { 1186 my ($filename) = @_; 1187 1188 return 0 if ((which("git") eq "") || !(-e "$gitroot")); 1189 1190 my $output = `${git_command} ls-files -- $filename 2>/dev/null`; 1191 my $count = $output =~ tr/\n//; 1192 return $count eq 1 && $output =~ m{^${filename}$}; 1193} 1194 1195sub git_commit_info { 1196 my ($commit, $id, $desc) = @_; 1197 1198 return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot")); 1199 1200 my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`; 1201 $output =~ s/^\s*//gm; 1202 my @lines = split("\n", $output); 1203 1204 return ($id, $desc) if ($#lines < 0); 1205 1206 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) { 1207# Maybe one day convert this block of bash into something that returns 1208# all matching commit ids, but it's very slow... 1209# 1210# echo "checking commits $1..." 1211# git rev-list --remotes | grep -i "^$1" | 1212# while read line ; do 1213# git log --format='%H %s' -1 $line | 1214# echo "commit $(cut -c 1-12,41-)" 1215# done 1216 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ || 1217 $lines[0] =~ /^fatal: bad object $commit/) { 1218 $id = undef; 1219 } else { 1220 $id = substr($lines[0], 0, 12); 1221 $desc = substr($lines[0], 41); 1222 } 1223 1224 return ($id, $desc); 1225} 1226 1227$chk_signoff = 0 if ($file); 1228 1229my @rawlines = (); 1230my @lines = (); 1231my @fixed = (); 1232my @fixed_inserted = (); 1233my @fixed_deleted = (); 1234my $fixlinenr = -1; 1235 1236# If input is git commits, extract all commits from the commit expressions. 1237# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'. 1238die "$P: No git repository found\n" if ($git && !-e "$gitroot"); 1239 1240if ($git) { 1241 my @commits = (); 1242 foreach my $commit_expr (@ARGV) { 1243 my $git_range; 1244 if ($commit_expr =~ m/^(.*)-(\d+)$/) { 1245 $git_range = "-$2 $1"; 1246 } elsif ($commit_expr =~ m/\.\./) { 1247 $git_range = "$commit_expr"; 1248 } else { 1249 $git_range = "-1 $commit_expr"; 1250 } 1251 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`; 1252 foreach my $line (split(/\n/, $lines)) { 1253 $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/; 1254 next if (!defined($1) || !defined($2)); 1255 my $sha1 = $1; 1256 my $subject = $2; 1257 unshift(@commits, $sha1); 1258 $git_commits{$sha1} = $subject; 1259 } 1260 } 1261 die "$P: no git commits after extraction!\n" if (@commits == 0); 1262 @ARGV = @commits; 1263} 1264 1265my $vname; 1266$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"}; 1267for my $filename (@ARGV) { 1268 my $FILE; 1269 my $is_git_file = git_is_single_file($filename); 1270 my $oldfile = $file; 1271 $file = 1 if ($is_git_file); 1272 if ($git) { 1273 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") || 1274 die "$P: $filename: git format-patch failed - $!\n"; 1275 } elsif ($file) { 1276 open($FILE, '-|', "diff -u /dev/null $filename") || 1277 die "$P: $filename: diff failed - $!\n"; 1278 } elsif ($filename eq '-') { 1279 open($FILE, '<&STDIN'); 1280 } else { 1281 open($FILE, '<', "$filename") || 1282 die "$P: $filename: open failed - $!\n"; 1283 } 1284 if ($filename eq '-') { 1285 $vname = 'Your patch'; 1286 } elsif ($git) { 1287 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")'; 1288 } else { 1289 $vname = $filename; 1290 } 1291 while (<$FILE>) { 1292 chomp; 1293 push(@rawlines, $_); 1294 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i); 1295 } 1296 close($FILE); 1297 1298 if ($#ARGV > 0 && $quiet == 0) { 1299 print '-' x length($vname) . "\n"; 1300 print "$vname\n"; 1301 print '-' x length($vname) . "\n"; 1302 } 1303 1304 if (!process($filename)) { 1305 $exit = 1; 1306 } 1307 @rawlines = (); 1308 @lines = (); 1309 @fixed = (); 1310 @fixed_inserted = (); 1311 @fixed_deleted = (); 1312 $fixlinenr = -1; 1313 @modifierListFile = (); 1314 @typeListFile = (); 1315 build_types(); 1316 $file = $oldfile if ($is_git_file); 1317} 1318 1319if (!$quiet) { 1320 hash_show_words(\%use_type, "Used"); 1321 hash_show_words(\%ignore_type, "Ignored"); 1322 1323 if (!$perl_version_ok) { 1324 print << "EOM" 1325 1326NOTE: perl $^V is not modern enough to detect all possible issues. 1327 An upgrade to at least perl $minimum_perl_version is suggested. 1328EOM 1329 } 1330 if ($exit) { 1331 print << "EOM" 1332 1333NOTE: If any of the errors are false positives, please report 1334 them to the maintainer, see CHECKPATCH in MAINTAINERS. 1335EOM 1336 } 1337} 1338 1339exit($exit); 1340 1341sub top_of_kernel_tree { 1342 my ($root) = @_; 1343 1344 my @tree_check = ( 1345 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile", 1346 "README", "Documentation", "arch", "include", "drivers", 1347 "fs", "init", "ipc", "kernel", "lib", "scripts", 1348 ); 1349 1350 foreach my $check (@tree_check) { 1351 if (! -e $root . '/' . $check) { 1352 return 0; 1353 } 1354 } 1355 return 1; 1356} 1357 1358sub parse_email { 1359 my ($formatted_email) = @_; 1360 1361 my $name = ""; 1362 my $quoted = ""; 1363 my $name_comment = ""; 1364 my $address = ""; 1365 my $comment = ""; 1366 1367 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) { 1368 $name = $1; 1369 $address = $2; 1370 $comment = $3 if defined $3; 1371 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) { 1372 $address = $1; 1373 $comment = $2 if defined $2; 1374 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) { 1375 $address = $1; 1376 $comment = $2 if defined $2; 1377 $formatted_email =~ s/\Q$address\E.*$//; 1378 $name = $formatted_email; 1379 $name = trim($name); 1380 $name =~ s/^\"|\"$//g; 1381 # If there's a name left after stripping spaces and 1382 # leading quotes, and the address doesn't have both 1383 # leading and trailing angle brackets, the address 1384 # is invalid. ie: 1385 # "joe smith joe@smith.com" bad 1386 # "joe smith <joe@smith.com" bad 1387 if ($name ne "" && $address !~ /^<[^>]+>$/) { 1388 $name = ""; 1389 $address = ""; 1390 $comment = ""; 1391 } 1392 } 1393 1394 # Extract comments from names excluding quoted parts 1395 # "John D. (Doe)" - Do not extract 1396 if ($name =~ s/\"(.+)\"//) { 1397 $quoted = $1; 1398 } 1399 while ($name =~ s/\s*($balanced_parens)\s*/ /) { 1400 $name_comment .= trim($1); 1401 } 1402 $name =~ s/^[ \"]+|[ \"]+$//g; 1403 $name = trim("$quoted $name"); 1404 1405 $address = trim($address); 1406 $address =~ s/^\<|\>$//g; 1407 $comment = trim($comment); 1408 1409 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars 1410 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes 1411 $name = "\"$name\""; 1412 } 1413 1414 return ($name, $name_comment, $address, $comment); 1415} 1416 1417sub format_email { 1418 my ($name, $name_comment, $address, $comment) = @_; 1419 1420 my $formatted_email; 1421 1422 $name =~ s/^[ \"]+|[ \"]+$//g; 1423 $address = trim($address); 1424 $address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes 1425 1426 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars 1427 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes 1428 $name = "\"$name\""; 1429 } 1430 1431 $name_comment = trim($name_comment); 1432 $name_comment = " $name_comment" if ($name_comment ne ""); 1433 $comment = trim($comment); 1434 $comment = " $comment" if ($comment ne ""); 1435 1436 if ("$name" eq "") { 1437 $formatted_email = "$address"; 1438 } else { 1439 $formatted_email = "$name$name_comment <$address>"; 1440 } 1441 $formatted_email .= "$comment"; 1442 return $formatted_email; 1443} 1444 1445sub reformat_email { 1446 my ($email) = @_; 1447 1448 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email); 1449 return format_email($email_name, $name_comment, $email_address, $comment); 1450} 1451 1452sub same_email_addresses { 1453 my ($email1, $email2) = @_; 1454 1455 my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1); 1456 my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2); 1457 1458 return $email1_name eq $email2_name && 1459 $email1_address eq $email2_address && 1460 $name1_comment eq $name2_comment && 1461 $comment1 eq $comment2; 1462} 1463 1464sub which { 1465 my ($bin) = @_; 1466 1467 foreach my $path (split(/:/, $ENV{PATH})) { 1468 if (-e "$path/$bin") { 1469 return "$path/$bin"; 1470 } 1471 } 1472 1473 return ""; 1474} 1475 1476sub which_conf { 1477 my ($conf) = @_; 1478 1479 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) { 1480 if (-e "$path/$conf") { 1481 return "$path/$conf"; 1482 } 1483 } 1484 1485 return ""; 1486} 1487 1488sub expand_tabs { 1489 my ($str) = @_; 1490 1491 my $res = ''; 1492 my $n = 0; 1493 for my $c (split(//, $str)) { 1494 if ($c eq "\t") { 1495 $res .= ' '; 1496 $n++; 1497 for (; ($n % $tabsize) != 0; $n++) { 1498 $res .= ' '; 1499 } 1500 next; 1501 } 1502 $res .= $c; 1503 $n++; 1504 } 1505 1506 return $res; 1507} 1508sub copy_spacing { 1509 (my $res = shift) =~ tr/\t/ /c; 1510 return $res; 1511} 1512 1513sub line_stats { 1514 my ($line) = @_; 1515 1516 # Drop the diff line leader and expand tabs 1517 $line =~ s/^.//; 1518 $line = expand_tabs($line); 1519 1520 # Pick the indent from the front of the line. 1521 my ($white) = ($line =~ /^(\s*)/); 1522 1523 return (length($line), length($white)); 1524} 1525 1526my $sanitise_quote = ''; 1527 1528sub sanitise_line_reset { 1529 my ($in_comment) = @_; 1530 1531 if ($in_comment) { 1532 $sanitise_quote = '*/'; 1533 } else { 1534 $sanitise_quote = ''; 1535 } 1536} 1537sub sanitise_line { 1538 my ($line) = @_; 1539 1540 my $res = ''; 1541 my $l = ''; 1542 1543 my $qlen = 0; 1544 my $off = 0; 1545 my $c; 1546 1547 # Always copy over the diff marker. 1548 $res = substr($line, 0, 1); 1549 1550 for ($off = 1; $off < length($line); $off++) { 1551 $c = substr($line, $off, 1); 1552 1553 # Comments we are whacking completely including the begin 1554 # and end, all to $;. 1555 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') { 1556 $sanitise_quote = '*/'; 1557 1558 substr($res, $off, 2, "$;$;"); 1559 $off++; 1560 next; 1561 } 1562 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') { 1563 $sanitise_quote = ''; 1564 substr($res, $off, 2, "$;$;"); 1565 $off++; 1566 next; 1567 } 1568 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') { 1569 $sanitise_quote = '//'; 1570 1571 substr($res, $off, 2, $sanitise_quote); 1572 $off++; 1573 next; 1574 } 1575 1576 # A \ in a string means ignore the next character. 1577 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') && 1578 $c eq "\\") { 1579 substr($res, $off, 2, 'XX'); 1580 $off++; 1581 next; 1582 } 1583 # Regular quotes. 1584 if ($c eq "'" || $c eq '"') { 1585 if ($sanitise_quote eq '') { 1586 $sanitise_quote = $c; 1587 1588 substr($res, $off, 1, $c); 1589 next; 1590 } elsif ($sanitise_quote eq $c) { 1591 $sanitise_quote = ''; 1592 } 1593 } 1594 1595 #print "c<$c> SQ<$sanitise_quote>\n"; 1596 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") { 1597 substr($res, $off, 1, $;); 1598 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") { 1599 substr($res, $off, 1, $;); 1600 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") { 1601 substr($res, $off, 1, 'X'); 1602 } else { 1603 substr($res, $off, 1, $c); 1604 } 1605 } 1606 1607 if ($sanitise_quote eq '//') { 1608 $sanitise_quote = ''; 1609 } 1610 1611 # The pathname on a #include may be surrounded by '<' and '>'. 1612 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) { 1613 my $clean = 'X' x length($1); 1614 $res =~ s@\<.*\>@<$clean>@; 1615 1616 # The whole of a #error is a string. 1617 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) { 1618 my $clean = 'X' x length($1); 1619 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@; 1620 } 1621 1622 if ($allow_c99_comments && $res =~ m@(//.*$)@) { 1623 my $match = $1; 1624 $res =~ s/\Q$match\E/"$;" x length($match)/e; 1625 } 1626 1627 return $res; 1628} 1629 1630sub get_quoted_string { 1631 my ($line, $rawline) = @_; 1632 1633 return "" if (!defined($line) || !defined($rawline)); 1634 return "" if ($line !~ m/($String)/g); 1635 return substr($rawline, $-[0], $+[0] - $-[0]); 1636} 1637 1638sub ctx_statement_block { 1639 my ($linenr, $remain, $off) = @_; 1640 my $line = $linenr - 1; 1641 my $blk = ''; 1642 my $soff = $off; 1643 my $coff = $off - 1; 1644 my $coff_set = 0; 1645 1646 my $loff = 0; 1647 1648 my $type = ''; 1649 my $level = 0; 1650 my @stack = (); 1651 my $p; 1652 my $c; 1653 my $len = 0; 1654 1655 my $remainder; 1656 while (1) { 1657 @stack = (['', 0]) if ($#stack == -1); 1658 1659 #warn "CSB: blk<$blk> remain<$remain>\n"; 1660 # If we are about to drop off the end, pull in more 1661 # context. 1662 if ($off >= $len) { 1663 for (; $remain > 0; $line++) { 1664 last if (!defined $lines[$line]); 1665 next if ($lines[$line] =~ /^-/); 1666 $remain--; 1667 $loff = $len; 1668 $blk .= $lines[$line] . "\n"; 1669 $len = length($blk); 1670 $line++; 1671 last; 1672 } 1673 # Bail if there is no further context. 1674 #warn "CSB: blk<$blk> off<$off> len<$len>\n"; 1675 if ($off >= $len) { 1676 last; 1677 } 1678 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) { 1679 $level++; 1680 $type = '#'; 1681 } 1682 } 1683 $p = $c; 1684 $c = substr($blk, $off, 1); 1685 $remainder = substr($blk, $off); 1686 1687 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n"; 1688 1689 # Handle nested #if/#else. 1690 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) { 1691 push(@stack, [ $type, $level ]); 1692 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) { 1693 ($type, $level) = @{$stack[$#stack - 1]}; 1694 } elsif ($remainder =~ /^#\s*endif\b/) { 1695 ($type, $level) = @{pop(@stack)}; 1696 } 1697 1698 # Statement ends at the ';' or a close '}' at the 1699 # outermost level. 1700 if ($level == 0 && $c eq ';') { 1701 last; 1702 } 1703 1704 # An else is really a conditional as long as its not else if 1705 if ($level == 0 && $coff_set == 0 && 1706 (!defined($p) || $p =~ /(?:\s|\}|\+)/) && 1707 $remainder =~ /^(else)(?:\s|{)/ && 1708 $remainder !~ /^else\s+if\b/) { 1709 $coff = $off + length($1) - 1; 1710 $coff_set = 1; 1711 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n"; 1712 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n"; 1713 } 1714 1715 if (($type eq '' || $type eq '(') && $c eq '(') { 1716 $level++; 1717 $type = '('; 1718 } 1719 if ($type eq '(' && $c eq ')') { 1720 $level--; 1721 $type = ($level != 0)? '(' : ''; 1722 1723 if ($level == 0 && $coff < $soff) { 1724 $coff = $off; 1725 $coff_set = 1; 1726 #warn "CSB: mark coff<$coff>\n"; 1727 } 1728 } 1729 if (($type eq '' || $type eq '{') && $c eq '{') { 1730 $level++; 1731 $type = '{'; 1732 } 1733 if ($type eq '{' && $c eq '}') { 1734 $level--; 1735 $type = ($level != 0)? '{' : ''; 1736 1737 if ($level == 0) { 1738 if (substr($blk, $off + 1, 1) eq ';') { 1739 $off++; 1740 } 1741 last; 1742 } 1743 } 1744 # Preprocessor commands end at the newline unless escaped. 1745 if ($type eq '#' && $c eq "\n" && $p ne "\\") { 1746 $level--; 1747 $type = ''; 1748 $off++; 1749 last; 1750 } 1751 $off++; 1752 } 1753 # We are truly at the end, so shuffle to the next line. 1754 if ($off == $len) { 1755 $loff = $len + 1; 1756 $line++; 1757 $remain--; 1758 } 1759 1760 my $statement = substr($blk, $soff, $off - $soff + 1); 1761 my $condition = substr($blk, $soff, $coff - $soff + 1); 1762 1763 #warn "STATEMENT<$statement>\n"; 1764 #warn "CONDITION<$condition>\n"; 1765 1766 #print "coff<$coff> soff<$off> loff<$loff>\n"; 1767 1768 return ($statement, $condition, 1769 $line, $remain + 1, $off - $loff + 1, $level); 1770} 1771 1772sub statement_lines { 1773 my ($stmt) = @_; 1774 1775 # Strip the diff line prefixes and rip blank lines at start and end. 1776 $stmt =~ s/(^|\n)./$1/g; 1777 $stmt =~ s/^\s*//; 1778 $stmt =~ s/\s*$//; 1779 1780 my @stmt_lines = ($stmt =~ /\n/g); 1781 1782 return $#stmt_lines + 2; 1783} 1784 1785sub statement_rawlines { 1786 my ($stmt) = @_; 1787 1788 my @stmt_lines = ($stmt =~ /\n/g); 1789 1790 return $#stmt_lines + 2; 1791} 1792 1793sub statement_block_size { 1794 my ($stmt) = @_; 1795 1796 $stmt =~ s/(^|\n)./$1/g; 1797 $stmt =~ s/^\s*{//; 1798 $stmt =~ s/}\s*$//; 1799 $stmt =~ s/^\s*//; 1800 $stmt =~ s/\s*$//; 1801 1802 my @stmt_lines = ($stmt =~ /\n/g); 1803 my @stmt_statements = ($stmt =~ /;/g); 1804 1805 my $stmt_lines = $#stmt_lines + 2; 1806 my $stmt_statements = $#stmt_statements + 1; 1807 1808 if ($stmt_lines > $stmt_statements) { 1809 return $stmt_lines; 1810 } else { 1811 return $stmt_statements; 1812 } 1813} 1814 1815sub ctx_statement_full { 1816 my ($linenr, $remain, $off) = @_; 1817 my ($statement, $condition, $level); 1818 1819 my (@chunks); 1820 1821 # Grab the first conditional/block pair. 1822 ($statement, $condition, $linenr, $remain, $off, $level) = 1823 ctx_statement_block($linenr, $remain, $off); 1824 #print "F: c<$condition> s<$statement> remain<$remain>\n"; 1825 push(@chunks, [ $condition, $statement ]); 1826 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) { 1827 return ($level, $linenr, @chunks); 1828 } 1829 1830 # Pull in the following conditional/block pairs and see if they 1831 # could continue the statement. 1832 for (;;) { 1833 ($statement, $condition, $linenr, $remain, $off, $level) = 1834 ctx_statement_block($linenr, $remain, $off); 1835 #print "C: c<$condition> s<$statement> remain<$remain>\n"; 1836 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s)); 1837 #print "C: push\n"; 1838 push(@chunks, [ $condition, $statement ]); 1839 } 1840 1841 return ($level, $linenr, @chunks); 1842} 1843 1844sub ctx_block_get { 1845 my ($linenr, $remain, $outer, $open, $close, $off) = @_; 1846 my $line; 1847 my $start = $linenr - 1; 1848 my $blk = ''; 1849 my @o; 1850 my @c; 1851 my @res = (); 1852 1853 my $level = 0; 1854 my @stack = ($level); 1855 for ($line = $start; $remain > 0; $line++) { 1856 next if ($rawlines[$line] =~ /^-/); 1857 $remain--; 1858 1859 $blk .= $rawlines[$line]; 1860 1861 # Handle nested #if/#else. 1862 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) { 1863 push(@stack, $level); 1864 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) { 1865 $level = $stack[$#stack - 1]; 1866 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) { 1867 $level = pop(@stack); 1868 } 1869 1870 foreach my $c (split(//, $lines[$line])) { 1871 ##print "C<$c>L<$level><$open$close>O<$off>\n"; 1872 if ($off > 0) { 1873 $off--; 1874 next; 1875 } 1876 1877 if ($c eq $close && $level > 0) { 1878 $level--; 1879 last if ($level == 0); 1880 } elsif ($c eq $open) { 1881 $level++; 1882 } 1883 } 1884 1885 if (!$outer || $level <= 1) { 1886 push(@res, $rawlines[$line]); 1887 } 1888 1889 last if ($level == 0); 1890 } 1891 1892 return ($level, @res); 1893} 1894sub ctx_block_outer { 1895 my ($linenr, $remain) = @_; 1896 1897 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0); 1898 return @r; 1899} 1900sub ctx_block { 1901 my ($linenr, $remain) = @_; 1902 1903 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0); 1904 return @r; 1905} 1906sub ctx_statement { 1907 my ($linenr, $remain, $off) = @_; 1908 1909 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off); 1910 return @r; 1911} 1912sub ctx_block_level { 1913 my ($linenr, $remain) = @_; 1914 1915 return ctx_block_get($linenr, $remain, 0, '{', '}', 0); 1916} 1917sub ctx_statement_level { 1918 my ($linenr, $remain, $off) = @_; 1919 1920 return ctx_block_get($linenr, $remain, 0, '(', ')', $off); 1921} 1922 1923sub ctx_locate_comment { 1924 my ($first_line, $end_line) = @_; 1925 1926 # If c99 comment on the current line, or the line before or after 1927 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@); 1928 return $current_comment if (defined $current_comment); 1929 ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@); 1930 return $current_comment if (defined $current_comment); 1931 ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@); 1932 return $current_comment if (defined $current_comment); 1933 1934 # Catch a comment on the end of the line itself. 1935 ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@); 1936 return $current_comment if (defined $current_comment); 1937 1938 # Look through the context and try and figure out if there is a 1939 # comment. 1940 my $in_comment = 0; 1941 $current_comment = ''; 1942 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) { 1943 my $line = $rawlines[$linenr - 1]; 1944 #warn " $line\n"; 1945 if ($linenr == $first_line and $line =~ m@^.\s*\*@) { 1946 $in_comment = 1; 1947 } 1948 if ($line =~ m@/\*@) { 1949 $in_comment = 1; 1950 } 1951 if (!$in_comment && $current_comment ne '') { 1952 $current_comment = ''; 1953 } 1954 $current_comment .= $line . "\n" if ($in_comment); 1955 if ($line =~ m@\*/@) { 1956 $in_comment = 0; 1957 } 1958 } 1959 1960 chomp($current_comment); 1961 return($current_comment); 1962} 1963sub ctx_has_comment { 1964 my ($first_line, $end_line) = @_; 1965 my $cmt = ctx_locate_comment($first_line, $end_line); 1966 1967 ##print "LINE: $rawlines[$end_line - 1 ]\n"; 1968 ##print "CMMT: $cmt\n"; 1969 1970 return ($cmt ne ''); 1971} 1972 1973sub raw_line { 1974 my ($linenr, $cnt) = @_; 1975 1976 my $offset = $linenr - 1; 1977 $cnt++; 1978 1979 my $line; 1980 while ($cnt) { 1981 $line = $rawlines[$offset++]; 1982 next if (defined($line) && $line =~ /^-/); 1983 $cnt--; 1984 } 1985 1986 return $line; 1987} 1988 1989sub get_stat_real { 1990 my ($linenr, $lc) = @_; 1991 1992 my $stat_real = raw_line($linenr, 0); 1993 for (my $count = $linenr + 1; $count <= $lc; $count++) { 1994 $stat_real = $stat_real . "\n" . raw_line($count, 0); 1995 } 1996 1997 return $stat_real; 1998} 1999 2000sub get_stat_here { 2001 my ($linenr, $cnt, $here) = @_; 2002 2003 my $herectx = $here . "\n"; 2004 for (my $n = 0; $n < $cnt; $n++) { 2005 $herectx .= raw_line($linenr, $n) . "\n"; 2006 } 2007 2008 return $herectx; 2009} 2010 2011sub cat_vet { 2012 my ($vet) = @_; 2013 my ($res, $coded); 2014 2015 $res = ''; 2016 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) { 2017 $res .= $1; 2018 if ($2 ne '') { 2019 $coded = sprintf("^%c", unpack('C', $2) + 64); 2020 $res .= $coded; 2021 } 2022 } 2023 $res =~ s/$/\$/; 2024 2025 return $res; 2026} 2027 2028my $av_preprocessor = 0; 2029my $av_pending; 2030my @av_paren_type; 2031my $av_pend_colon; 2032 2033sub annotate_reset { 2034 $av_preprocessor = 0; 2035 $av_pending = '_'; 2036 @av_paren_type = ('E'); 2037 $av_pend_colon = 'O'; 2038} 2039 2040sub annotate_values { 2041 my ($stream, $type) = @_; 2042 2043 my $res; 2044 my $var = '_' x length($stream); 2045 my $cur = $stream; 2046 2047 print "$stream\n" if ($dbg_values > 1); 2048 2049 while (length($cur)) { 2050 @av_paren_type = ('E') if ($#av_paren_type < 0); 2051 print " <" . join('', @av_paren_type) . 2052 "> <$type> <$av_pending>" if ($dbg_values > 1); 2053 if ($cur =~ /^(\s+)/o) { 2054 print "WS($1)\n" if ($dbg_values > 1); 2055 if ($1 =~ /\n/ && $av_preprocessor) { 2056 $type = pop(@av_paren_type); 2057 $av_preprocessor = 0; 2058 } 2059 2060 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') { 2061 print "CAST($1)\n" if ($dbg_values > 1); 2062 push(@av_paren_type, $type); 2063 $type = 'c'; 2064 2065 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) { 2066 print "DECLARE($1)\n" if ($dbg_values > 1); 2067 $type = 'T'; 2068 2069 } elsif ($cur =~ /^($Modifier)\s*/) { 2070 print "MODIFIER($1)\n" if ($dbg_values > 1); 2071 $type = 'T'; 2072 2073 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) { 2074 print "DEFINE($1,$2)\n" if ($dbg_values > 1); 2075 $av_preprocessor = 1; 2076 push(@av_paren_type, $type); 2077 if ($2 ne '') { 2078 $av_pending = 'N'; 2079 } 2080 $type = 'E'; 2081 2082 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) { 2083 print "UNDEF($1)\n" if ($dbg_values > 1); 2084 $av_preprocessor = 1; 2085 push(@av_paren_type, $type); 2086 2087 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) { 2088 print "PRE_START($1)\n" if ($dbg_values > 1); 2089 $av_preprocessor = 1; 2090 2091 push(@av_paren_type, $type); 2092 push(@av_paren_type, $type); 2093 $type = 'E'; 2094 2095 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) { 2096 print "PRE_RESTART($1)\n" if ($dbg_values > 1); 2097 $av_preprocessor = 1; 2098 2099 push(@av_paren_type, $av_paren_type[$#av_paren_type]); 2100 2101 $type = 'E'; 2102 2103 } elsif ($cur =~ /^(\#\s*(?:endif))/o) { 2104 print "PRE_END($1)\n" if ($dbg_values > 1); 2105 2106 $av_preprocessor = 1; 2107 2108 # Assume all arms of the conditional end as this 2109 # one does, and continue as if the #endif was not here. 2110 pop(@av_paren_type); 2111 push(@av_paren_type, $type); 2112 $type = 'E'; 2113 2114 } elsif ($cur =~ /^(\\\n)/o) { 2115 print "PRECONT($1)\n" if ($dbg_values > 1); 2116 2117 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) { 2118 print "ATTR($1)\n" if ($dbg_values > 1); 2119 $av_pending = $type; 2120 $type = 'N'; 2121 2122 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) { 2123 print "SIZEOF($1)\n" if ($dbg_values > 1); 2124 if (defined $2) { 2125 $av_pending = 'V'; 2126 } 2127 $type = 'N'; 2128 2129 } elsif ($cur =~ /^(if|while|for)\b/o) { 2130 print "COND($1)\n" if ($dbg_values > 1); 2131 $av_pending = 'E'; 2132 $type = 'N'; 2133 2134 } elsif ($cur =~/^(case)/o) { 2135 print "CASE($1)\n" if ($dbg_values > 1); 2136 $av_pend_colon = 'C'; 2137 $type = 'N'; 2138 2139 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) { 2140 print "KEYWORD($1)\n" if ($dbg_values > 1); 2141 $type = 'N'; 2142 2143 } elsif ($cur =~ /^(\()/o) { 2144 print "PAREN('$1')\n" if ($dbg_values > 1); 2145 push(@av_paren_type, $av_pending); 2146 $av_pending = '_'; 2147 $type = 'N'; 2148 2149 } elsif ($cur =~ /^(\))/o) { 2150 my $new_type = pop(@av_paren_type); 2151 if ($new_type ne '_') { 2152 $type = $new_type; 2153 print "PAREN('$1') -> $type\n" 2154 if ($dbg_values > 1); 2155 } else { 2156 print "PAREN('$1')\n" if ($dbg_values > 1); 2157 } 2158 2159 } elsif ($cur =~ /^($Ident)\s*\(/o) { 2160 print "FUNC($1)\n" if ($dbg_values > 1); 2161 $type = 'V'; 2162 $av_pending = 'V'; 2163 2164 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) { 2165 if (defined $2 && $type eq 'C' || $type eq 'T') { 2166 $av_pend_colon = 'B'; 2167 } elsif ($type eq 'E') { 2168 $av_pend_colon = 'L'; 2169 } 2170 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1); 2171 $type = 'V'; 2172 2173 } elsif ($cur =~ /^($Ident|$Constant)/o) { 2174 print "IDENT($1)\n" if ($dbg_values > 1); 2175 $type = 'V'; 2176 2177 } elsif ($cur =~ /^($Assignment)/o) { 2178 print "ASSIGN($1)\n" if ($dbg_values > 1); 2179 $type = 'N'; 2180 2181 } elsif ($cur =~/^(;|{|})/) { 2182 print "END($1)\n" if ($dbg_values > 1); 2183 $type = 'E'; 2184 $av_pend_colon = 'O'; 2185 2186 } elsif ($cur =~/^(,)/) { 2187 print "COMMA($1)\n" if ($dbg_values > 1); 2188 $type = 'C'; 2189 2190 } elsif ($cur =~ /^(\?)/o) { 2191 print "QUESTION($1)\n" if ($dbg_values > 1); 2192 $type = 'N'; 2193 2194 } elsif ($cur =~ /^(:)/o) { 2195 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1); 2196 2197 substr($var, length($res), 1, $av_pend_colon); 2198 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') { 2199 $type = 'E'; 2200 } else { 2201 $type = 'N'; 2202 } 2203 $av_pend_colon = 'O'; 2204 2205 } elsif ($cur =~ /^(\[)/o) { 2206 print "CLOSE($1)\n" if ($dbg_values > 1); 2207 $type = 'N'; 2208 2209 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) { 2210 my $variant; 2211 2212 print "OPV($1)\n" if ($dbg_values > 1); 2213 if ($type eq 'V') { 2214 $variant = 'B'; 2215 } else { 2216 $variant = 'U'; 2217 } 2218 2219 substr($var, length($res), 1, $variant); 2220 $type = 'N'; 2221 2222 } elsif ($cur =~ /^($Operators)/o) { 2223 print "OP($1)\n" if ($dbg_values > 1); 2224 if ($1 ne '++' && $1 ne '--') { 2225 $type = 'N'; 2226 } 2227 2228 } elsif ($cur =~ /(^.)/o) { 2229 print "C($1)\n" if ($dbg_values > 1); 2230 } 2231 if (defined $1) { 2232 $cur = substr($cur, length($1)); 2233 $res .= $type x length($1); 2234 } 2235 } 2236 2237 return ($res, $var); 2238} 2239 2240sub possible { 2241 my ($possible, $line) = @_; 2242 my $notPermitted = qr{(?: 2243 ^(?: 2244 $Modifier| 2245 $Storage| 2246 $Type| 2247 DEFINE_\S+ 2248 )$| 2249 ^(?: 2250 goto| 2251 return| 2252 case| 2253 else| 2254 asm|__asm__| 2255 do| 2256 \#| 2257 \#\#| 2258 )(?:\s|$)| 2259 ^(?:typedef|struct|enum)\b 2260 )}x; 2261 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2); 2262 if ($possible !~ $notPermitted) { 2263 # Check for modifiers. 2264 $possible =~ s/\s*$Storage\s*//g; 2265 $possible =~ s/\s*$Sparse\s*//g; 2266 if ($possible =~ /^\s*$/) { 2267 2268 } elsif ($possible =~ /\s/) { 2269 $possible =~ s/\s*$Type\s*//g; 2270 for my $modifier (split(' ', $possible)) { 2271 if ($modifier !~ $notPermitted) { 2272 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible); 2273 push(@modifierListFile, $modifier); 2274 } 2275 } 2276 2277 } else { 2278 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible); 2279 push(@typeListFile, $possible); 2280 } 2281 build_types(); 2282 } else { 2283 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1); 2284 } 2285} 2286 2287my $prefix = ''; 2288 2289sub show_type { 2290 my ($type) = @_; 2291 2292 $type =~ tr/[a-z]/[A-Z]/; 2293 2294 return defined $use_type{$type} if (scalar keys %use_type > 0); 2295 2296 return !defined $ignore_type{$type}; 2297} 2298 2299sub report { 2300 my ($level, $type, $msg) = @_; 2301 2302 if (!show_type($type) || 2303 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) { 2304 return 0; 2305 } 2306 my $output = ''; 2307 if ($color) { 2308 if ($level eq 'ERROR') { 2309 $output .= RED; 2310 } elsif ($level eq 'WARNING') { 2311 $output .= YELLOW; 2312 } else { 2313 $output .= GREEN; 2314 } 2315 } 2316 $output .= $prefix . $level . ':'; 2317 if ($show_types) { 2318 $output .= BLUE if ($color); 2319 $output .= "$type:"; 2320 } 2321 $output .= RESET if ($color); 2322 $output .= ' ' . $msg . "\n"; 2323 2324 if ($showfile) { 2325 my @lines = split("\n", $output, -1); 2326 splice(@lines, 1, 1); 2327 $output = join("\n", @lines); 2328 } 2329 2330 if ($terse) { 2331 $output = (split('\n', $output))[0] . "\n"; 2332 } 2333 2334 if ($verbose && exists($verbose_messages{$type}) && 2335 !exists($verbose_emitted{$type})) { 2336 $output .= $verbose_messages{$type} . "\n\n"; 2337 $verbose_emitted{$type} = 1; 2338 } 2339 2340 push(our @report, $output); 2341 2342 return 1; 2343} 2344 2345sub report_dump { 2346 our @report; 2347} 2348 2349sub fixup_current_range { 2350 my ($lineRef, $offset, $length) = @_; 2351 2352 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) { 2353 my $o = $1; 2354 my $l = $2; 2355 my $no = $o + $offset; 2356 my $nl = $l + $length; 2357 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/; 2358 } 2359} 2360 2361sub fix_inserted_deleted_lines { 2362 my ($linesRef, $insertedRef, $deletedRef) = @_; 2363 2364 my $range_last_linenr = 0; 2365 my $delta_offset = 0; 2366 2367 my $old_linenr = 0; 2368 my $new_linenr = 0; 2369 2370 my $next_insert = 0; 2371 my $next_delete = 0; 2372 2373 my @lines = (); 2374 2375 my $inserted = @{$insertedRef}[$next_insert++]; 2376 my $deleted = @{$deletedRef}[$next_delete++]; 2377 2378 foreach my $old_line (@{$linesRef}) { 2379 my $save_line = 1; 2380 my $line = $old_line; #don't modify the array 2381 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename 2382 $delta_offset = 0; 2383 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk 2384 $range_last_linenr = $new_linenr; 2385 fixup_current_range(\$line, $delta_offset, 0); 2386 } 2387 2388 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) { 2389 $deleted = @{$deletedRef}[$next_delete++]; 2390 $save_line = 0; 2391 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1); 2392 } 2393 2394 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) { 2395 push(@lines, ${$inserted}{'LINE'}); 2396 $inserted = @{$insertedRef}[$next_insert++]; 2397 $new_linenr++; 2398 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1); 2399 } 2400 2401 if ($save_line) { 2402 push(@lines, $line); 2403 $new_linenr++; 2404 } 2405 2406 $old_linenr++; 2407 } 2408 2409 return @lines; 2410} 2411 2412sub fix_insert_line { 2413 my ($linenr, $line) = @_; 2414 2415 my $inserted = { 2416 LINENR => $linenr, 2417 LINE => $line, 2418 }; 2419 push(@fixed_inserted, $inserted); 2420} 2421 2422sub fix_delete_line { 2423 my ($linenr, $line) = @_; 2424 2425 my $deleted = { 2426 LINENR => $linenr, 2427 LINE => $line, 2428 }; 2429 2430 push(@fixed_deleted, $deleted); 2431} 2432 2433sub ERROR { 2434 my ($type, $msg) = @_; 2435 2436 if (report("ERROR", $type, $msg)) { 2437 our $clean = 0; 2438 our $cnt_error++; 2439 return 1; 2440 } 2441 return 0; 2442} 2443sub WARN { 2444 my ($type, $msg) = @_; 2445 2446 if (report("WARNING", $type, $msg)) { 2447 our $clean = 0; 2448 our $cnt_warn++; 2449 return 1; 2450 } 2451 return 0; 2452} 2453sub CHK { 2454 my ($type, $msg) = @_; 2455 2456 if ($check && report("CHECK", $type, $msg)) { 2457 our $clean = 0; 2458 our $cnt_chk++; 2459 return 1; 2460 } 2461 return 0; 2462} 2463 2464sub check_absolute_file { 2465 my ($absolute, $herecurr) = @_; 2466 my $file = $absolute; 2467 2468 ##print "absolute<$absolute>\n"; 2469 2470 # See if any suffix of this path is a path within the tree. 2471 while ($file =~ s@^[^/]*/@@) { 2472 if (-f "$root/$file") { 2473 ##print "file<$file>\n"; 2474 last; 2475 } 2476 } 2477 if (! -f _) { 2478 return 0; 2479 } 2480 2481 # It is, so see if the prefix is acceptable. 2482 my $prefix = $absolute; 2483 substr($prefix, -length($file)) = ''; 2484 2485 ##print "prefix<$prefix>\n"; 2486 if ($prefix ne ".../") { 2487 WARN("USE_RELATIVE_PATH", 2488 "use relative pathname instead of absolute in changelog text\n" . $herecurr); 2489 } 2490} 2491 2492sub trim { 2493 my ($string) = @_; 2494 2495 $string =~ s/^\s+|\s+$//g; 2496 2497 return $string; 2498} 2499 2500sub ltrim { 2501 my ($string) = @_; 2502 2503 $string =~ s/^\s+//; 2504 2505 return $string; 2506} 2507 2508sub rtrim { 2509 my ($string) = @_; 2510 2511 $string =~ s/\s+$//; 2512 2513 return $string; 2514} 2515 2516sub string_find_replace { 2517 my ($string, $find, $replace) = @_; 2518 2519 $string =~ s/$find/$replace/g; 2520 2521 return $string; 2522} 2523 2524sub tabify { 2525 my ($leading) = @_; 2526 2527 my $source_indent = $tabsize; 2528 my $max_spaces_before_tab = $source_indent - 1; 2529 my $spaces_to_tab = " " x $source_indent; 2530 2531 #convert leading spaces to tabs 2532 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g; 2533 #Remove spaces before a tab 2534 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g; 2535 2536 return "$leading"; 2537} 2538 2539sub pos_last_openparen { 2540 my ($line) = @_; 2541 2542 my $pos = 0; 2543 2544 my $opens = $line =~ tr/\(/\(/; 2545 my $closes = $line =~ tr/\)/\)/; 2546 2547 my $last_openparen = 0; 2548 2549 if (($opens == 0) || ($closes >= $opens)) { 2550 return -1; 2551 } 2552 2553 my $len = length($line); 2554 2555 for ($pos = 0; $pos < $len; $pos++) { 2556 my $string = substr($line, $pos); 2557 if ($string =~ /^($FuncArg|$balanced_parens)/) { 2558 $pos += length($1) - 1; 2559 } elsif (substr($line, $pos, 1) eq '(') { 2560 $last_openparen = $pos; 2561 } elsif (index($string, '(') == -1) { 2562 last; 2563 } 2564 } 2565 2566 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1; 2567} 2568 2569sub get_raw_comment { 2570 my ($line, $rawline) = @_; 2571 my $comment = ''; 2572 2573 for my $i (0 .. (length($line) - 1)) { 2574 if (substr($line, $i, 1) eq "$;") { 2575 $comment .= substr($rawline, $i, 1); 2576 } 2577 } 2578 2579 return $comment; 2580} 2581 2582sub exclude_global_initialisers { 2583 my ($realfile) = @_; 2584 2585 # Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c). 2586 return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ || 2587 $realfile =~ m@^samples/bpf/.*_kern\.c$@ || 2588 $realfile =~ m@/bpf/.*\.bpf\.c$@; 2589} 2590 2591sub process { 2592 my $filename = shift; 2593 2594 my $linenr=0; 2595 my $prevline=""; 2596 my $prevrawline=""; 2597 my $stashline=""; 2598 my $stashrawline=""; 2599 2600 my $length; 2601 my $indent; 2602 my $previndent=0; 2603 my $stashindent=0; 2604 2605 our $clean = 1; 2606 my $signoff = 0; 2607 my $author = ''; 2608 my $authorsignoff = 0; 2609 my $author_sob = ''; 2610 my $is_patch = 0; 2611 my $is_binding_patch = -1; 2612 my $in_header_lines = $file ? 0 : 1; 2613 my $in_commit_log = 0; #Scanning lines before patch 2614 my $has_patch_separator = 0; #Found a --- line 2615 my $has_commit_log = 0; #Encountered lines before patch 2616 my $commit_log_lines = 0; #Number of commit log lines 2617 my $commit_log_possible_stack_dump = 0; 2618 my $commit_log_long_line = 0; 2619 my $commit_log_has_diff = 0; 2620 my $reported_maintainer_file = 0; 2621 my $non_utf8_charset = 0; 2622 2623 my $last_git_commit_id_linenr = -1; 2624 2625 my $last_blank_line = 0; 2626 my $last_coalesced_string_linenr = -1; 2627 2628 our @report = (); 2629 our $cnt_lines = 0; 2630 our $cnt_error = 0; 2631 our $cnt_warn = 0; 2632 our $cnt_chk = 0; 2633 2634 # Trace the real file/line as we go. 2635 my $realfile = ''; 2636 my $realline = 0; 2637 my $realcnt = 0; 2638 my $here = ''; 2639 my $context_function; #undef'd unless there's a known function 2640 my $in_comment = 0; 2641 my $comment_edge = 0; 2642 my $first_line = 0; 2643 my $p1_prefix = ''; 2644 2645 my $prev_values = 'E'; 2646 2647 # suppression flags 2648 my %suppress_ifbraces; 2649 my %suppress_whiletrailers; 2650 my %suppress_export; 2651 my $suppress_statement = 0; 2652 2653 my %signatures = (); 2654 2655 # Pre-scan the patch sanitizing the lines. 2656 # Pre-scan the patch looking for any __setup documentation. 2657 # 2658 my @setup_docs = (); 2659 my $setup_docs = 0; 2660 2661 my $camelcase_file_seeded = 0; 2662 2663 my $checklicenseline = 1; 2664 2665 sanitise_line_reset(); 2666 my $line; 2667 foreach my $rawline (@rawlines) { 2668 $linenr++; 2669 $line = $rawline; 2670 2671 push(@fixed, $rawline) if ($fix); 2672 2673 if ($rawline=~/^\+\+\+\s+(\S+)/) { 2674 $setup_docs = 0; 2675 if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) { 2676 $setup_docs = 1; 2677 } 2678 #next; 2679 } 2680 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) { 2681 $realline=$1-1; 2682 if (defined $2) { 2683 $realcnt=$3+1; 2684 } else { 2685 $realcnt=1+1; 2686 } 2687 $in_comment = 0; 2688 2689 # Guestimate if this is a continuing comment. Run 2690 # the context looking for a comment "edge". If this 2691 # edge is a close comment then we must be in a comment 2692 # at context start. 2693 my $edge; 2694 my $cnt = $realcnt; 2695 for (my $ln = $linenr + 1; $cnt > 0; $ln++) { 2696 next if (defined $rawlines[$ln - 1] && 2697 $rawlines[$ln - 1] =~ /^-/); 2698 $cnt--; 2699 #print "RAW<$rawlines[$ln - 1]>\n"; 2700 last if (!defined $rawlines[$ln - 1]); 2701 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ && 2702 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) { 2703 ($edge) = $1; 2704 last; 2705 } 2706 } 2707 if (defined $edge && $edge eq '*/') { 2708 $in_comment = 1; 2709 } 2710 2711 # Guestimate if this is a continuing comment. If this 2712 # is the start of a diff block and this line starts 2713 # ' *' then it is very likely a comment. 2714 if (!defined $edge && 2715 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@) 2716 { 2717 $in_comment = 1; 2718 } 2719 2720 ##print "COMMENT:$in_comment edge<$edge> $rawline\n"; 2721 sanitise_line_reset($in_comment); 2722 2723 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) { 2724 # Standardise the strings and chars within the input to 2725 # simplify matching -- only bother with positive lines. 2726 $line = sanitise_line($rawline); 2727 } 2728 push(@lines, $line); 2729 2730 if ($realcnt > 1) { 2731 $realcnt-- if ($line =~ /^(?:\+| |$)/); 2732 } else { 2733 $realcnt = 0; 2734 } 2735 2736 #print "==>$rawline\n"; 2737 #print "-->$line\n"; 2738 2739 if ($setup_docs && $line =~ /^\+/) { 2740 push(@setup_docs, $line); 2741 } 2742 } 2743 2744 $prefix = ''; 2745 2746 $realcnt = 0; 2747 $linenr = 0; 2748 $fixlinenr = -1; 2749 foreach my $line (@lines) { 2750 $linenr++; 2751 $fixlinenr++; 2752 my $sline = $line; #copy of $line 2753 $sline =~ s/$;/ /g; #with comments as spaces 2754 2755 my $rawline = $rawlines[$linenr - 1]; 2756 my $raw_comment = get_raw_comment($line, $rawline); 2757 2758# check if it's a mode change, rename or start of a patch 2759 if (!$in_commit_log && 2760 ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ || 2761 ($line =~ /^rename (?:from|to) \S+\s*$/ || 2762 $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) { 2763 $is_patch = 1; 2764 } 2765 2766#extract the line range in the file after the patch is applied 2767 if (!$in_commit_log && 2768 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) { 2769 my $context = $4; 2770 $is_patch = 1; 2771 $first_line = $linenr + 1; 2772 $realline=$1-1; 2773 if (defined $2) { 2774 $realcnt=$3+1; 2775 } else { 2776 $realcnt=1+1; 2777 } 2778 annotate_reset(); 2779 $prev_values = 'E'; 2780 2781 %suppress_ifbraces = (); 2782 %suppress_whiletrailers = (); 2783 %suppress_export = (); 2784 $suppress_statement = 0; 2785 if ($context =~ /\b(\w+)\s*\(/) { 2786 $context_function = $1; 2787 } else { 2788 undef $context_function; 2789 } 2790 next; 2791 2792# track the line number as we move through the hunk, note that 2793# new versions of GNU diff omit the leading space on completely 2794# blank context lines so we need to count that too. 2795 } elsif ($line =~ /^( |\+|$)/) { 2796 $realline++; 2797 $realcnt-- if ($realcnt != 0); 2798 2799 # Measure the line length and indent. 2800 ($length, $indent) = line_stats($rawline); 2801 2802 # Track the previous line. 2803 ($prevline, $stashline) = ($stashline, $line); 2804 ($previndent, $stashindent) = ($stashindent, $indent); 2805 ($prevrawline, $stashrawline) = ($stashrawline, $rawline); 2806 2807 #warn "line<$line>\n"; 2808 2809 } elsif ($realcnt == 1) { 2810 $realcnt--; 2811 } 2812 2813 my $hunk_line = ($realcnt != 0); 2814 2815 $here = "#$linenr: " if (!$file); 2816 $here = "#$realline: " if ($file); 2817 2818 my $found_file = 0; 2819 # extract the filename as it passes 2820 if ($line =~ /^diff --git.*?(\S+)$/) { 2821 $realfile = $1; 2822 $realfile =~ s@^([^/]*)/@@ if (!$file); 2823 $in_commit_log = 0; 2824 $found_file = 1; 2825 } elsif ($line =~ /^\+\+\+\s+(\S+)/) { 2826 $realfile = $1; 2827 $realfile =~ s@^([^/]*)/@@ if (!$file); 2828 $in_commit_log = 0; 2829 2830 $p1_prefix = $1; 2831 if (!$file && $tree && $p1_prefix ne '' && 2832 -e "$root/$p1_prefix") { 2833 WARN("PATCH_PREFIX", 2834 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n"); 2835 } 2836 2837 if ($realfile =~ m@^include/asm/@) { 2838 ERROR("MODIFIED_INCLUDE_ASM", 2839 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n"); 2840 } 2841 $found_file = 1; 2842 } 2843 2844#make up the handle for any error we report on this line 2845 if ($showfile) { 2846 $prefix = "$realfile:$realline: " 2847 } elsif ($emacs) { 2848 if ($file) { 2849 $prefix = "$filename:$realline: "; 2850 } else { 2851 $prefix = "$filename:$linenr: "; 2852 } 2853 } 2854 2855 if ($found_file) { 2856 if (is_maintained_obsolete($realfile)) { 2857 WARN("OBSOLETE", 2858 "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy. No unnecessary modifications please.\n"); 2859 } 2860 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) { 2861 $check = 1; 2862 } else { 2863 $check = $check_orig; 2864 } 2865 $checklicenseline = 1; 2866 2867 if ($realfile !~ /^MAINTAINERS/) { 2868 my $last_binding_patch = $is_binding_patch; 2869 2870 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@; 2871 2872 if (($last_binding_patch != -1) && 2873 ($last_binding_patch ^ $is_binding_patch)) { 2874 WARN("DT_SPLIT_BINDING_PATCH", 2875 "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n"); 2876 } 2877 } 2878 2879 next; 2880 } 2881 2882 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0); 2883 2884 my $hereline = "$here\n$rawline\n"; 2885 my $herecurr = "$here\n$rawline\n"; 2886 my $hereprev = "$here\n$prevrawline\n$rawline\n"; 2887 2888 $cnt_lines++ if ($realcnt != 0); 2889 2890# Verify the existence of a commit log if appropriate 2891# 2 is used because a $signature is counted in $commit_log_lines 2892 if ($in_commit_log) { 2893 if ($line !~ /^\s*$/) { 2894 $commit_log_lines++; #could be a $signature 2895 } 2896 } elsif ($has_commit_log && $commit_log_lines < 2) { 2897 WARN("COMMIT_MESSAGE", 2898 "Missing commit description - Add an appropriate one\n"); 2899 $commit_log_lines = 2; #warn only once 2900 } 2901 2902# Check if the commit log has what seems like a diff which can confuse patch 2903 if ($in_commit_log && !$commit_log_has_diff && 2904 (($line =~ m@^\s+diff\b.*a/([\w/]+)@ && 2905 $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) || 2906 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ || 2907 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) { 2908 ERROR("DIFF_IN_COMMIT_MSG", 2909 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr); 2910 $commit_log_has_diff = 1; 2911 } 2912 2913# Check for incorrect file permissions 2914 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) { 2915 my $permhere = $here . "FILE: $realfile\n"; 2916 if ($realfile !~ m@scripts/@ && 2917 $realfile !~ /\.(py|pl|awk|sh)$/) { 2918 ERROR("EXECUTE_PERMISSIONS", 2919 "do not set execute permissions for source files\n" . $permhere); 2920 } 2921 } 2922 2923# Check the patch for a From: 2924 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) { 2925 $author = $1; 2926 my $curline = $linenr; 2927 while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) { 2928 $author .= $1; 2929 } 2930 $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i); 2931 $author =~ s/"//g; 2932 $author = reformat_email($author); 2933 } 2934 2935# Check the patch for a signoff: 2936 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) { 2937 $signoff++; 2938 $in_commit_log = 0; 2939 if ($author ne '' && $authorsignoff != 1) { 2940 if (same_email_addresses($1, $author)) { 2941 $authorsignoff = 1; 2942 } else { 2943 my $ctx = $1; 2944 my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx); 2945 my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author); 2946 2947 if (lc $email_address eq lc $author_address && $email_name eq $author_name) { 2948 $author_sob = $ctx; 2949 $authorsignoff = 2; 2950 } elsif (lc $email_address eq lc $author_address) { 2951 $author_sob = $ctx; 2952 $authorsignoff = 3; 2953 } elsif ($email_name eq $author_name) { 2954 $author_sob = $ctx; 2955 $authorsignoff = 4; 2956 2957 my $address1 = $email_address; 2958 my $address2 = $author_address; 2959 2960 if ($address1 =~ /(\S+)\+\S+(\@.*)/) { 2961 $address1 = "$1$2"; 2962 } 2963 if ($address2 =~ /(\S+)\+\S+(\@.*)/) { 2964 $address2 = "$1$2"; 2965 } 2966 if ($address1 eq $address2) { 2967 $authorsignoff = 5; 2968 } 2969 } 2970 } 2971 } 2972 } 2973 2974# Check for patch separator 2975 if ($line =~ /^---$/) { 2976 $has_patch_separator = 1; 2977 $in_commit_log = 0; 2978 } 2979 2980# Check if MAINTAINERS is being updated. If so, there's probably no need to 2981# emit the "does MAINTAINERS need updating?" message on file add/move/delete 2982 if ($line =~ /^\s*MAINTAINERS\s*\|/) { 2983 $reported_maintainer_file = 1; 2984 } 2985 2986# Check signature styles 2987 if (!$in_header_lines && 2988 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) { 2989 my $space_before = $1; 2990 my $sign_off = $2; 2991 my $space_after = $3; 2992 my $email = $4; 2993 my $ucfirst_sign_off = ucfirst(lc($sign_off)); 2994 2995 if ($sign_off !~ /$signature_tags/) { 2996 my $suggested_signature = find_standard_signature($sign_off); 2997 if ($suggested_signature eq "") { 2998 WARN("BAD_SIGN_OFF", 2999 "Non-standard signature: $sign_off\n" . $herecurr); 3000 } else { 3001 if (WARN("BAD_SIGN_OFF", 3002 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) && 3003 $fix) { 3004 $fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/; 3005 } 3006 } 3007 } 3008 if (defined $space_before && $space_before ne "") { 3009 if (WARN("BAD_SIGN_OFF", 3010 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) && 3011 $fix) { 3012 $fixed[$fixlinenr] = 3013 "$ucfirst_sign_off $email"; 3014 } 3015 } 3016 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) { 3017 if (WARN("BAD_SIGN_OFF", 3018 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) && 3019 $fix) { 3020 $fixed[$fixlinenr] = 3021 "$ucfirst_sign_off $email"; 3022 } 3023 3024 } 3025 if (!defined $space_after || $space_after ne " ") { 3026 if (WARN("BAD_SIGN_OFF", 3027 "Use a single space after $ucfirst_sign_off\n" . $herecurr) && 3028 $fix) { 3029 $fixed[$fixlinenr] = 3030 "$ucfirst_sign_off $email"; 3031 } 3032 } 3033 3034 my ($email_name, $name_comment, $email_address, $comment) = parse_email($email); 3035 my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment)); 3036 if ($suggested_email eq "") { 3037 ERROR("BAD_SIGN_OFF", 3038 "Unrecognized email address: '$email'\n" . $herecurr); 3039 } else { 3040 my $dequoted = $suggested_email; 3041 $dequoted =~ s/^"//; 3042 $dequoted =~ s/" </ </; 3043 # Don't force email to have quotes 3044 # Allow just an angle bracketed address 3045 if (!same_email_addresses($email, $suggested_email)) { 3046 if (WARN("BAD_SIGN_OFF", 3047 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) && 3048 $fix) { 3049 $fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/; 3050 } 3051 } 3052 3053 # Address part shouldn't have comments 3054 my $stripped_address = $email_address; 3055 $stripped_address =~ s/\([^\(\)]*\)//g; 3056 if ($email_address ne $stripped_address) { 3057 if (WARN("BAD_SIGN_OFF", 3058 "address part of email should not have comments: '$email_address'\n" . $herecurr) && 3059 $fix) { 3060 $fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/; 3061 } 3062 } 3063 3064 # Only one name comment should be allowed 3065 my $comment_count = () = $name_comment =~ /\([^\)]+\)/g; 3066 if ($comment_count > 1) { 3067 WARN("BAD_SIGN_OFF", 3068 "Use a single name comment in email: '$email'\n" . $herecurr); 3069 } 3070 3071 3072 # stable@vger.kernel.org or stable@kernel.org shouldn't 3073 # have an email name. In addition comments should strictly 3074 # begin with a # 3075 if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) { 3076 if (($comment ne "" && $comment !~ /^#.+/) || 3077 ($email_name ne "")) { 3078 my $cur_name = $email_name; 3079 my $new_comment = $comment; 3080 $cur_name =~ s/[a-zA-Z\s\-\"]+//g; 3081 3082 # Remove brackets enclosing comment text 3083 # and # from start of comments to get comment text 3084 $new_comment =~ s/^\((.*)\)$/$1/; 3085 $new_comment =~ s/^\[(.*)\]$/$1/; 3086 $new_comment =~ s/^[\s\#]+|\s+$//g; 3087 3088 $new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment); 3089 $new_comment = " # $new_comment" if ($new_comment ne ""); 3090 my $new_email = "$email_address$new_comment"; 3091 3092 if (WARN("BAD_STABLE_ADDRESS_STYLE", 3093 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) && 3094 $fix) { 3095 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/; 3096 } 3097 } 3098 } elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) { 3099 my $new_comment = $comment; 3100 3101 # Extract comment text from within brackets or 3102 # c89 style /*...*/ comments 3103 $new_comment =~ s/^\[(.*)\]$/$1/; 3104 $new_comment =~ s/^\/\*(.*)\*\/$/$1/; 3105 3106 $new_comment = trim($new_comment); 3107 $new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo 3108 $new_comment = "($new_comment)" if ($new_comment ne ""); 3109 my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment); 3110 3111 if (WARN("BAD_SIGN_OFF", 3112 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) && 3113 $fix) { 3114 $fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/; 3115 } 3116 } 3117 } 3118 3119# Check for duplicate signatures 3120 my $sig_nospace = $line; 3121 $sig_nospace =~ s/\s//g; 3122 $sig_nospace = lc($sig_nospace); 3123 if (defined $signatures{$sig_nospace}) { 3124 WARN("BAD_SIGN_OFF", 3125 "Duplicate signature\n" . $herecurr); 3126 } else { 3127 $signatures{$sig_nospace} = 1; 3128 } 3129 3130# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email 3131 if ($sign_off =~ /^co-developed-by:$/i) { 3132 if ($email eq $author) { 3133 WARN("BAD_SIGN_OFF", 3134 "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline); 3135 } 3136 if (!defined $lines[$linenr]) { 3137 WARN("BAD_SIGN_OFF", 3138 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline); 3139 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) { 3140 WARN("BAD_SIGN_OFF", 3141 "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]); 3142 } elsif ($1 ne $email) { 3143 WARN("BAD_SIGN_OFF", 3144 "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]); 3145 } 3146 } 3147 } 3148 3149# Check Fixes: styles is correct 3150 if (!$in_header_lines && 3151 $line =~ /^\s*fixes:?\s*(?:commit\s*)?[0-9a-f]{5,}\b/i) { 3152 my $orig_commit = ""; 3153 my $id = "0123456789ab"; 3154 my $title = "commit title"; 3155 my $tag_case = 1; 3156 my $tag_space = 1; 3157 my $id_length = 1; 3158 my $id_case = 1; 3159 my $title_has_quotes = 0; 3160 3161 if ($line =~ /(\s*fixes:?)\s+([0-9a-f]{5,})\s+($balanced_parens)/i) { 3162 my $tag = $1; 3163 $orig_commit = $2; 3164 $title = $3; 3165 3166 $tag_case = 0 if $tag eq "Fixes:"; 3167 $tag_space = 0 if ($line =~ /^fixes:? [0-9a-f]{5,} ($balanced_parens)/i); 3168 3169 $id_length = 0 if ($orig_commit =~ /^[0-9a-f]{12}$/i); 3170 $id_case = 0 if ($orig_commit !~ /[A-F]/); 3171 3172 # Always strip leading/trailing parens then double quotes if existing 3173 $title = substr($title, 1, -1); 3174 if ($title =~ /^".*"$/) { 3175 $title = substr($title, 1, -1); 3176 $title_has_quotes = 1; 3177 } 3178 } 3179 3180 my ($cid, $ctitle) = git_commit_info($orig_commit, $id, 3181 $title); 3182 3183 if ($ctitle ne $title || $tag_case || $tag_space || 3184 $id_length || $id_case || !$title_has_quotes) { 3185 if (WARN("BAD_FIXES_TAG", 3186 "Please use correct Fixes: style 'Fixes: <12 chars of sha1> (\"<title line>\")' - ie: 'Fixes: $cid (\"$ctitle\")'\n" . $herecurr) && 3187 $fix) { 3188 $fixed[$fixlinenr] = "Fixes: $cid (\"$ctitle\")"; 3189 } 3190 } 3191 } 3192 3193# Check email subject for common tools that don't need to be mentioned 3194 if ($in_header_lines && 3195 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) { 3196 WARN("EMAIL_SUBJECT", 3197 "A patch subject line should describe the change not the tool that found it\n" . $herecurr); 3198 } 3199 3200# Check for Gerrit Change-Ids not in any patch context 3201 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) { 3202 if (ERROR("GERRIT_CHANGE_ID", 3203 "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) && 3204 $fix) { 3205 fix_delete_line($fixlinenr, $rawline); 3206 } 3207 } 3208 3209# Check if the commit log is in a possible stack dump 3210 if ($in_commit_log && !$commit_log_possible_stack_dump && 3211 ($line =~ /^\s*(?:WARNING:|BUG:)/ || 3212 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ || 3213 # timestamp 3214 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) || 3215 $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ || 3216 $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) { 3217 # stack dump address styles 3218 $commit_log_possible_stack_dump = 1; 3219 } 3220 3221# Check for line lengths > 75 in commit log, warn once 3222 if ($in_commit_log && !$commit_log_long_line && 3223 length($line) > 75 && 3224 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ || 3225 # file delta changes 3226 $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ || 3227 # filename then : 3228 $line =~ /^\s*(?:Fixes:|Link:|$signature_tags)/i || 3229 # A Fixes: or Link: line or signature tag line 3230 $commit_log_possible_stack_dump)) { 3231 WARN("COMMIT_LOG_LONG_LINE", 3232 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr); 3233 $commit_log_long_line = 1; 3234 } 3235 3236# Reset possible stack dump if a blank line is found 3237 if ($in_commit_log && $commit_log_possible_stack_dump && 3238 $line =~ /^\s*$/) { 3239 $commit_log_possible_stack_dump = 0; 3240 } 3241 3242# Check for lines starting with a # 3243 if ($in_commit_log && $line =~ /^#/) { 3244 if (WARN("COMMIT_COMMENT_SYMBOL", 3245 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) && 3246 $fix) { 3247 $fixed[$fixlinenr] =~ s/^/ /; 3248 } 3249 } 3250 3251# Check for git id commit length and improperly formed commit descriptions 3252# A correctly formed commit description is: 3253# commit <SHA-1 hash length 12+ chars> ("Complete commit subject") 3254# with the commit subject '("' prefix and '")' suffix 3255# This is a fairly compilicated block as it tests for what appears to be 3256# bare SHA-1 hash with minimum length of 5. It also avoids several types of 3257# possible SHA-1 matches. 3258# A commit match can span multiple lines so this block attempts to find a 3259# complete typical commit on a maximum of 3 lines 3260 if ($perl_version_ok && 3261 $in_commit_log && !$commit_log_possible_stack_dump && 3262 $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i && 3263 $line !~ /^This reverts commit [0-9a-f]{7,40}/ && 3264 (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i || 3265 ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) || 3266 ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i && 3267 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i && 3268 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) { 3269 my $init_char = "c"; 3270 my $orig_commit = ""; 3271 my $short = 1; 3272 my $long = 0; 3273 my $case = 1; 3274 my $space = 1; 3275 my $id = '0123456789ab'; 3276 my $orig_desc = "commit description"; 3277 my $description = ""; 3278 my $herectx = $herecurr; 3279 my $has_parens = 0; 3280 my $has_quotes = 0; 3281 3282 my $input = $line; 3283 if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) { 3284 for (my $n = 0; $n < 2; $n++) { 3285 if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) { 3286 $orig_desc = $1; 3287 $has_parens = 1; 3288 # Always strip leading/trailing parens then double quotes if existing 3289 $orig_desc = substr($orig_desc, 1, -1); 3290 if ($orig_desc =~ /^".*"$/) { 3291 $orig_desc = substr($orig_desc, 1, -1); 3292 $has_quotes = 1; 3293 } 3294 last; 3295 } 3296 last if ($#lines < $linenr + $n); 3297 $input .= " " . trim($rawlines[$linenr + $n]); 3298 $herectx .= "$rawlines[$linenr + $n]\n"; 3299 } 3300 $herectx = $herecurr if (!$has_parens); 3301 } 3302 3303 if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) { 3304 $init_char = $1; 3305 $orig_commit = lc($2); 3306 $short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i); 3307 $long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i); 3308 $space = 0 if ($input =~ /\bcommit [0-9a-f]/i); 3309 $case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/); 3310 } elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) { 3311 $orig_commit = lc($1); 3312 } 3313 3314 ($id, $description) = git_commit_info($orig_commit, 3315 $id, $orig_desc); 3316 3317 if (defined($id) && 3318 ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) && 3319 $last_git_commit_id_linenr != $linenr - 1) { 3320 ERROR("GIT_COMMIT_ID", 3321 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx); 3322 } 3323 #don't report the next line if this line ends in commit and the sha1 hash is the next line 3324 $last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i); 3325 } 3326 3327# Check for added, moved or deleted files 3328 if (!$reported_maintainer_file && !$in_commit_log && 3329 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ || 3330 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ || 3331 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ && 3332 (defined($1) || defined($2))))) { 3333 $is_patch = 1; 3334 $reported_maintainer_file = 1; 3335 WARN("FILE_PATH_CHANGES", 3336 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr); 3337 } 3338 3339# Check for adding new DT bindings not in schema format 3340 if (!$in_commit_log && 3341 ($line =~ /^new file mode\s*\d+\s*$/) && 3342 ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) { 3343 WARN("DT_SCHEMA_BINDING_PATCH", 3344 "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n"); 3345 } 3346 3347# Check for wrappage within a valid hunk of the file 3348 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) { 3349 ERROR("CORRUPTED_PATCH", 3350 "patch seems to be corrupt (line wrapped?)\n" . 3351 $herecurr) if (!$emitted_corrupt++); 3352 } 3353 3354# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php 3355 if (($realfile =~ /^$/ || $line =~ /^\+/) && 3356 $rawline !~ m/^$UTF8*$/) { 3357 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/); 3358 3359 my $blank = copy_spacing($rawline); 3360 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^"; 3361 my $hereptr = "$hereline$ptr\n"; 3362 3363 CHK("INVALID_UTF8", 3364 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr); 3365 } 3366 3367# Check if it's the start of a commit log 3368# (not a header line and we haven't seen the patch filename) 3369 if ($in_header_lines && $realfile =~ /^$/ && 3370 !($rawline =~ /^\s+(?:\S|$)/ || 3371 $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) { 3372 $in_header_lines = 0; 3373 $in_commit_log = 1; 3374 $has_commit_log = 1; 3375 } 3376 3377# Check if there is UTF-8 in a commit log when a mail header has explicitly 3378# declined it, i.e defined some charset where it is missing. 3379 if ($in_header_lines && 3380 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ && 3381 $1 !~ /utf-8/i) { 3382 $non_utf8_charset = 1; 3383 } 3384 3385 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ && 3386 $rawline =~ /$NON_ASCII_UTF8/) { 3387 WARN("UTF8_BEFORE_PATCH", 3388 "8-bit UTF-8 used in possible commit log\n" . $herecurr); 3389 } 3390 3391# Check for absolute kernel paths in commit message 3392 if ($tree && $in_commit_log) { 3393 while ($line =~ m{(?:^|\s)(/\S*)}g) { 3394 my $file = $1; 3395 3396 if ($file =~ m{^(.*?)(?::\d+)+:?$} && 3397 check_absolute_file($1, $herecurr)) { 3398 # 3399 } else { 3400 check_absolute_file($file, $herecurr); 3401 } 3402 } 3403 } 3404 3405# Check for various typo / spelling mistakes 3406 if (defined($misspellings) && 3407 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) { 3408 while ($rawline =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) { 3409 my $typo = $1; 3410 my $blank = copy_spacing($rawline); 3411 my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo); 3412 my $hereptr = "$hereline$ptr\n"; 3413 my $typo_fix = $spelling_fix{lc($typo)}; 3414 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/); 3415 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/); 3416 my $msg_level = \&WARN; 3417 $msg_level = \&CHK if ($file); 3418 if (&{$msg_level}("TYPO_SPELLING", 3419 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) && 3420 $fix) { 3421 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/; 3422 } 3423 } 3424 } 3425 3426# check for invalid commit id 3427 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) { 3428 my $id; 3429 my $description; 3430 ($id, $description) = git_commit_info($2, undef, undef); 3431 if (!defined($id)) { 3432 WARN("UNKNOWN_COMMIT_ID", 3433 "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr); 3434 } 3435 } 3436 3437# check for repeated words separated by a single space 3438# avoid false positive from list command eg, '-rw-r--r-- 1 root root' 3439 if (($rawline =~ /^\+/ || $in_commit_log) && 3440 $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) { 3441 pos($rawline) = 1 if (!$in_commit_log); 3442 while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) { 3443 3444 my $first = $1; 3445 my $second = $2; 3446 my $start_pos = $-[1]; 3447 my $end_pos = $+[2]; 3448 if ($first =~ /(?:struct|union|enum)/) { 3449 pos($rawline) += length($first) + length($second) + 1; 3450 next; 3451 } 3452 3453 next if (lc($first) ne lc($second)); 3454 next if ($first eq 'long'); 3455 3456 # check for character before and after the word matches 3457 my $start_char = ''; 3458 my $end_char = ''; 3459 $start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1)); 3460 $end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline)); 3461 3462 next if ($start_char =~ /^\S$/); 3463 next if (index(" \t.,;?!", $end_char) == -1); 3464 3465 # avoid repeating hex occurrences like 'ff ff fe 09 ...' 3466 if ($first =~ /\b[0-9a-f]{2,}\b/i) { 3467 next if (!exists($allow_repeated_words{lc($first)})); 3468 } 3469 3470 if (WARN("REPEATED_WORD", 3471 "Possible repeated word: '$first'\n" . $herecurr) && 3472 $fix) { 3473 $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/; 3474 } 3475 } 3476 3477 # if it's a repeated word on consecutive lines in a comment block 3478 if ($prevline =~ /$;+\s*$/ && 3479 $prevrawline =~ /($word_pattern)\s*$/) { 3480 my $last_word = $1; 3481 if ($rawline =~ /^\+\s*\*\s*$last_word /) { 3482 if (WARN("REPEATED_WORD", 3483 "Possible repeated word: '$last_word'\n" . $hereprev) && 3484 $fix) { 3485 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/; 3486 } 3487 } 3488 } 3489 } 3490 3491# ignore non-hunk lines and lines being removed 3492 next if (!$hunk_line || $line =~ /^-/); 3493 3494#trailing whitespace 3495 if ($line =~ /^\+.*\015/) { 3496 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 3497 if (ERROR("DOS_LINE_ENDINGS", 3498 "DOS line endings\n" . $herevet) && 3499 $fix) { 3500 $fixed[$fixlinenr] =~ s/[\s\015]+$//; 3501 } 3502 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) { 3503 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 3504 if (ERROR("TRAILING_WHITESPACE", 3505 "trailing whitespace\n" . $herevet) && 3506 $fix) { 3507 $fixed[$fixlinenr] =~ s/\s+$//; 3508 } 3509 3510 $rpt_cleaners = 1; 3511 } 3512 3513# Check for FSF mailing addresses. 3514 if ($rawline =~ /\bwrite to the Free/i || 3515 $rawline =~ /\b675\s+Mass\s+Ave/i || 3516 $rawline =~ /\b59\s+Temple\s+Pl/i || 3517 $rawline =~ /\b51\s+Franklin\s+St/i) { 3518 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 3519 my $msg_level = \&ERROR; 3520 $msg_level = \&CHK if ($file); 3521 &{$msg_level}("FSF_MAILING_ADDRESS", 3522 "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) 3523 } 3524 3525# check for Kconfig help text having a real description 3526# Only applies when adding the entry originally, after that we do not have 3527# sufficient context to determine whether it is indeed long enough. 3528 if ($realfile =~ /Kconfig/ && 3529 # 'choice' is usually the last thing on the line (though 3530 # Kconfig supports named choices), so use a word boundary 3531 # (\b) rather than a whitespace character (\s) 3532 $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) { 3533 my $ln = $linenr; 3534 my $needs_help = 0; 3535 my $has_help = 0; 3536 my $help_length = 0; 3537 while (defined $lines[$ln]) { 3538 my $f = $lines[$ln++]; 3539 3540 next if ($f =~ /^-/); 3541 last if ($f !~ /^[\+ ]/); # !patch context 3542 3543 if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) { 3544 $needs_help = 1; 3545 next; 3546 } 3547 if ($f =~ /^\+\s*help\s*$/) { 3548 $has_help = 1; 3549 next; 3550 } 3551 3552 $f =~ s/^.//; # strip patch context [+ ] 3553 $f =~ s/#.*//; # strip # directives 3554 $f =~ s/^\s+//; # strip leading blanks 3555 next if ($f =~ /^$/); # skip blank lines 3556 3557 # At the end of this Kconfig block: 3558 # This only checks context lines in the patch 3559 # and so hopefully shouldn't trigger false 3560 # positives, even though some of these are 3561 # common words in help texts 3562 if ($f =~ /^(?:config|menuconfig|choice|endchoice| 3563 if|endif|menu|endmenu|source)\b/x) { 3564 last; 3565 } 3566 $help_length++ if ($has_help); 3567 } 3568 if ($needs_help && 3569 $help_length < $min_conf_desc_length) { 3570 my $stat_real = get_stat_real($linenr, $ln - 1); 3571 WARN("CONFIG_DESCRIPTION", 3572 "please write a help paragraph that fully describes the config symbol\n" . "$here\n$stat_real\n"); 3573 } 3574 } 3575 3576# check MAINTAINERS entries 3577 if ($realfile =~ /^MAINTAINERS$/) { 3578# check MAINTAINERS entries for the right form 3579 if ($rawline =~ /^\+[A-Z]:/ && 3580 $rawline !~ /^\+[A-Z]:\t\S/) { 3581 if (WARN("MAINTAINERS_STYLE", 3582 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) && 3583 $fix) { 3584 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/; 3585 } 3586 } 3587# check MAINTAINERS entries for the right ordering too 3588 my $preferred_order = 'MRLSWQBCPTFXNK'; 3589 if ($rawline =~ /^\+[A-Z]:/ && 3590 $prevrawline =~ /^[\+ ][A-Z]:/) { 3591 $rawline =~ /^\+([A-Z]):\s*(.*)/; 3592 my $cur = $1; 3593 my $curval = $2; 3594 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/; 3595 my $prev = $1; 3596 my $prevval = $2; 3597 my $curindex = index($preferred_order, $cur); 3598 my $previndex = index($preferred_order, $prev); 3599 if ($curindex < 0) { 3600 WARN("MAINTAINERS_STYLE", 3601 "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr); 3602 } else { 3603 if ($previndex >= 0 && $curindex < $previndex) { 3604 WARN("MAINTAINERS_STYLE", 3605 "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev); 3606 } elsif ((($prev eq 'F' && $cur eq 'F') || 3607 ($prev eq 'X' && $cur eq 'X')) && 3608 ($prevval cmp $curval) > 0) { 3609 WARN("MAINTAINERS_STYLE", 3610 "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev); 3611 } 3612 } 3613 } 3614 } 3615 3616 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) && 3617 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) { 3618 my $flag = $1; 3619 my $replacement = { 3620 'EXTRA_AFLAGS' => 'asflags-y', 3621 'EXTRA_CFLAGS' => 'ccflags-y', 3622 'EXTRA_CPPFLAGS' => 'cppflags-y', 3623 'EXTRA_LDFLAGS' => 'ldflags-y', 3624 }; 3625 3626 WARN("DEPRECATED_VARIABLE", 3627 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag}); 3628 } 3629 3630# check for DT compatible documentation 3631 if (defined $root && 3632 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) || 3633 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) { 3634 3635 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g; 3636 3637 my $dt_path = $root . "/Documentation/devicetree/bindings/"; 3638 my $vp_file = $dt_path . "vendor-prefixes.yaml"; 3639 3640 foreach my $compat (@compats) { 3641 my $compat2 = $compat; 3642 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/; 3643 my $compat3 = $compat; 3644 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/; 3645 `grep -Erq "$compat|$compat2|$compat3" $dt_path`; 3646 if ( $? >> 8 ) { 3647 WARN("UNDOCUMENTED_DT_STRING", 3648 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr); 3649 } 3650 3651 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/; 3652 my $vendor = $1; 3653 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`; 3654 if ( $? >> 8 ) { 3655 WARN("UNDOCUMENTED_DT_STRING", 3656 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr); 3657 } 3658 } 3659 } 3660 3661# check for using SPDX license tag at beginning of files 3662 if ($realline == $checklicenseline) { 3663 if ($rawline =~ /^[ \+]\s*\#\!\s*\//) { 3664 $checklicenseline = 2; 3665 } elsif ($rawline =~ /^\+/) { 3666 my $comment = ""; 3667 if ($realfile =~ /\.(h|s|S)$/) { 3668 $comment = '/*'; 3669 } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) { 3670 $comment = '//'; 3671 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) { 3672 $comment = '#'; 3673 } elsif ($realfile =~ /\.rst$/) { 3674 $comment = '..'; 3675 } 3676 3677# check SPDX comment style for .[chsS] files 3678 if ($realfile =~ /\.[chsS]$/ && 3679 $rawline =~ /SPDX-License-Identifier:/ && 3680 $rawline !~ m@^\+\s*\Q$comment\E\s*@) { 3681 WARN("SPDX_LICENSE_TAG", 3682 "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr); 3683 } 3684 3685 if ($comment !~ /^$/ && 3686 $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) { 3687 WARN("SPDX_LICENSE_TAG", 3688 "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr); 3689 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) { 3690 my $spdx_license = $1; 3691 if (!is_SPDX_License_valid($spdx_license)) { 3692 WARN("SPDX_LICENSE_TAG", 3693 "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr); 3694 } 3695 if ($realfile =~ m@^Documentation/devicetree/bindings/@ && 3696 not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) { 3697 my $msg_level = \&WARN; 3698 $msg_level = \&CHK if ($file); 3699 if (&{$msg_level}("SPDX_LICENSE_TAG", 3700 3701 "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) && 3702 $fix) { 3703 $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/; 3704 } 3705 } 3706 } 3707 } 3708 } 3709 3710# check for embedded filenames 3711 if ($rawline =~ /^\+.*\Q$realfile\E/) { 3712 WARN("EMBEDDED_FILENAME", 3713 "It's generally not useful to have the filename in the file\n" . $herecurr); 3714 } 3715 3716# check we are in a valid source file if not then ignore this hunk 3717 next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/); 3718 3719# check for using SPDX-License-Identifier on the wrong line number 3720 if ($realline != $checklicenseline && 3721 $rawline =~ /\bSPDX-License-Identifier:/ && 3722 substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) { 3723 WARN("SPDX_LICENSE_TAG", 3724 "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr); 3725 } 3726 3727# line length limit (with some exclusions) 3728# 3729# There are a few types of lines that may extend beyond $max_line_length: 3730# logging functions like pr_info that end in a string 3731# lines with a single string 3732# #defines that are a single string 3733# lines with an RFC3986 like URL 3734# 3735# There are 3 different line length message types: 3736# LONG_LINE_COMMENT a comment starts before but extends beyond $max_line_length 3737# LONG_LINE_STRING a string starts before but extends beyond $max_line_length 3738# LONG_LINE all other lines longer than $max_line_length 3739# 3740# if LONG_LINE is ignored, the other 2 types are also ignored 3741# 3742 3743 if ($line =~ /^\+/ && $length > $max_line_length) { 3744 my $msg_type = "LONG_LINE"; 3745 3746 # Check the allowed long line types first 3747 3748 # logging functions that end in a string that starts 3749 # before $max_line_length 3750 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ && 3751 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) { 3752 $msg_type = ""; 3753 3754 # lines with only strings (w/ possible termination) 3755 # #defines with only strings 3756 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ || 3757 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) { 3758 $msg_type = ""; 3759 3760 # More special cases 3761 } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ || 3762 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) { 3763 $msg_type = ""; 3764 3765 # URL ($rawline is used in case the URL is in a comment) 3766 } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) { 3767 $msg_type = ""; 3768 3769 # Otherwise set the alternate message types 3770 3771 # a comment starts before $max_line_length 3772 } elsif ($line =~ /($;[\s$;]*)$/ && 3773 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) { 3774 $msg_type = "LONG_LINE_COMMENT" 3775 3776 # a quoted string starts before $max_line_length 3777 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ && 3778 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) { 3779 $msg_type = "LONG_LINE_STRING" 3780 } 3781 3782 if ($msg_type ne "" && 3783 (show_type("LONG_LINE") || show_type($msg_type))) { 3784 my $msg_level = \&WARN; 3785 $msg_level = \&CHK if ($file); 3786 &{$msg_level}($msg_type, 3787 "line length of $length exceeds $max_line_length columns\n" . $herecurr); 3788 } 3789 } 3790 3791# check for adding lines without a newline. 3792 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) { 3793 if (WARN("MISSING_EOF_NEWLINE", 3794 "adding a line without newline at end of file\n" . $herecurr) && 3795 $fix) { 3796 fix_delete_line($fixlinenr+1, "No newline at end of file"); 3797 } 3798 } 3799 3800# check for .L prefix local symbols in .S files 3801 if ($realfile =~ /\.S$/ && 3802 $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) { 3803 WARN("AVOID_L_PREFIX", 3804 "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr); 3805 } 3806 3807# check we are in a valid source file C or perl if not then ignore this hunk 3808 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/); 3809 3810# at the beginning of a line any tabs must come first and anything 3811# more than $tabsize must use tabs. 3812 if ($rawline =~ /^\+\s* \t\s*\S/ || 3813 $rawline =~ /^\+\s* \s*/) { 3814 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 3815 $rpt_cleaners = 1; 3816 if (ERROR("CODE_INDENT", 3817 "code indent should use tabs where possible\n" . $herevet) && 3818 $fix) { 3819 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e; 3820 } 3821 } 3822 3823# check for space before tabs. 3824 if ($rawline =~ /^\+/ && $rawline =~ / \t/) { 3825 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 3826 if (WARN("SPACE_BEFORE_TAB", 3827 "please, no space before tabs\n" . $herevet) && 3828 $fix) { 3829 while ($fixed[$fixlinenr] =~ 3830 s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {} 3831 while ($fixed[$fixlinenr] =~ 3832 s/(^\+.*) +\t/$1\t/) {} 3833 } 3834 } 3835 3836# check for assignments on the start of a line 3837 if ($sline =~ /^\+\s+($Assignment)[^=]/) { 3838 my $operator = $1; 3839 if (CHK("ASSIGNMENT_CONTINUATIONS", 3840 "Assignment operator '$1' should be on the previous line\n" . $hereprev) && 3841 $fix && $prevrawline =~ /^\+/) { 3842 # add assignment operator to the previous line, remove from current line 3843 $fixed[$fixlinenr - 1] .= " $operator"; 3844 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//; 3845 } 3846 } 3847 3848# check for && or || at the start of a line 3849 if ($rawline =~ /^\+\s*(&&|\|\|)/) { 3850 my $operator = $1; 3851 if (CHK("LOGICAL_CONTINUATIONS", 3852 "Logical continuations should be on the previous line\n" . $hereprev) && 3853 $fix && $prevrawline =~ /^\+/) { 3854 # insert logical operator at last non-comment, non-whitepsace char on previous line 3855 $prevline =~ /[\s$;]*$/; 3856 my $line_end = substr($prevrawline, $-[0]); 3857 $fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/; 3858 $fixed[$fixlinenr] =~ s/\Q$operator\E\s*//; 3859 } 3860 } 3861 3862# check indentation starts on a tab stop 3863 if ($perl_version_ok && 3864 $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) { 3865 my $indent = length($1); 3866 if ($indent % $tabsize) { 3867 if (WARN("TABSTOP", 3868 "Statements should start on a tabstop\n" . $herecurr) && 3869 $fix) { 3870 $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e; 3871 } 3872 } 3873 } 3874 3875# check multi-line statement indentation matches previous line 3876 if ($perl_version_ok && 3877 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) { 3878 $prevline =~ /^\+(\t*)(.*)$/; 3879 my $oldindent = $1; 3880 my $rest = $2; 3881 3882 my $pos = pos_last_openparen($rest); 3883 if ($pos >= 0) { 3884 $line =~ /^(\+| )([ \t]*)/; 3885 my $newindent = $2; 3886 3887 my $goodtabindent = $oldindent . 3888 "\t" x ($pos / $tabsize) . 3889 " " x ($pos % $tabsize); 3890 my $goodspaceindent = $oldindent . " " x $pos; 3891 3892 if ($newindent ne $goodtabindent && 3893 $newindent ne $goodspaceindent) { 3894 3895 if (CHK("PARENTHESIS_ALIGNMENT", 3896 "Alignment should match open parenthesis\n" . $hereprev) && 3897 $fix && $line =~ /^\+/) { 3898 $fixed[$fixlinenr] =~ 3899 s/^\+[ \t]*/\+$goodtabindent/; 3900 } 3901 } 3902 } 3903 } 3904 3905# check for space after cast like "(int) foo" or "(struct foo) bar" 3906# avoid checking a few false positives: 3907# "sizeof(<type>)" or "__alignof__(<type>)" 3908# function pointer declarations like "(*foo)(int) = bar;" 3909# structure definitions like "(struct foo) { 0 };" 3910# multiline macros that define functions 3911# known attributes or the __attribute__ keyword 3912 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ && 3913 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) { 3914 if (CHK("SPACING", 3915 "No space is necessary after a cast\n" . $herecurr) && 3916 $fix) { 3917 $fixed[$fixlinenr] =~ 3918 s/(\(\s*$Type\s*\))[ \t]+/$1/; 3919 } 3920 } 3921 3922# Block comment styles 3923# Networking with an initial /* 3924 if ($realfile =~ m@^(drivers/net/|net/)@ && 3925 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ && 3926 $rawline =~ /^\+[ \t]*\*/ && 3927 $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier 3928 WARN("NETWORKING_BLOCK_COMMENT_STYLE", 3929 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev); 3930 } 3931 3932# Block comments use * on subsequent lines 3933 if ($prevline =~ /$;[ \t]*$/ && #ends in comment 3934 $prevrawline =~ /^\+.*?\/\*/ && #starting /* 3935 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */ 3936 $rawline =~ /^\+/ && #line is new 3937 $rawline !~ /^\+[ \t]*\*/) { #no leading * 3938 WARN("BLOCK_COMMENT_STYLE", 3939 "Block comments use * on subsequent lines\n" . $hereprev); 3940 } 3941 3942# Block comments use */ on trailing lines 3943 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */ 3944 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/ 3945 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/ 3946 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */ 3947 WARN("BLOCK_COMMENT_STYLE", 3948 "Block comments use a trailing */ on a separate line\n" . $herecurr); 3949 } 3950 3951# Block comment * alignment 3952 if ($prevline =~ /$;[ \t]*$/ && #ends in comment 3953 $line =~ /^\+[ \t]*$;/ && #leading comment 3954 $rawline =~ /^\+[ \t]*\*/ && #leading * 3955 (($prevrawline =~ /^\+.*?\/\*/ && #leading /* 3956 $prevrawline !~ /\*\/[ \t]*$/) || #no trailing */ 3957 $prevrawline =~ /^\+[ \t]*\*/)) { #leading * 3958 my $oldindent; 3959 $prevrawline =~ m@^\+([ \t]*/?)\*@; 3960 if (defined($1)) { 3961 $oldindent = expand_tabs($1); 3962 } else { 3963 $prevrawline =~ m@^\+(.*/?)\*@; 3964 $oldindent = expand_tabs($1); 3965 } 3966 $rawline =~ m@^\+([ \t]*)\*@; 3967 my $newindent = $1; 3968 $newindent = expand_tabs($newindent); 3969 if (length($oldindent) ne length($newindent)) { 3970 WARN("BLOCK_COMMENT_STYLE", 3971 "Block comments should align the * on each line\n" . $hereprev); 3972 } 3973 } 3974 3975# check for missing blank lines after struct/union declarations 3976# with exceptions for various attributes and macros 3977 if ($prevline =~ /^[\+ ]};?\s*$/ && 3978 $line =~ /^\+/ && 3979 !($line =~ /^\+\s*$/ || 3980 $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param)/ || 3981 $line =~ /^\+\s*MODULE_/i || 3982 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ || 3983 $line =~ /^\+[a-z_]*init/ || 3984 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ || 3985 $line =~ /^\+\s*DECLARE/ || 3986 $line =~ /^\+\s*builtin_[\w_]*driver/ || 3987 $line =~ /^\+\s*__setup/)) { 3988 if (CHK("LINE_SPACING", 3989 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) && 3990 $fix) { 3991 fix_insert_line($fixlinenr, "\+"); 3992 } 3993 } 3994 3995# check for multiple consecutive blank lines 3996 if ($prevline =~ /^[\+ ]\s*$/ && 3997 $line =~ /^\+\s*$/ && 3998 $last_blank_line != ($linenr - 1)) { 3999 if (CHK("LINE_SPACING", 4000 "Please don't use multiple blank lines\n" . $hereprev) && 4001 $fix) { 4002 fix_delete_line($fixlinenr, $rawline); 4003 } 4004 4005 $last_blank_line = $linenr; 4006 } 4007 4008# check for missing blank lines after declarations 4009# (declarations must have the same indentation and not be at the start of line) 4010 if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) { 4011 # use temporaries 4012 my $sl = $sline; 4013 my $pl = $prevline; 4014 # remove $Attribute/$Sparse uses to simplify comparisons 4015 $sl =~ s/\b(?:$Attribute|$Sparse)\b//g; 4016 $pl =~ s/\b(?:$Attribute|$Sparse)\b//g; 4017 if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ || 4018 # function pointer declarations 4019 $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ || 4020 # foo bar; where foo is some local typedef or #define 4021 $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ || 4022 # known declaration macros 4023 $pl =~ /^\+\s+$declaration_macros/) && 4024 # for "else if" which can look like "$Ident $Ident" 4025 !($pl =~ /^\+\s+$c90_Keywords\b/ || 4026 # other possible extensions of declaration lines 4027 $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ || 4028 # not starting a section or a macro "\" extended line 4029 $pl =~ /(?:\{\s*|\\)$/) && 4030 # looks like a declaration 4031 !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ || 4032 # function pointer declarations 4033 $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ || 4034 # foo bar; where foo is some local typedef or #define 4035 $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ || 4036 # known declaration macros 4037 $sl =~ /^\+\s+$declaration_macros/ || 4038 # start of struct or union or enum 4039 $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ || 4040 # start or end of block or continuation of declaration 4041 $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ || 4042 # bitfield continuation 4043 $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ || 4044 # other possible extensions of declaration lines 4045 $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) { 4046 if (WARN("LINE_SPACING", 4047 "Missing a blank line after declarations\n" . $hereprev) && 4048 $fix) { 4049 fix_insert_line($fixlinenr, "\+"); 4050 } 4051 } 4052 } 4053 4054# check for spaces at the beginning of a line. 4055# Exceptions: 4056# 1) within comments 4057# 2) indented preprocessor commands 4058# 3) hanging labels 4059 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) { 4060 my $herevet = "$here\n" . cat_vet($rawline) . "\n"; 4061 if (WARN("LEADING_SPACE", 4062 "please, no spaces at the start of a line\n" . $herevet) && 4063 $fix) { 4064 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e; 4065 } 4066 } 4067 4068# check we are in a valid C source file if not then ignore this hunk 4069 next if ($realfile !~ /\.(h|c)$/); 4070 4071# check for unusual line ending [ or ( 4072 if ($line =~ /^\+.*([\[\(])\s*$/) { 4073 CHK("OPEN_ENDED_LINE", 4074 "Lines should not end with a '$1'\n" . $herecurr); 4075 } 4076 4077# check if this appears to be the start function declaration, save the name 4078 if ($sline =~ /^\+\{\s*$/ && 4079 $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) { 4080 $context_function = $1; 4081 } 4082 4083# check if this appears to be the end of function declaration 4084 if ($sline =~ /^\+\}\s*$/) { 4085 undef $context_function; 4086 } 4087 4088# check indentation of any line with a bare else 4089# (but not if it is a multiple line "if (foo) return bar; else return baz;") 4090# if the previous line is a break or return and is indented 1 tab more... 4091 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) { 4092 my $tabs = length($1) + 1; 4093 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ || 4094 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ && 4095 defined $lines[$linenr] && 4096 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) { 4097 WARN("UNNECESSARY_ELSE", 4098 "else is not generally useful after a break or return\n" . $hereprev); 4099 } 4100 } 4101 4102# check indentation of a line with a break; 4103# if the previous line is a goto, return or break 4104# and is indented the same # of tabs 4105 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) { 4106 my $tabs = $1; 4107 if ($prevline =~ /^\+$tabs(goto|return|break)\b/) { 4108 if (WARN("UNNECESSARY_BREAK", 4109 "break is not useful after a $1\n" . $hereprev) && 4110 $fix) { 4111 fix_delete_line($fixlinenr, $rawline); 4112 } 4113 } 4114 } 4115 4116# check for RCS/CVS revision markers 4117 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) { 4118 WARN("CVS_KEYWORD", 4119 "CVS style keyword markers, these will _not_ be updated\n". $herecurr); 4120 } 4121 4122# check for old HOTPLUG __dev<foo> section markings 4123 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) { 4124 WARN("HOTPLUG_SECTION", 4125 "Using $1 is unnecessary\n" . $herecurr); 4126 } 4127 4128# Check for potential 'bare' types 4129 my ($stat, $cond, $line_nr_next, $remain_next, $off_next, 4130 $realline_next); 4131#print "LINE<$line>\n"; 4132 if ($linenr > $suppress_statement && 4133 $realcnt && $sline =~ /.\s*\S/) { 4134 ($stat, $cond, $line_nr_next, $remain_next, $off_next) = 4135 ctx_statement_block($linenr, $realcnt, 0); 4136 $stat =~ s/\n./\n /g; 4137 $cond =~ s/\n./\n /g; 4138 4139#print "linenr<$linenr> <$stat>\n"; 4140 # If this statement has no statement boundaries within 4141 # it there is no point in retrying a statement scan 4142 # until we hit end of it. 4143 my $frag = $stat; $frag =~ s/;+\s*$//; 4144 if ($frag !~ /(?:{|;)/) { 4145#print "skip<$line_nr_next>\n"; 4146 $suppress_statement = $line_nr_next; 4147 } 4148 4149 # Find the real next line. 4150 $realline_next = $line_nr_next; 4151 if (defined $realline_next && 4152 (!defined $lines[$realline_next - 1] || 4153 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) { 4154 $realline_next++; 4155 } 4156 4157 my $s = $stat; 4158 $s =~ s/{.*$//s; 4159 4160 # Ignore goto labels. 4161 if ($s =~ /$Ident:\*$/s) { 4162 4163 # Ignore functions being called 4164 } elsif ($s =~ /^.\s*$Ident\s*\(/s) { 4165 4166 } elsif ($s =~ /^.\s*else\b/s) { 4167 4168 # declarations always start with types 4169 } 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) { 4170 my $type = $1; 4171 $type =~ s/\s+/ /g; 4172 possible($type, "A:" . $s); 4173 4174 # definitions in global scope can only start with types 4175 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) { 4176 possible($1, "B:" . $s); 4177 } 4178 4179 # any (foo ... *) is a pointer cast, and foo is a type 4180 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) { 4181 possible($1, "C:" . $s); 4182 } 4183 4184 # Check for any sort of function declaration. 4185 # int foo(something bar, other baz); 4186 # void (*store_gdt)(x86_descr_ptr *); 4187 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) { 4188 my ($name_len) = length($1); 4189 4190 my $ctx = $s; 4191 substr($ctx, 0, $name_len + 1, ''); 4192 $ctx =~ s/\)[^\)]*$//; 4193 4194 for my $arg (split(/\s*,\s*/, $ctx)) { 4195 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) { 4196 4197 possible($1, "D:" . $s); 4198 } 4199 } 4200 } 4201 4202 } 4203 4204# 4205# Checks which may be anchored in the context. 4206# 4207 4208# Check for switch () and associated case and default 4209# statements should be at the same indent. 4210 if ($line=~/\bswitch\s*\(.*\)/) { 4211 my $err = ''; 4212 my $sep = ''; 4213 my @ctx = ctx_block_outer($linenr, $realcnt); 4214 shift(@ctx); 4215 for my $ctx (@ctx) { 4216 my ($clen, $cindent) = line_stats($ctx); 4217 if ($ctx =~ /^\+\s*(case\s+|default:)/ && 4218 $indent != $cindent) { 4219 $err .= "$sep$ctx\n"; 4220 $sep = ''; 4221 } else { 4222 $sep = "[...]\n"; 4223 } 4224 } 4225 if ($err ne '') { 4226 ERROR("SWITCH_CASE_INDENT_LEVEL", 4227 "switch and case should be at the same indent\n$hereline$err"); 4228 } 4229 } 4230 4231# if/while/etc brace do not go on next line, unless defining a do while loop, 4232# or if that brace on the next line is for something else 4233 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) { 4234 my $pre_ctx = "$1$2"; 4235 4236 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0); 4237 4238 if ($line =~ /^\+\t{6,}/) { 4239 WARN("DEEP_INDENTATION", 4240 "Too many leading tabs - consider code refactoring\n" . $herecurr); 4241 } 4242 4243 my $ctx_cnt = $realcnt - $#ctx - 1; 4244 my $ctx = join("\n", @ctx); 4245 4246 my $ctx_ln = $linenr; 4247 my $ctx_skip = $realcnt; 4248 4249 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt && 4250 defined $lines[$ctx_ln - 1] && 4251 $lines[$ctx_ln - 1] =~ /^-/)) { 4252 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n"; 4253 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/); 4254 $ctx_ln++; 4255 } 4256 4257 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n"; 4258 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n"; 4259 4260 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) { 4261 ERROR("OPEN_BRACE", 4262 "that open brace { should be on the previous line\n" . 4263 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); 4264 } 4265 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ && 4266 $ctx =~ /\)\s*\;\s*$/ && 4267 defined $lines[$ctx_ln - 1]) 4268 { 4269 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]); 4270 if ($nindent > $indent) { 4271 WARN("TRAILING_SEMICOLON", 4272 "trailing semicolon indicates no statements, indent implies otherwise\n" . 4273 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); 4274 } 4275 } 4276 } 4277 4278# Check relative indent for conditionals and blocks. 4279 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) { 4280 ($stat, $cond, $line_nr_next, $remain_next, $off_next) = 4281 ctx_statement_block($linenr, $realcnt, 0) 4282 if (!defined $stat); 4283 my ($s, $c) = ($stat, $cond); 4284 4285 substr($s, 0, length($c), ''); 4286 4287 # remove inline comments 4288 $s =~ s/$;/ /g; 4289 $c =~ s/$;/ /g; 4290 4291 # Find out how long the conditional actually is. 4292 my @newlines = ($c =~ /\n/gs); 4293 my $cond_lines = 1 + $#newlines; 4294 4295 # Make sure we remove the line prefixes as we have 4296 # none on the first line, and are going to readd them 4297 # where necessary. 4298 $s =~ s/\n./\n/gs; 4299 while ($s =~ /\n\s+\\\n/) { 4300 $cond_lines += $s =~ s/\n\s+\\\n/\n/g; 4301 } 4302 4303 # We want to check the first line inside the block 4304 # starting at the end of the conditional, so remove: 4305 # 1) any blank line termination 4306 # 2) any opening brace { on end of the line 4307 # 3) any do (...) { 4308 my $continuation = 0; 4309 my $check = 0; 4310 $s =~ s/^.*\bdo\b//; 4311 $s =~ s/^\s*{//; 4312 if ($s =~ s/^\s*\\//) { 4313 $continuation = 1; 4314 } 4315 if ($s =~ s/^\s*?\n//) { 4316 $check = 1; 4317 $cond_lines++; 4318 } 4319 4320 # Also ignore a loop construct at the end of a 4321 # preprocessor statement. 4322 if (($prevline =~ /^.\s*#\s*define\s/ || 4323 $prevline =~ /\\\s*$/) && $continuation == 0) { 4324 $check = 0; 4325 } 4326 4327 my $cond_ptr = -1; 4328 $continuation = 0; 4329 while ($cond_ptr != $cond_lines) { 4330 $cond_ptr = $cond_lines; 4331 4332 # If we see an #else/#elif then the code 4333 # is not linear. 4334 if ($s =~ /^\s*\#\s*(?:else|elif)/) { 4335 $check = 0; 4336 } 4337 4338 # Ignore: 4339 # 1) blank lines, they should be at 0, 4340 # 2) preprocessor lines, and 4341 # 3) labels. 4342 if ($continuation || 4343 $s =~ /^\s*?\n/ || 4344 $s =~ /^\s*#\s*?/ || 4345 $s =~ /^\s*$Ident\s*:/) { 4346 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0; 4347 if ($s =~ s/^.*?\n//) { 4348 $cond_lines++; 4349 } 4350 } 4351 } 4352 4353 my (undef, $sindent) = line_stats("+" . $s); 4354 my $stat_real = raw_line($linenr, $cond_lines); 4355 4356 # Check if either of these lines are modified, else 4357 # this is not this patch's fault. 4358 if (!defined($stat_real) || 4359 $stat !~ /^\+/ && $stat_real !~ /^\+/) { 4360 $check = 0; 4361 } 4362 if (defined($stat_real) && $cond_lines > 1) { 4363 $stat_real = "[...]\n$stat_real"; 4364 } 4365 4366 #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"; 4367 4368 if ($check && $s ne '' && 4369 (($sindent % $tabsize) != 0 || 4370 ($sindent < $indent) || 4371 ($sindent == $indent && 4372 ($s !~ /^\s*(?:\}|\{|else\b)/)) || 4373 ($sindent > $indent + $tabsize))) { 4374 WARN("SUSPECT_CODE_INDENT", 4375 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n"); 4376 } 4377 } 4378 4379 # Track the 'values' across context and added lines. 4380 my $opline = $line; $opline =~ s/^./ /; 4381 my ($curr_values, $curr_vars) = 4382 annotate_values($opline . "\n", $prev_values); 4383 $curr_values = $prev_values . $curr_values; 4384 if ($dbg_values) { 4385 my $outline = $opline; $outline =~ s/\t/ /g; 4386 print "$linenr > .$outline\n"; 4387 print "$linenr > $curr_values\n"; 4388 print "$linenr > $curr_vars\n"; 4389 } 4390 $prev_values = substr($curr_values, -1); 4391 4392#ignore lines not being added 4393 next if ($line =~ /^[^\+]/); 4394 4395# check for self assignments used to avoid compiler warnings 4396# e.g.: int foo = foo, *bar = NULL; 4397# struct foo bar = *(&(bar)); 4398 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) { 4399 my $var = $1; 4400 if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) { 4401 WARN("SELF_ASSIGNMENT", 4402 "Do not use self-assignments to avoid compiler warnings\n" . $herecurr); 4403 } 4404 } 4405 4406# check for dereferences that span multiple lines 4407 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ && 4408 $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) { 4409 $prevline =~ /($Lval\s*(?:\.|->))\s*$/; 4410 my $ref = $1; 4411 $line =~ /^.\s*($Lval)/; 4412 $ref .= $1; 4413 $ref =~ s/\s//g; 4414 WARN("MULTILINE_DEREFERENCE", 4415 "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev); 4416 } 4417 4418# check for declarations of signed or unsigned without int 4419 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) { 4420 my $type = $1; 4421 my $var = $2; 4422 $var = "" if (!defined $var); 4423 if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) { 4424 my $sign = $1; 4425 my $pointer = $2; 4426 4427 $pointer = "" if (!defined $pointer); 4428 4429 if (WARN("UNSPECIFIED_INT", 4430 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) && 4431 $fix) { 4432 my $decl = trim($sign) . " int "; 4433 my $comp_pointer = $pointer; 4434 $comp_pointer =~ s/\s//g; 4435 $decl .= $comp_pointer; 4436 $decl = rtrim($decl) if ($var eq ""); 4437 $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@; 4438 } 4439 } 4440 } 4441 4442# TEST: allow direct testing of the type matcher. 4443 if ($dbg_type) { 4444 if ($line =~ /^.\s*$Declare\s*$/) { 4445 ERROR("TEST_TYPE", 4446 "TEST: is type\n" . $herecurr); 4447 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) { 4448 ERROR("TEST_NOT_TYPE", 4449 "TEST: is not type ($1 is)\n". $herecurr); 4450 } 4451 next; 4452 } 4453# TEST: allow direct testing of the attribute matcher. 4454 if ($dbg_attr) { 4455 if ($line =~ /^.\s*$Modifier\s*$/) { 4456 ERROR("TEST_ATTR", 4457 "TEST: is attr\n" . $herecurr); 4458 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) { 4459 ERROR("TEST_NOT_ATTR", 4460 "TEST: is not attr ($1 is)\n". $herecurr); 4461 } 4462 next; 4463 } 4464 4465# check for initialisation to aggregates open brace on the next line 4466 if ($line =~ /^.\s*{/ && 4467 $prevline =~ /(?:^|[^=])=\s*$/) { 4468 if (ERROR("OPEN_BRACE", 4469 "that open brace { should be on the previous line\n" . $hereprev) && 4470 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) { 4471 fix_delete_line($fixlinenr - 1, $prevrawline); 4472 fix_delete_line($fixlinenr, $rawline); 4473 my $fixedline = $prevrawline; 4474 $fixedline =~ s/\s*=\s*$/ = {/; 4475 fix_insert_line($fixlinenr, $fixedline); 4476 $fixedline = $line; 4477 $fixedline =~ s/^(.\s*)\{\s*/$1/; 4478 fix_insert_line($fixlinenr, $fixedline); 4479 } 4480 } 4481 4482# 4483# Checks which are anchored on the added line. 4484# 4485 4486# check for malformed paths in #include statements (uses RAW line) 4487 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) { 4488 my $path = $1; 4489 if ($path =~ m{//}) { 4490 ERROR("MALFORMED_INCLUDE", 4491 "malformed #include filename\n" . $herecurr); 4492 } 4493 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) { 4494 ERROR("UAPI_INCLUDE", 4495 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr); 4496 } 4497 } 4498 4499# no C99 // comments 4500 if ($line =~ m{//}) { 4501 if (ERROR("C99_COMMENTS", 4502 "do not use C99 // comments\n" . $herecurr) && 4503 $fix) { 4504 my $line = $fixed[$fixlinenr]; 4505 if ($line =~ /\/\/(.*)$/) { 4506 my $comment = trim($1); 4507 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@; 4508 } 4509 } 4510 } 4511 # Remove C99 comments. 4512 $line =~ s@//.*@@; 4513 $opline =~ s@//.*@@; 4514 4515# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider 4516# the whole statement. 4517#print "APW <$lines[$realline_next - 1]>\n"; 4518 if (defined $realline_next && 4519 exists $lines[$realline_next - 1] && 4520 !defined $suppress_export{$realline_next} && 4521 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) { 4522 # Handle definitions which produce identifiers with 4523 # a prefix: 4524 # XXX(foo); 4525 # EXPORT_SYMBOL(something_foo); 4526 my $name = $1; 4527 $name =~ s/^\s*($Ident).*/$1/; 4528 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ && 4529 $name =~ /^${Ident}_$2/) { 4530#print "FOO C name<$name>\n"; 4531 $suppress_export{$realline_next} = 1; 4532 4533 } elsif ($stat !~ /(?: 4534 \n.}\s*$| 4535 ^.DEFINE_$Ident\(\Q$name\E\)| 4536 ^.DECLARE_$Ident\(\Q$name\E\)| 4537 ^.LIST_HEAD\(\Q$name\E\)| 4538 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(| 4539 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\() 4540 )/x) { 4541#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n"; 4542 $suppress_export{$realline_next} = 2; 4543 } else { 4544 $suppress_export{$realline_next} = 1; 4545 } 4546 } 4547 if (!defined $suppress_export{$linenr} && 4548 $prevline =~ /^.\s*$/ && 4549 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) { 4550#print "FOO B <$lines[$linenr - 1]>\n"; 4551 $suppress_export{$linenr} = 2; 4552 } 4553 if (defined $suppress_export{$linenr} && 4554 $suppress_export{$linenr} == 2) { 4555 WARN("EXPORT_SYMBOL", 4556 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr); 4557 } 4558 4559# check for global initialisers. 4560 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ && 4561 !exclude_global_initialisers($realfile)) { 4562 if (ERROR("GLOBAL_INITIALISERS", 4563 "do not initialise globals to $1\n" . $herecurr) && 4564 $fix) { 4565 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/; 4566 } 4567 } 4568# check for static initialisers. 4569 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) { 4570 if (ERROR("INITIALISED_STATIC", 4571 "do not initialise statics to $1\n" . 4572 $herecurr) && 4573 $fix) { 4574 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/; 4575 } 4576 } 4577 4578# check for misordered declarations of char/short/int/long with signed/unsigned 4579 while ($sline =~ m{(\b$TypeMisordered\b)}g) { 4580 my $tmp = trim($1); 4581 WARN("MISORDERED_TYPE", 4582 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr); 4583 } 4584 4585# check for unnecessary <signed> int declarations of short/long/long long 4586 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) { 4587 my $type = trim($1); 4588 next if ($type !~ /\bint\b/); 4589 next if ($type !~ /\b(?:short|long\s+long|long)\b/); 4590 my $new_type = $type; 4591 $new_type =~ s/\b\s*int\s*\b/ /; 4592 $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /; 4593 $new_type =~ s/^const\s+//; 4594 $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/); 4595 $new_type = "const $new_type" if ($type =~ /^const\b/); 4596 $new_type =~ s/\s+/ /g; 4597 $new_type = trim($new_type); 4598 if (WARN("UNNECESSARY_INT", 4599 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) && 4600 $fix) { 4601 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/; 4602 } 4603 } 4604 4605# check for static const char * arrays. 4606 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) { 4607 WARN("STATIC_CONST_CHAR_ARRAY", 4608 "static const char * array should probably be static const char * const\n" . 4609 $herecurr); 4610 } 4611 4612# check for initialized const char arrays that should be static const 4613 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) { 4614 if (WARN("STATIC_CONST_CHAR_ARRAY", 4615 "const array should probably be static const\n" . $herecurr) && 4616 $fix) { 4617 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/; 4618 } 4619 } 4620 4621# check for static char foo[] = "bar" declarations. 4622 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) { 4623 WARN("STATIC_CONST_CHAR_ARRAY", 4624 "static char array declaration should probably be static const char\n" . 4625 $herecurr); 4626 } 4627 4628# check for const <foo> const where <foo> is not a pointer or array type 4629 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) { 4630 my $found = $1; 4631 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) { 4632 WARN("CONST_CONST", 4633 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr); 4634 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) { 4635 WARN("CONST_CONST", 4636 "'const $found const' should probably be 'const $found'\n" . $herecurr); 4637 } 4638 } 4639 4640# check for const static or static <non ptr type> const declarations 4641# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const' 4642 if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ || 4643 $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) { 4644 if (WARN("STATIC_CONST", 4645 "Move const after static - use 'static const $1'\n" . $herecurr) && 4646 $fix) { 4647 $fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/; 4648 $fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/; 4649 } 4650 } 4651 4652# check for non-global char *foo[] = {"bar", ...} declarations. 4653 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) { 4654 WARN("STATIC_CONST_CHAR_ARRAY", 4655 "char * array declaration might be better as static const\n" . 4656 $herecurr); 4657 } 4658 4659# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo) 4660 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) { 4661 my $array = $1; 4662 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) { 4663 my $array_div = $1; 4664 if (WARN("ARRAY_SIZE", 4665 "Prefer ARRAY_SIZE($array)\n" . $herecurr) && 4666 $fix) { 4667 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/; 4668 } 4669 } 4670 } 4671 4672# check for function declarations without arguments like "int foo()" 4673 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) { 4674 if (ERROR("FUNCTION_WITHOUT_ARGS", 4675 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) && 4676 $fix) { 4677 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/; 4678 } 4679 } 4680 4681# check for new typedefs, only function parameters and sparse annotations 4682# make sense. 4683 if ($line =~ /\btypedef\s/ && 4684 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ && 4685 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ && 4686 $line !~ /\b$typeTypedefs\b/ && 4687 $line !~ /\b__bitwise\b/) { 4688 WARN("NEW_TYPEDEFS", 4689 "do not add new typedefs\n" . $herecurr); 4690 } 4691 4692# * goes on variable not on type 4693 # (char*[ const]) 4694 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) { 4695 #print "AA<$1>\n"; 4696 my ($ident, $from, $to) = ($1, $2, $2); 4697 4698 # Should start with a space. 4699 $to =~ s/^(\S)/ $1/; 4700 # Should not end with a space. 4701 $to =~ s/\s+$//; 4702 # '*'s should not have spaces between. 4703 while ($to =~ s/\*\s+\*/\*\*/) { 4704 } 4705 4706## print "1: from<$from> to<$to> ident<$ident>\n"; 4707 if ($from ne $to) { 4708 if (ERROR("POINTER_LOCATION", 4709 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) && 4710 $fix) { 4711 my $sub_from = $ident; 4712 my $sub_to = $ident; 4713 $sub_to =~ s/\Q$from\E/$to/; 4714 $fixed[$fixlinenr] =~ 4715 s@\Q$sub_from\E@$sub_to@; 4716 } 4717 } 4718 } 4719 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) { 4720 #print "BB<$1>\n"; 4721 my ($match, $from, $to, $ident) = ($1, $2, $2, $3); 4722 4723 # Should start with a space. 4724 $to =~ s/^(\S)/ $1/; 4725 # Should not end with a space. 4726 $to =~ s/\s+$//; 4727 # '*'s should not have spaces between. 4728 while ($to =~ s/\*\s+\*/\*\*/) { 4729 } 4730 # Modifiers should have spaces. 4731 $to =~ s/(\b$Modifier$)/$1 /; 4732 4733## print "2: from<$from> to<$to> ident<$ident>\n"; 4734 if ($from ne $to && $ident !~ /^$Modifier$/) { 4735 if (ERROR("POINTER_LOCATION", 4736 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) && 4737 $fix) { 4738 4739 my $sub_from = $match; 4740 my $sub_to = $match; 4741 $sub_to =~ s/\Q$from\E/$to/; 4742 $fixed[$fixlinenr] =~ 4743 s@\Q$sub_from\E@$sub_to@; 4744 } 4745 } 4746 } 4747 4748# do not use BUG() or variants 4749 if ($line =~ /\b(?!AA_|BUILD_|DCCP_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) { 4750 my $msg_level = \&WARN; 4751 $msg_level = \&CHK if ($file); 4752 &{$msg_level}("AVOID_BUG", 4753 "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr); 4754 } 4755 4756# avoid LINUX_VERSION_CODE 4757 if ($line =~ /\bLINUX_VERSION_CODE\b/) { 4758 WARN("LINUX_VERSION_CODE", 4759 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr); 4760 } 4761 4762# check for uses of printk_ratelimit 4763 if ($line =~ /\bprintk_ratelimit\s*\(/) { 4764 WARN("PRINTK_RATELIMITED", 4765 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr); 4766 } 4767 4768# printk should use KERN_* levels 4769 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) { 4770 WARN("PRINTK_WITHOUT_KERN_LEVEL", 4771 "printk() should include KERN_<LEVEL> facility level\n" . $herecurr); 4772 } 4773 4774# prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL> 4775 if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) { 4776 my $printk = $1; 4777 my $modifier = $2; 4778 my $orig = $3; 4779 $modifier = "" if (!defined($modifier)); 4780 my $level = lc($orig); 4781 $level = "warn" if ($level eq "warning"); 4782 my $level2 = $level; 4783 $level2 = "dbg" if ($level eq "debug"); 4784 $level .= $modifier; 4785 $level2 .= $modifier; 4786 WARN("PREFER_PR_LEVEL", 4787 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to $printk(KERN_$orig ...\n" . $herecurr); 4788 } 4789 4790# prefer dev_<level> to dev_printk(KERN_<LEVEL> 4791 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) { 4792 my $orig = $1; 4793 my $level = lc($orig); 4794 $level = "warn" if ($level eq "warning"); 4795 $level = "dbg" if ($level eq "debug"); 4796 WARN("PREFER_DEV_LEVEL", 4797 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr); 4798 } 4799 4800# trace_printk should not be used in production code. 4801 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) { 4802 WARN("TRACE_PRINTK", 4803 "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr); 4804 } 4805 4806# ENOSYS means "bad syscall nr" and nothing else. This will have a small 4807# number of false positives, but assembly files are not checked, so at 4808# least the arch entry code will not trigger this warning. 4809 if ($line =~ /\bENOSYS\b/) { 4810 WARN("ENOSYS", 4811 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr); 4812 } 4813 4814# ENOTSUPP is not a standard error code and should be avoided in new patches. 4815# Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP. 4816# Similarly to ENOSYS warning a small number of false positives is expected. 4817 if (!$file && $line =~ /\bENOTSUPP\b/) { 4818 if (WARN("ENOTSUPP", 4819 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) && 4820 $fix) { 4821 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/; 4822 } 4823 } 4824 4825# function brace can't be on same line, except for #defines of do while, 4826# or if closed on same line 4827 if ($perl_version_ok && 4828 $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ && 4829 $sline !~ /\#\s*define\b.*do\s*\{/ && 4830 $sline !~ /}/) { 4831 if (ERROR("OPEN_BRACE", 4832 "open brace '{' following function definitions go on the next line\n" . $herecurr) && 4833 $fix) { 4834 fix_delete_line($fixlinenr, $rawline); 4835 my $fixed_line = $rawline; 4836 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/; 4837 my $line1 = $1; 4838 my $line2 = $2; 4839 fix_insert_line($fixlinenr, ltrim($line1)); 4840 fix_insert_line($fixlinenr, "\+{"); 4841 if ($line2 !~ /^\s*$/) { 4842 fix_insert_line($fixlinenr, "\+\t" . trim($line2)); 4843 } 4844 } 4845 } 4846 4847# open braces for enum, union and struct go on the same line. 4848 if ($line =~ /^.\s*{/ && 4849 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) { 4850 if (ERROR("OPEN_BRACE", 4851 "open brace '{' following $1 go on the same line\n" . $hereprev) && 4852 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) { 4853 fix_delete_line($fixlinenr - 1, $prevrawline); 4854 fix_delete_line($fixlinenr, $rawline); 4855 my $fixedline = rtrim($prevrawline) . " {"; 4856 fix_insert_line($fixlinenr, $fixedline); 4857 $fixedline = $rawline; 4858 $fixedline =~ s/^(.\s*)\{\s*/$1\t/; 4859 if ($fixedline !~ /^\+\s*$/) { 4860 fix_insert_line($fixlinenr, $fixedline); 4861 } 4862 } 4863 } 4864 4865# missing space after union, struct or enum definition 4866 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) { 4867 if (WARN("SPACING", 4868 "missing space after $1 definition\n" . $herecurr) && 4869 $fix) { 4870 $fixed[$fixlinenr] =~ 4871 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/; 4872 } 4873 } 4874 4875# Function pointer declarations 4876# check spacing between type, funcptr, and args 4877# canonical declaration is "type (*funcptr)(args...)" 4878 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) { 4879 my $declare = $1; 4880 my $pre_pointer_space = $2; 4881 my $post_pointer_space = $3; 4882 my $funcname = $4; 4883 my $post_funcname_space = $5; 4884 my $pre_args_space = $6; 4885 4886# the $Declare variable will capture all spaces after the type 4887# so check it for a missing trailing missing space but pointer return types 4888# don't need a space so don't warn for those. 4889 my $post_declare_space = ""; 4890 if ($declare =~ /(\s+)$/) { 4891 $post_declare_space = $1; 4892 $declare = rtrim($declare); 4893 } 4894 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) { 4895 WARN("SPACING", 4896 "missing space after return type\n" . $herecurr); 4897 $post_declare_space = " "; 4898 } 4899 4900# unnecessary space "type (*funcptr)(args...)" 4901# This test is not currently implemented because these declarations are 4902# equivalent to 4903# int foo(int bar, ...) 4904# and this is form shouldn't/doesn't generate a checkpatch warning. 4905# 4906# elsif ($declare =~ /\s{2,}$/) { 4907# WARN("SPACING", 4908# "Multiple spaces after return type\n" . $herecurr); 4909# } 4910 4911# unnecessary space "type ( *funcptr)(args...)" 4912 if (defined $pre_pointer_space && 4913 $pre_pointer_space =~ /^\s/) { 4914 WARN("SPACING", 4915 "Unnecessary space after function pointer open parenthesis\n" . $herecurr); 4916 } 4917 4918# unnecessary space "type (* funcptr)(args...)" 4919 if (defined $post_pointer_space && 4920 $post_pointer_space =~ /^\s/) { 4921 WARN("SPACING", 4922 "Unnecessary space before function pointer name\n" . $herecurr); 4923 } 4924 4925# unnecessary space "type (*funcptr )(args...)" 4926 if (defined $post_funcname_space && 4927 $post_funcname_space =~ /^\s/) { 4928 WARN("SPACING", 4929 "Unnecessary space after function pointer name\n" . $herecurr); 4930 } 4931 4932# unnecessary space "type (*funcptr) (args...)" 4933 if (defined $pre_args_space && 4934 $pre_args_space =~ /^\s/) { 4935 WARN("SPACING", 4936 "Unnecessary space before function pointer arguments\n" . $herecurr); 4937 } 4938 4939 if (show_type("SPACING") && $fix) { 4940 $fixed[$fixlinenr] =~ 4941 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex; 4942 } 4943 } 4944 4945# check for spacing round square brackets; allowed: 4946# 1. with a type on the left -- int [] a; 4947# 2. at the beginning of a line for slice initialisers -- [0...10] = 5, 4948# 3. inside a curly brace -- = { [0...10] = 5 } 4949 while ($line =~ /(.*?\s)\[/g) { 4950 my ($where, $prefix) = ($-[1], $1); 4951 if ($prefix !~ /$Type\s+$/ && 4952 ($where != 0 || $prefix !~ /^.\s+$/) && 4953 $prefix !~ /[{,:]\s+$/) { 4954 if (ERROR("BRACKET_SPACE", 4955 "space prohibited before open square bracket '['\n" . $herecurr) && 4956 $fix) { 4957 $fixed[$fixlinenr] =~ 4958 s/^(\+.*?)\s+\[/$1\[/; 4959 } 4960 } 4961 } 4962 4963# check for spaces between functions and their parentheses. 4964 while ($line =~ /($Ident)\s+\(/g) { 4965 my $name = $1; 4966 my $ctx_before = substr($line, 0, $-[1]); 4967 my $ctx = "$ctx_before$name"; 4968 4969 # Ignore those directives where spaces _are_ permitted. 4970 if ($name =~ /^(?: 4971 if|for|while|switch|return|case| 4972 volatile|__volatile__| 4973 __attribute__|format|__extension__| 4974 asm|__asm__)$/x) 4975 { 4976 # cpp #define statements have non-optional spaces, ie 4977 # if there is a space between the name and the open 4978 # parenthesis it is simply not a parameter group. 4979 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) { 4980 4981 # cpp #elif statement condition may start with a ( 4982 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) { 4983 4984 # If this whole things ends with a type its most 4985 # likely a typedef for a function. 4986 } elsif ($ctx =~ /$Type$/) { 4987 4988 } else { 4989 if (WARN("SPACING", 4990 "space prohibited between function name and open parenthesis '('\n" . $herecurr) && 4991 $fix) { 4992 $fixed[$fixlinenr] =~ 4993 s/\b$name\s+\(/$name\(/; 4994 } 4995 } 4996 } 4997 4998# Check operator spacing. 4999 if (!($line=~/\#\s*include/)) { 5000 my $fixed_line = ""; 5001 my $line_fixed = 0; 5002 5003 my $ops = qr{ 5004 <<=|>>=|<=|>=|==|!=| 5005 \+=|-=|\*=|\/=|%=|\^=|\|=|&=| 5006 =>|->|<<|>>|<|>|=|!|~| 5007 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%| 5008 \?:|\?|: 5009 }x; 5010 my @elements = split(/($ops|;)/, $opline); 5011 5012## print("element count: <" . $#elements . ">\n"); 5013## foreach my $el (@elements) { 5014## print("el: <$el>\n"); 5015## } 5016 5017 my @fix_elements = (); 5018 my $off = 0; 5019 5020 foreach my $el (@elements) { 5021 push(@fix_elements, substr($rawline, $off, length($el))); 5022 $off += length($el); 5023 } 5024 5025 $off = 0; 5026 5027 my $blank = copy_spacing($opline); 5028 my $last_after = -1; 5029 5030 for (my $n = 0; $n < $#elements; $n += 2) { 5031 5032 my $good = $fix_elements[$n] . $fix_elements[$n + 1]; 5033 5034## print("n: <$n> good: <$good>\n"); 5035 5036 $off += length($elements[$n]); 5037 5038 # Pick up the preceding and succeeding characters. 5039 my $ca = substr($opline, 0, $off); 5040 my $cc = ''; 5041 if (length($opline) >= ($off + length($elements[$n + 1]))) { 5042 $cc = substr($opline, $off + length($elements[$n + 1])); 5043 } 5044 my $cb = "$ca$;$cc"; 5045 5046 my $a = ''; 5047 $a = 'V' if ($elements[$n] ne ''); 5048 $a = 'W' if ($elements[$n] =~ /\s$/); 5049 $a = 'C' if ($elements[$n] =~ /$;$/); 5050 $a = 'B' if ($elements[$n] =~ /(\[|\()$/); 5051 $a = 'O' if ($elements[$n] eq ''); 5052 $a = 'E' if ($ca =~ /^\s*$/); 5053 5054 my $op = $elements[$n + 1]; 5055 5056 my $c = ''; 5057 if (defined $elements[$n + 2]) { 5058 $c = 'V' if ($elements[$n + 2] ne ''); 5059 $c = 'W' if ($elements[$n + 2] =~ /^\s/); 5060 $c = 'C' if ($elements[$n + 2] =~ /^$;/); 5061 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/); 5062 $c = 'O' if ($elements[$n + 2] eq ''); 5063 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/); 5064 } else { 5065 $c = 'E'; 5066 } 5067 5068 my $ctx = "${a}x${c}"; 5069 5070 my $at = "(ctx:$ctx)"; 5071 5072 my $ptr = substr($blank, 0, $off) . "^"; 5073 my $hereptr = "$hereline$ptr\n"; 5074 5075 # Pull out the value of this operator. 5076 my $op_type = substr($curr_values, $off + 1, 1); 5077 5078 # Get the full operator variant. 5079 my $opv = $op . substr($curr_vars, $off, 1); 5080 5081 # Ignore operators passed as parameters. 5082 if ($op_type ne 'V' && 5083 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) { 5084 5085# # Ignore comments 5086# } elsif ($op =~ /^$;+$/) { 5087 5088 # ; should have either the end of line or a space or \ after it 5089 } elsif ($op eq ';') { 5090 if ($ctx !~ /.x[WEBC]/ && 5091 $cc !~ /^\\/ && $cc !~ /^;/) { 5092 if (ERROR("SPACING", 5093 "space required after that '$op' $at\n" . $hereptr)) { 5094 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " "; 5095 $line_fixed = 1; 5096 } 5097 } 5098 5099 # // is a comment 5100 } elsif ($op eq '//') { 5101 5102 # : when part of a bitfield 5103 } elsif ($opv eq ':B') { 5104 # skip the bitfield test for now 5105 5106 # No spaces for: 5107 # -> 5108 } elsif ($op eq '->') { 5109 if ($ctx =~ /Wx.|.xW/) { 5110 if (ERROR("SPACING", 5111 "spaces prohibited around that '$op' $at\n" . $hereptr)) { 5112 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); 5113 if (defined $fix_elements[$n + 2]) { 5114 $fix_elements[$n + 2] =~ s/^\s+//; 5115 } 5116 $line_fixed = 1; 5117 } 5118 } 5119 5120 # , must not have a space before and must have a space on the right. 5121 } elsif ($op eq ',') { 5122 my $rtrim_before = 0; 5123 my $space_after = 0; 5124 if ($ctx =~ /Wx./) { 5125 if (ERROR("SPACING", 5126 "space prohibited before that '$op' $at\n" . $hereptr)) { 5127 $line_fixed = 1; 5128 $rtrim_before = 1; 5129 } 5130 } 5131 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) { 5132 if (ERROR("SPACING", 5133 "space required after that '$op' $at\n" . $hereptr)) { 5134 $line_fixed = 1; 5135 $last_after = $n; 5136 $space_after = 1; 5137 } 5138 } 5139 if ($rtrim_before || $space_after) { 5140 if ($rtrim_before) { 5141 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); 5142 } else { 5143 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]); 5144 } 5145 if ($space_after) { 5146 $good .= " "; 5147 } 5148 } 5149 5150 # '*' as part of a type definition -- reported already. 5151 } elsif ($opv eq '*_') { 5152 #warn "'*' is part of type\n"; 5153 5154 # unary operators should have a space before and 5155 # none after. May be left adjacent to another 5156 # unary operator, or a cast 5157 } elsif ($op eq '!' || $op eq '~' || 5158 $opv eq '*U' || $opv eq '-U' || 5159 $opv eq '&U' || $opv eq '&&U') { 5160 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) { 5161 if (ERROR("SPACING", 5162 "space required before that '$op' $at\n" . $hereptr)) { 5163 if ($n != $last_after + 2) { 5164 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]); 5165 $line_fixed = 1; 5166 } 5167 } 5168 } 5169 if ($op eq '*' && $cc =~/\s*$Modifier\b/) { 5170 # A unary '*' may be const 5171 5172 } elsif ($ctx =~ /.xW/) { 5173 if (ERROR("SPACING", 5174 "space prohibited after that '$op' $at\n" . $hereptr)) { 5175 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]); 5176 if (defined $fix_elements[$n + 2]) { 5177 $fix_elements[$n + 2] =~ s/^\s+//; 5178 } 5179 $line_fixed = 1; 5180 } 5181 } 5182 5183 # unary ++ and unary -- are allowed no space on one side. 5184 } elsif ($op eq '++' or $op eq '--') { 5185 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) { 5186 if (ERROR("SPACING", 5187 "space required one side of that '$op' $at\n" . $hereptr)) { 5188 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " "; 5189 $line_fixed = 1; 5190 } 5191 } 5192 if ($ctx =~ /Wx[BE]/ || 5193 ($ctx =~ /Wx./ && $cc =~ /^;/)) { 5194 if (ERROR("SPACING", 5195 "space prohibited before that '$op' $at\n" . $hereptr)) { 5196 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); 5197 $line_fixed = 1; 5198 } 5199 } 5200 if ($ctx =~ /ExW/) { 5201 if (ERROR("SPACING", 5202 "space prohibited after that '$op' $at\n" . $hereptr)) { 5203 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]); 5204 if (defined $fix_elements[$n + 2]) { 5205 $fix_elements[$n + 2] =~ s/^\s+//; 5206 } 5207 $line_fixed = 1; 5208 } 5209 } 5210 5211 # << and >> may either have or not have spaces both sides 5212 } elsif ($op eq '<<' or $op eq '>>' or 5213 $op eq '&' or $op eq '^' or $op eq '|' or 5214 $op eq '+' or $op eq '-' or 5215 $op eq '*' or $op eq '/' or 5216 $op eq '%') 5217 { 5218 if ($check) { 5219 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) { 5220 if (CHK("SPACING", 5221 "spaces preferred around that '$op' $at\n" . $hereptr)) { 5222 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " "; 5223 $fix_elements[$n + 2] =~ s/^\s+//; 5224 $line_fixed = 1; 5225 } 5226 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) { 5227 if (CHK("SPACING", 5228 "space preferred before that '$op' $at\n" . $hereptr)) { 5229 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]); 5230 $line_fixed = 1; 5231 } 5232 } 5233 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) { 5234 if (ERROR("SPACING", 5235 "need consistent spacing around '$op' $at\n" . $hereptr)) { 5236 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " "; 5237 if (defined $fix_elements[$n + 2]) { 5238 $fix_elements[$n + 2] =~ s/^\s+//; 5239 } 5240 $line_fixed = 1; 5241 } 5242 } 5243 5244 # A colon needs no spaces before when it is 5245 # terminating a case value or a label. 5246 } elsif ($opv eq ':C' || $opv eq ':L') { 5247 if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) { 5248 if (ERROR("SPACING", 5249 "space prohibited before that '$op' $at\n" . $hereptr)) { 5250 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); 5251 $line_fixed = 1; 5252 } 5253 } 5254 5255 # All the others need spaces both sides. 5256 } elsif ($ctx !~ /[EWC]x[CWE]/) { 5257 my $ok = 0; 5258 5259 # Ignore email addresses <foo@bar> 5260 if (($op eq '<' && 5261 $cc =~ /^\S+\@\S+>/) || 5262 ($op eq '>' && 5263 $ca =~ /<\S+\@\S+$/)) 5264 { 5265 $ok = 1; 5266 } 5267 5268 # for asm volatile statements 5269 # ignore a colon with another 5270 # colon immediately before or after 5271 if (($op eq ':') && 5272 ($ca =~ /:$/ || $cc =~ /^:/)) { 5273 $ok = 1; 5274 } 5275 5276 # messages are ERROR, but ?: are CHK 5277 if ($ok == 0) { 5278 my $msg_level = \&ERROR; 5279 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/); 5280 5281 if (&{$msg_level}("SPACING", 5282 "spaces required around that '$op' $at\n" . $hereptr)) { 5283 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " "; 5284 if (defined $fix_elements[$n + 2]) { 5285 $fix_elements[$n + 2] =~ s/^\s+//; 5286 } 5287 $line_fixed = 1; 5288 } 5289 } 5290 } 5291 $off += length($elements[$n + 1]); 5292 5293## print("n: <$n> GOOD: <$good>\n"); 5294 5295 $fixed_line = $fixed_line . $good; 5296 } 5297 5298 if (($#elements % 2) == 0) { 5299 $fixed_line = $fixed_line . $fix_elements[$#elements]; 5300 } 5301 5302 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) { 5303 $fixed[$fixlinenr] = $fixed_line; 5304 } 5305 5306 5307 } 5308 5309# check for whitespace before a non-naked semicolon 5310 if ($line =~ /^\+.*\S\s+;\s*$/) { 5311 if (WARN("SPACING", 5312 "space prohibited before semicolon\n" . $herecurr) && 5313 $fix) { 5314 1 while $fixed[$fixlinenr] =~ 5315 s/^(\+.*\S)\s+;/$1;/; 5316 } 5317 } 5318 5319# check for multiple assignments 5320 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) { 5321 CHK("MULTIPLE_ASSIGNMENTS", 5322 "multiple assignments should be avoided\n" . $herecurr); 5323 } 5324 5325## # check for multiple declarations, allowing for a function declaration 5326## # continuation. 5327## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ && 5328## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) { 5329## 5330## # Remove any bracketed sections to ensure we do not 5331## # falsely report the parameters of functions. 5332## my $ln = $line; 5333## while ($ln =~ s/\([^\(\)]*\)//g) { 5334## } 5335## if ($ln =~ /,/) { 5336## WARN("MULTIPLE_DECLARATION", 5337## "declaring multiple variables together should be avoided\n" . $herecurr); 5338## } 5339## } 5340 5341#need space before brace following if, while, etc 5342 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) || 5343 $line =~ /\b(?:else|do)\{/) { 5344 if (ERROR("SPACING", 5345 "space required before the open brace '{'\n" . $herecurr) && 5346 $fix) { 5347 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/; 5348 } 5349 } 5350 5351## # check for blank lines before declarations 5352## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ && 5353## $prevrawline =~ /^.\s*$/) { 5354## WARN("SPACING", 5355## "No blank lines before declarations\n" . $hereprev); 5356## } 5357## 5358 5359# closing brace should have a space following it when it has anything 5360# on the line 5361 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) { 5362 if (ERROR("SPACING", 5363 "space required after that close brace '}'\n" . $herecurr) && 5364 $fix) { 5365 $fixed[$fixlinenr] =~ 5366 s/}((?!(?:,|;|\)))\S)/} $1/; 5367 } 5368 } 5369 5370# check spacing on square brackets 5371 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) { 5372 if (ERROR("SPACING", 5373 "space prohibited after that open square bracket '['\n" . $herecurr) && 5374 $fix) { 5375 $fixed[$fixlinenr] =~ 5376 s/\[\s+/\[/; 5377 } 5378 } 5379 if ($line =~ /\s\]/) { 5380 if (ERROR("SPACING", 5381 "space prohibited before that close square bracket ']'\n" . $herecurr) && 5382 $fix) { 5383 $fixed[$fixlinenr] =~ 5384 s/\s+\]/\]/; 5385 } 5386 } 5387 5388# check spacing on parentheses 5389 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ && 5390 $line !~ /for\s*\(\s+;/) { 5391 if (ERROR("SPACING", 5392 "space prohibited after that open parenthesis '('\n" . $herecurr) && 5393 $fix) { 5394 $fixed[$fixlinenr] =~ 5395 s/\(\s+/\(/; 5396 } 5397 } 5398 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ && 5399 $line !~ /for\s*\(.*;\s+\)/ && 5400 $line !~ /:\s+\)/) { 5401 if (ERROR("SPACING", 5402 "space prohibited before that close parenthesis ')'\n" . $herecurr) && 5403 $fix) { 5404 $fixed[$fixlinenr] =~ 5405 s/\s+\)/\)/; 5406 } 5407 } 5408 5409# check unnecessary parentheses around addressof/dereference single $Lvals 5410# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar 5411 5412 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) { 5413 my $var = $1; 5414 if (CHK("UNNECESSARY_PARENTHESES", 5415 "Unnecessary parentheses around $var\n" . $herecurr) && 5416 $fix) { 5417 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/; 5418 } 5419 } 5420 5421# check for unnecessary parentheses around function pointer uses 5422# ie: (foo->bar)(); should be foo->bar(); 5423# but not "if (foo->bar) (" to avoid some false positives 5424 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) { 5425 my $var = $2; 5426 if (CHK("UNNECESSARY_PARENTHESES", 5427 "Unnecessary parentheses around function pointer $var\n" . $herecurr) && 5428 $fix) { 5429 my $var2 = deparenthesize($var); 5430 $var2 =~ s/\s//g; 5431 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/; 5432 } 5433 } 5434 5435# check for unnecessary parentheses around comparisons in if uses 5436# when !drivers/staging or command-line uses --strict 5437 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) && 5438 $perl_version_ok && defined($stat) && 5439 $stat =~ /(^.\s*if\s*($balanced_parens))/) { 5440 my $if_stat = $1; 5441 my $test = substr($2, 1, -1); 5442 my $herectx; 5443 while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) { 5444 my $match = $1; 5445 # avoid parentheses around potential macro args 5446 next if ($match =~ /^\s*\w+\s*$/); 5447 if (!defined($herectx)) { 5448 $herectx = $here . "\n"; 5449 my $cnt = statement_rawlines($if_stat); 5450 for (my $n = 0; $n < $cnt; $n++) { 5451 my $rl = raw_line($linenr, $n); 5452 $herectx .= $rl . "\n"; 5453 last if $rl =~ /^[ \+].*\{/; 5454 } 5455 } 5456 CHK("UNNECESSARY_PARENTHESES", 5457 "Unnecessary parentheses around '$match'\n" . $herectx); 5458 } 5459 } 5460 5461# check that goto labels aren't indented (allow a single space indentation) 5462# and ignore bitfield definitions like foo:1 5463# Strictly, labels can have whitespace after the identifier and before the : 5464# but this is not allowed here as many ?: uses would appear to be labels 5465 if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ && 5466 $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ && 5467 $sline !~ /^.\s+default:/) { 5468 if (WARN("INDENTED_LABEL", 5469 "labels should not be indented\n" . $herecurr) && 5470 $fix) { 5471 $fixed[$fixlinenr] =~ 5472 s/^(.)\s+/$1/; 5473 } 5474 } 5475 5476# check if a statement with a comma should be two statements like: 5477# foo = bar(), /* comma should be semicolon */ 5478# bar = baz(); 5479 if (defined($stat) && 5480 $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) { 5481 my $cnt = statement_rawlines($stat); 5482 my $herectx = get_stat_here($linenr, $cnt, $here); 5483 WARN("SUSPECT_COMMA_SEMICOLON", 5484 "Possible comma where semicolon could be used\n" . $herectx); 5485 } 5486 5487# return is not a function 5488 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) { 5489 my $spacing = $1; 5490 if ($perl_version_ok && 5491 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) { 5492 my $value = $1; 5493 $value = deparenthesize($value); 5494 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) { 5495 ERROR("RETURN_PARENTHESES", 5496 "return is not a function, parentheses are not required\n" . $herecurr); 5497 } 5498 } elsif ($spacing !~ /\s+/) { 5499 ERROR("SPACING", 5500 "space required before the open parenthesis '('\n" . $herecurr); 5501 } 5502 } 5503 5504# unnecessary return in a void function 5505# at end-of-function, with the previous line a single leading tab, then return; 5506# and the line before that not a goto label target like "out:" 5507 if ($sline =~ /^[ \+]}\s*$/ && 5508 $prevline =~ /^\+\treturn\s*;\s*$/ && 5509 $linenr >= 3 && 5510 $lines[$linenr - 3] =~ /^[ +]/ && 5511 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) { 5512 WARN("RETURN_VOID", 5513 "void function return statements are not generally useful\n" . $hereprev); 5514 } 5515 5516# if statements using unnecessary parentheses - ie: if ((foo == bar)) 5517 if ($perl_version_ok && 5518 $line =~ /\bif\s*((?:\(\s*){2,})/) { 5519 my $openparens = $1; 5520 my $count = $openparens =~ tr@\(@\(@; 5521 my $msg = ""; 5522 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) { 5523 my $comp = $4; #Not $1 because of $LvalOrFunc 5524 $msg = " - maybe == should be = ?" if ($comp eq "=="); 5525 WARN("UNNECESSARY_PARENTHESES", 5526 "Unnecessary parentheses$msg\n" . $herecurr); 5527 } 5528 } 5529 5530# comparisons with a constant or upper case identifier on the left 5531# avoid cases like "foo + BAR < baz" 5532# only fix matches surrounded by parentheses to avoid incorrect 5533# conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5" 5534 if ($perl_version_ok && 5535 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) { 5536 my $lead = $1; 5537 my $const = $2; 5538 my $comp = $3; 5539 my $to = $4; 5540 my $newcomp = $comp; 5541 if ($lead !~ /(?:$Operators|\.)\s*$/ && 5542 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ && 5543 WARN("CONSTANT_COMPARISON", 5544 "Comparisons should place the constant on the right side of the test\n" . $herecurr) && 5545 $fix) { 5546 if ($comp eq "<") { 5547 $newcomp = ">"; 5548 } elsif ($comp eq "<=") { 5549 $newcomp = ">="; 5550 } elsif ($comp eq ">") { 5551 $newcomp = "<"; 5552 } elsif ($comp eq ">=") { 5553 $newcomp = "<="; 5554 } 5555 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/; 5556 } 5557 } 5558 5559# Return of what appears to be an errno should normally be negative 5560 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) { 5561 my $name = $1; 5562 if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) { 5563 WARN("USE_NEGATIVE_ERRNO", 5564 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr); 5565 } 5566 } 5567 5568# Need a space before open parenthesis after if, while etc 5569 if ($line =~ /\b(if|while|for|switch)\(/) { 5570 if (ERROR("SPACING", 5571 "space required before the open parenthesis '('\n" . $herecurr) && 5572 $fix) { 5573 $fixed[$fixlinenr] =~ 5574 s/\b(if|while|for|switch)\(/$1 \(/; 5575 } 5576 } 5577 5578# Check for illegal assignment in if conditional -- and check for trailing 5579# statements after the conditional. 5580 if ($line =~ /do\s*(?!{)/) { 5581 ($stat, $cond, $line_nr_next, $remain_next, $off_next) = 5582 ctx_statement_block($linenr, $realcnt, 0) 5583 if (!defined $stat); 5584 my ($stat_next) = ctx_statement_block($line_nr_next, 5585 $remain_next, $off_next); 5586 $stat_next =~ s/\n./\n /g; 5587 ##print "stat<$stat> stat_next<$stat_next>\n"; 5588 5589 if ($stat_next =~ /^\s*while\b/) { 5590 # If the statement carries leading newlines, 5591 # then count those as offsets. 5592 my ($whitespace) = 5593 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s); 5594 my $offset = 5595 statement_rawlines($whitespace) - 1; 5596 5597 $suppress_whiletrailers{$line_nr_next + 5598 $offset} = 1; 5599 } 5600 } 5601 if (!defined $suppress_whiletrailers{$linenr} && 5602 defined($stat) && defined($cond) && 5603 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) { 5604 my ($s, $c) = ($stat, $cond); 5605 my $fixed_assign_in_if = 0; 5606 5607 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) { 5608 if (ERROR("ASSIGN_IN_IF", 5609 "do not use assignment in if condition\n" . $herecurr) && 5610 $fix && $perl_version_ok) { 5611 if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) { 5612 my $space = $1; 5613 my $not = $2; 5614 my $statement = $3; 5615 my $assigned = $4; 5616 my $test = $8; 5617 my $against = $9; 5618 my $brace = $15; 5619 fix_delete_line($fixlinenr, $rawline); 5620 fix_insert_line($fixlinenr, "$space$statement;"); 5621 my $newline = "${space}if ("; 5622 $newline .= '!' if defined($not); 5623 $newline .= '(' if (defined $not && defined($test) && defined($against)); 5624 $newline .= "$assigned"; 5625 $newline .= " $test $against" if (defined($test) && defined($against)); 5626 $newline .= ')' if (defined $not && defined($test) && defined($against)); 5627 $newline .= ')'; 5628 $newline .= " {" if (defined($brace)); 5629 fix_insert_line($fixlinenr + 1, $newline); 5630 $fixed_assign_in_if = 1; 5631 } 5632 } 5633 } 5634 5635 # Find out what is on the end of the line after the 5636 # conditional. 5637 substr($s, 0, length($c), ''); 5638 $s =~ s/\n.*//g; 5639 $s =~ s/$;//g; # Remove any comments 5640 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ && 5641 $c !~ /}\s*while\s*/) 5642 { 5643 # Find out how long the conditional actually is. 5644 my @newlines = ($c =~ /\n/gs); 5645 my $cond_lines = 1 + $#newlines; 5646 my $stat_real = ''; 5647 5648 $stat_real = raw_line($linenr, $cond_lines) 5649 . "\n" if ($cond_lines); 5650 if (defined($stat_real) && $cond_lines > 1) { 5651 $stat_real = "[...]\n$stat_real"; 5652 } 5653 5654 if (ERROR("TRAILING_STATEMENTS", 5655 "trailing statements should be on next line\n" . $herecurr . $stat_real) && 5656 !$fixed_assign_in_if && 5657 $cond_lines == 0 && 5658 $fix && $perl_version_ok && 5659 $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) { 5660 my $indent = $1; 5661 my $test = $2; 5662 my $rest = rtrim($4); 5663 if ($rest =~ /;$/) { 5664 $fixed[$fixlinenr] = "\+$indent$test"; 5665 fix_insert_line($fixlinenr + 1, "$indent\t$rest"); 5666 } 5667 } 5668 } 5669 } 5670 5671# Check for bitwise tests written as boolean 5672 if ($line =~ / 5673 (?: 5674 (?:\[|\(|\&\&|\|\|) 5675 \s*0[xX][0-9]+\s* 5676 (?:\&\&|\|\|) 5677 | 5678 (?:\&\&|\|\|) 5679 \s*0[xX][0-9]+\s* 5680 (?:\&\&|\|\||\)|\]) 5681 )/x) 5682 { 5683 WARN("HEXADECIMAL_BOOLEAN_TEST", 5684 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr); 5685 } 5686 5687# if and else should not have general statements after it 5688 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) { 5689 my $s = $1; 5690 $s =~ s/$;//g; # Remove any comments 5691 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) { 5692 ERROR("TRAILING_STATEMENTS", 5693 "trailing statements should be on next line\n" . $herecurr); 5694 } 5695 } 5696# if should not continue a brace 5697 if ($line =~ /}\s*if\b/) { 5698 ERROR("TRAILING_STATEMENTS", 5699 "trailing statements should be on next line (or did you mean 'else if'?)\n" . 5700 $herecurr); 5701 } 5702# case and default should not have general statements after them 5703 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g && 5704 $line !~ /\G(?: 5705 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$| 5706 \s*return\s+ 5707 )/xg) 5708 { 5709 ERROR("TRAILING_STATEMENTS", 5710 "trailing statements should be on next line\n" . $herecurr); 5711 } 5712 5713 # Check for }<nl>else {, these must be at the same 5714 # indent level to be relevant to each other. 5715 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ && 5716 $previndent == $indent) { 5717 if (ERROR("ELSE_AFTER_BRACE", 5718 "else should follow close brace '}'\n" . $hereprev) && 5719 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) { 5720 fix_delete_line($fixlinenr - 1, $prevrawline); 5721 fix_delete_line($fixlinenr, $rawline); 5722 my $fixedline = $prevrawline; 5723 $fixedline =~ s/}\s*$//; 5724 if ($fixedline !~ /^\+\s*$/) { 5725 fix_insert_line($fixlinenr, $fixedline); 5726 } 5727 $fixedline = $rawline; 5728 $fixedline =~ s/^(.\s*)else/$1} else/; 5729 fix_insert_line($fixlinenr, $fixedline); 5730 } 5731 } 5732 5733 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ && 5734 $previndent == $indent) { 5735 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0); 5736 5737 # Find out what is on the end of the line after the 5738 # conditional. 5739 substr($s, 0, length($c), ''); 5740 $s =~ s/\n.*//g; 5741 5742 if ($s =~ /^\s*;/) { 5743 if (ERROR("WHILE_AFTER_BRACE", 5744 "while should follow close brace '}'\n" . $hereprev) && 5745 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) { 5746 fix_delete_line($fixlinenr - 1, $prevrawline); 5747 fix_delete_line($fixlinenr, $rawline); 5748 my $fixedline = $prevrawline; 5749 my $trailing = $rawline; 5750 $trailing =~ s/^\+//; 5751 $trailing = trim($trailing); 5752 $fixedline =~ s/}\s*$/} $trailing/; 5753 fix_insert_line($fixlinenr, $fixedline); 5754 } 5755 } 5756 } 5757 5758#Specific variable tests 5759 while ($line =~ m{($Constant|$Lval)}g) { 5760 my $var = $1; 5761 5762#CamelCase 5763 if ($var !~ /^$Constant$/ && 5764 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ && 5765#Ignore some autogenerated defines and enum values 5766 $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ && 5767#Ignore Page<foo> variants 5768 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ && 5769#Ignore SI style variants like nS, mV and dB 5770#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE) 5771 $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ && 5772#Ignore some three character SI units explicitly, like MiB and KHz 5773 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) { 5774 while ($var =~ m{\b($Ident)}g) { 5775 my $word = $1; 5776 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/); 5777 if ($check) { 5778 seed_camelcase_includes(); 5779 if (!$file && !$camelcase_file_seeded) { 5780 seed_camelcase_file($realfile); 5781 $camelcase_file_seeded = 1; 5782 } 5783 } 5784 if (!defined $camelcase{$word}) { 5785 $camelcase{$word} = 1; 5786 CHK("CAMELCASE", 5787 "Avoid CamelCase: <$word>\n" . $herecurr); 5788 } 5789 } 5790 } 5791 } 5792 5793#no spaces allowed after \ in define 5794 if ($line =~ /\#\s*define.*\\\s+$/) { 5795 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION", 5796 "Whitespace after \\ makes next lines useless\n" . $herecurr) && 5797 $fix) { 5798 $fixed[$fixlinenr] =~ s/\s+$//; 5799 } 5800 } 5801 5802# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes 5803# itself <asm/foo.h> (uses RAW line) 5804 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) { 5805 my $file = "$1.h"; 5806 my $checkfile = "include/linux/$file"; 5807 if (-f "$root/$checkfile" && 5808 $realfile ne $checkfile && 5809 $1 !~ /$allowed_asm_includes/) 5810 { 5811 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`; 5812 if ($asminclude > 0) { 5813 if ($realfile =~ m{^arch/}) { 5814 CHK("ARCH_INCLUDE_LINUX", 5815 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr); 5816 } else { 5817 WARN("INCLUDE_LINUX", 5818 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr); 5819 } 5820 } 5821 } 5822 } 5823 5824# multi-statement macros should be enclosed in a do while loop, grab the 5825# first statement and ensure its the whole macro if its not enclosed 5826# in a known good container 5827 if ($realfile !~ m@/vmlinux.lds.h$@ && 5828 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) { 5829 my $ln = $linenr; 5830 my $cnt = $realcnt; 5831 my ($off, $dstat, $dcond, $rest); 5832 my $ctx = ''; 5833 my $has_flow_statement = 0; 5834 my $has_arg_concat = 0; 5835 ($dstat, $dcond, $ln, $cnt, $off) = 5836 ctx_statement_block($linenr, $realcnt, 0); 5837 $ctx = $dstat; 5838 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n"; 5839 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n"; 5840 5841 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/); 5842 $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/); 5843 5844 $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//; 5845 my $define_args = $1; 5846 my $define_stmt = $dstat; 5847 my @def_args = (); 5848 5849 if (defined $define_args && $define_args ne "") { 5850 $define_args = substr($define_args, 1, length($define_args) - 2); 5851 $define_args =~ s/\s*//g; 5852 $define_args =~ s/\\\+?//g; 5853 @def_args = split(",", $define_args); 5854 } 5855 5856 $dstat =~ s/$;//g; 5857 $dstat =~ s/\\\n.//g; 5858 $dstat =~ s/^\s*//s; 5859 $dstat =~ s/\s*$//s; 5860 5861 # Flatten any parentheses and braces 5862 while ($dstat =~ s/\([^\(\)]*\)/1u/ || 5863 $dstat =~ s/\{[^\{\}]*\}/1u/ || 5864 $dstat =~ s/.\[[^\[\]]*\]/1u/) 5865 { 5866 } 5867 5868 # Flatten any obvious string concatenation. 5869 while ($dstat =~ s/($String)\s*$Ident/$1/ || 5870 $dstat =~ s/$Ident\s*($String)/$1/) 5871 { 5872 } 5873 5874 # Make asm volatile uses seem like a generic function 5875 $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g; 5876 5877 my $exceptions = qr{ 5878 $Declare| 5879 module_param_named| 5880 MODULE_PARM_DESC| 5881 DECLARE_PER_CPU| 5882 DEFINE_PER_CPU| 5883 __typeof__\(| 5884 union| 5885 struct| 5886 \.$Ident\s*=\s*| 5887 ^\"|\"$| 5888 ^\[ 5889 }x; 5890 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n"; 5891 5892 $ctx =~ s/\n*$//; 5893 my $stmt_cnt = statement_rawlines($ctx); 5894 my $herectx = get_stat_here($linenr, $stmt_cnt, $here); 5895 5896 if ($dstat ne '' && 5897 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(), 5898 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo(); 5899 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz 5900 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants 5901 $dstat !~ /$exceptions/ && 5902 $dstat !~ /^\.$Ident\s*=/ && # .foo = 5903 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo 5904 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...) 5905 $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ && # while (...) {...} 5906 $dstat !~ /^for\s*$Constant$/ && # for (...) 5907 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar() 5908 $dstat !~ /^do\s*{/ && # do {... 5909 $dstat !~ /^\(\{/ && # ({... 5910 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/) 5911 { 5912 if ($dstat =~ /^\s*if\b/) { 5913 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE", 5914 "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx"); 5915 } elsif ($dstat =~ /;/) { 5916 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE", 5917 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx"); 5918 } else { 5919 ERROR("COMPLEX_MACRO", 5920 "Macros with complex values should be enclosed in parentheses\n" . "$herectx"); 5921 } 5922 5923 } 5924 5925 # Make $define_stmt single line, comment-free, etc 5926 my @stmt_array = split('\n', $define_stmt); 5927 my $first = 1; 5928 $define_stmt = ""; 5929 foreach my $l (@stmt_array) { 5930 $l =~ s/\\$//; 5931 if ($first) { 5932 $define_stmt = $l; 5933 $first = 0; 5934 } elsif ($l =~ /^[\+ ]/) { 5935 $define_stmt .= substr($l, 1); 5936 } 5937 } 5938 $define_stmt =~ s/$;//g; 5939 $define_stmt =~ s/\s+/ /g; 5940 $define_stmt = trim($define_stmt); 5941 5942# check if any macro arguments are reused (ignore '...' and 'type') 5943 foreach my $arg (@def_args) { 5944 next if ($arg =~ /\.\.\./); 5945 next if ($arg =~ /^type$/i); 5946 my $tmp_stmt = $define_stmt; 5947 $tmp_stmt =~ s/\b(__must_be_array|offsetof|sizeof|sizeof_field|__stringify|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g; 5948 $tmp_stmt =~ s/\#+\s*$arg\b//g; 5949 $tmp_stmt =~ s/\b$arg\s*\#\#//g; 5950 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g; 5951 if ($use_cnt > 1) { 5952 CHK("MACRO_ARG_REUSE", 5953 "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx"); 5954 } 5955# check if any macro arguments may have other precedence issues 5956 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m && 5957 ((defined($1) && $1 ne ',') || 5958 (defined($2) && $2 ne ','))) { 5959 CHK("MACRO_ARG_PRECEDENCE", 5960 "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx"); 5961 } 5962 } 5963 5964# check for macros with flow control, but without ## concatenation 5965# ## concatenation is commonly a macro that defines a function so ignore those 5966 if ($has_flow_statement && !$has_arg_concat) { 5967 my $cnt = statement_rawlines($ctx); 5968 my $herectx = get_stat_here($linenr, $cnt, $here); 5969 5970 WARN("MACRO_WITH_FLOW_CONTROL", 5971 "Macros with flow control statements should be avoided\n" . "$herectx"); 5972 } 5973 5974# check for line continuations outside of #defines, preprocessor #, and asm 5975 5976 } else { 5977 if ($prevline !~ /^..*\\$/ && 5978 $line !~ /^\+\s*\#.*\\$/ && # preprocessor 5979 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm 5980 $line =~ /^\+.*\\$/) { 5981 WARN("LINE_CONTINUATIONS", 5982 "Avoid unnecessary line continuations\n" . $herecurr); 5983 } 5984 } 5985 5986# do {} while (0) macro tests: 5987# single-statement macros do not need to be enclosed in do while (0) loop, 5988# macro should not end with a semicolon 5989 if ($perl_version_ok && 5990 $realfile !~ m@/vmlinux.lds.h$@ && 5991 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) { 5992 my $ln = $linenr; 5993 my $cnt = $realcnt; 5994 my ($off, $dstat, $dcond, $rest); 5995 my $ctx = ''; 5996 ($dstat, $dcond, $ln, $cnt, $off) = 5997 ctx_statement_block($linenr, $realcnt, 0); 5998 $ctx = $dstat; 5999 6000 $dstat =~ s/\\\n.//g; 6001 $dstat =~ s/$;/ /g; 6002 6003 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) { 6004 my $stmts = $2; 6005 my $semis = $3; 6006 6007 $ctx =~ s/\n*$//; 6008 my $cnt = statement_rawlines($ctx); 6009 my $herectx = get_stat_here($linenr, $cnt, $here); 6010 6011 if (($stmts =~ tr/;/;/) == 1 && 6012 $stmts !~ /^\s*(if|while|for|switch)\b/) { 6013 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO", 6014 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx"); 6015 } 6016 if (defined $semis && $semis ne "") { 6017 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON", 6018 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx"); 6019 } 6020 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) { 6021 $ctx =~ s/\n*$//; 6022 my $cnt = statement_rawlines($ctx); 6023 my $herectx = get_stat_here($linenr, $cnt, $here); 6024 6025 WARN("TRAILING_SEMICOLON", 6026 "macros should not use a trailing semicolon\n" . "$herectx"); 6027 } 6028 } 6029 6030# check for redundant bracing round if etc 6031 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) { 6032 my ($level, $endln, @chunks) = 6033 ctx_statement_full($linenr, $realcnt, 1); 6034 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n"; 6035 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"; 6036 if ($#chunks > 0 && $level == 0) { 6037 my @allowed = (); 6038 my $allow = 0; 6039 my $seen = 0; 6040 my $herectx = $here . "\n"; 6041 my $ln = $linenr - 1; 6042 for my $chunk (@chunks) { 6043 my ($cond, $block) = @{$chunk}; 6044 6045 # If the condition carries leading newlines, then count those as offsets. 6046 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s); 6047 my $offset = statement_rawlines($whitespace) - 1; 6048 6049 $allowed[$allow] = 0; 6050 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n"; 6051 6052 # We have looked at and allowed this specific line. 6053 $suppress_ifbraces{$ln + $offset} = 1; 6054 6055 $herectx .= "$rawlines[$ln + $offset]\n[...]\n"; 6056 $ln += statement_rawlines($block) - 1; 6057 6058 substr($block, 0, length($cond), ''); 6059 6060 $seen++ if ($block =~ /^\s*{/); 6061 6062 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n"; 6063 if (statement_lines($cond) > 1) { 6064 #print "APW: ALLOWED: cond<$cond>\n"; 6065 $allowed[$allow] = 1; 6066 } 6067 if ($block =~/\b(?:if|for|while)\b/) { 6068 #print "APW: ALLOWED: block<$block>\n"; 6069 $allowed[$allow] = 1; 6070 } 6071 if (statement_block_size($block) > 1) { 6072 #print "APW: ALLOWED: lines block<$block>\n"; 6073 $allowed[$allow] = 1; 6074 } 6075 $allow++; 6076 } 6077 if ($seen) { 6078 my $sum_allowed = 0; 6079 foreach (@allowed) { 6080 $sum_allowed += $_; 6081 } 6082 if ($sum_allowed == 0) { 6083 WARN("BRACES", 6084 "braces {} are not necessary for any arm of this statement\n" . $herectx); 6085 } elsif ($sum_allowed != $allow && 6086 $seen != $allow) { 6087 CHK("BRACES", 6088 "braces {} should be used on all arms of this statement\n" . $herectx); 6089 } 6090 } 6091 } 6092 } 6093 if (!defined $suppress_ifbraces{$linenr - 1} && 6094 $line =~ /\b(if|while|for|else)\b/) { 6095 my $allowed = 0; 6096 6097 # Check the pre-context. 6098 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) { 6099 #print "APW: ALLOWED: pre<$1>\n"; 6100 $allowed = 1; 6101 } 6102 6103 my ($level, $endln, @chunks) = 6104 ctx_statement_full($linenr, $realcnt, $-[0]); 6105 6106 # Check the condition. 6107 my ($cond, $block) = @{$chunks[0]}; 6108 #print "CHECKING<$linenr> cond<$cond> block<$block>\n"; 6109 if (defined $cond) { 6110 substr($block, 0, length($cond), ''); 6111 } 6112 if (statement_lines($cond) > 1) { 6113 #print "APW: ALLOWED: cond<$cond>\n"; 6114 $allowed = 1; 6115 } 6116 if ($block =~/\b(?:if|for|while)\b/) { 6117 #print "APW: ALLOWED: block<$block>\n"; 6118 $allowed = 1; 6119 } 6120 if (statement_block_size($block) > 1) { 6121 #print "APW: ALLOWED: lines block<$block>\n"; 6122 $allowed = 1; 6123 } 6124 # Check the post-context. 6125 if (defined $chunks[1]) { 6126 my ($cond, $block) = @{$chunks[1]}; 6127 if (defined $cond) { 6128 substr($block, 0, length($cond), ''); 6129 } 6130 if ($block =~ /^\s*\{/) { 6131 #print "APW: ALLOWED: chunk-1 block<$block>\n"; 6132 $allowed = 1; 6133 } 6134 } 6135 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) { 6136 my $cnt = statement_rawlines($block); 6137 my $herectx = get_stat_here($linenr, $cnt, $here); 6138 6139 WARN("BRACES", 6140 "braces {} are not necessary for single statement blocks\n" . $herectx); 6141 } 6142 } 6143 6144# check for single line unbalanced braces 6145 if ($sline =~ /^.\s*\}\s*else\s*$/ || 6146 $sline =~ /^.\s*else\s*\{\s*$/) { 6147 CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr); 6148 } 6149 6150# check for unnecessary blank lines around braces 6151 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) { 6152 if (CHK("BRACES", 6153 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) && 6154 $fix && $prevrawline =~ /^\+/) { 6155 fix_delete_line($fixlinenr - 1, $prevrawline); 6156 } 6157 } 6158 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) { 6159 if (CHK("BRACES", 6160 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) && 6161 $fix) { 6162 fix_delete_line($fixlinenr, $rawline); 6163 } 6164 } 6165 6166# no volatiles please 6167 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b}; 6168 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) { 6169 WARN("VOLATILE", 6170 "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr); 6171 } 6172 6173# Check for user-visible strings broken across lines, which breaks the ability 6174# to grep for the string. Make exceptions when the previous string ends in a 6175# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{' 6176# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value 6177 if ($line =~ /^\+\s*$String/ && 6178 $prevline =~ /"\s*$/ && 6179 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) { 6180 if (WARN("SPLIT_STRING", 6181 "quoted string split across lines\n" . $hereprev) && 6182 $fix && 6183 $prevrawline =~ /^\+.*"\s*$/ && 6184 $last_coalesced_string_linenr != $linenr - 1) { 6185 my $extracted_string = get_quoted_string($line, $rawline); 6186 my $comma_close = ""; 6187 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) { 6188 $comma_close = $1; 6189 } 6190 6191 fix_delete_line($fixlinenr - 1, $prevrawline); 6192 fix_delete_line($fixlinenr, $rawline); 6193 my $fixedline = $prevrawline; 6194 $fixedline =~ s/"\s*$//; 6195 $fixedline .= substr($extracted_string, 1) . trim($comma_close); 6196 fix_insert_line($fixlinenr - 1, $fixedline); 6197 $fixedline = $rawline; 6198 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//; 6199 if ($fixedline !~ /\+\s*$/) { 6200 fix_insert_line($fixlinenr, $fixedline); 6201 } 6202 $last_coalesced_string_linenr = $linenr; 6203 } 6204 } 6205 6206# check for missing a space in a string concatenation 6207 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) { 6208 WARN('MISSING_SPACE', 6209 "break quoted strings at a space character\n" . $hereprev); 6210 } 6211 6212# check for an embedded function name in a string when the function is known 6213# This does not work very well for -f --file checking as it depends on patch 6214# context providing the function name or a single line form for in-file 6215# function declarations 6216 if ($line =~ /^\+.*$String/ && 6217 defined($context_function) && 6218 get_quoted_string($line, $rawline) =~ /\b$context_function\b/ && 6219 length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) { 6220 WARN("EMBEDDED_FUNCTION_NAME", 6221 "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr); 6222 } 6223 6224# check for unnecessary function tracing like uses 6225# This does not use $logFunctions because there are many instances like 6226# 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions 6227 if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) { 6228 if (WARN("TRACING_LOGGING", 6229 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) && 6230 $fix) { 6231 fix_delete_line($fixlinenr, $rawline); 6232 } 6233 } 6234 6235# check for spaces before a quoted newline 6236 if ($rawline =~ /^.*\".*\s\\n/) { 6237 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE", 6238 "unnecessary whitespace before a quoted newline\n" . $herecurr) && 6239 $fix) { 6240 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/; 6241 } 6242 6243 } 6244 6245# concatenated string without spaces between elements 6246 if ($line =~ /$String[A-Z_]/ || 6247 ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) { 6248 if (CHK("CONCATENATED_STRING", 6249 "Concatenated strings should use spaces between elements\n" . $herecurr) && 6250 $fix) { 6251 while ($line =~ /($String)/g) { 6252 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]); 6253 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/; 6254 $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/; 6255 } 6256 } 6257 } 6258 6259# uncoalesced string fragments 6260 if ($line =~ /$String\s*[Lu]?"/) { 6261 if (WARN("STRING_FRAGMENTS", 6262 "Consecutive strings are generally better as a single string\n" . $herecurr) && 6263 $fix) { 6264 while ($line =~ /($String)(?=\s*")/g) { 6265 my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]); 6266 $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e; 6267 } 6268 } 6269 } 6270 6271# check for non-standard and hex prefixed decimal printf formats 6272 my $show_L = 1; #don't show the same defect twice 6273 my $show_Z = 1; 6274 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) { 6275 my $string = substr($rawline, $-[1], $+[1] - $-[1]); 6276 $string =~ s/%%/__/g; 6277 # check for %L 6278 if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) { 6279 WARN("PRINTF_L", 6280 "\%L$1 is non-standard C, use %ll$1\n" . $herecurr); 6281 $show_L = 0; 6282 } 6283 # check for %Z 6284 if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) { 6285 WARN("PRINTF_Z", 6286 "%Z$1 is non-standard C, use %z$1\n" . $herecurr); 6287 $show_Z = 0; 6288 } 6289 # check for 0x<decimal> 6290 if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) { 6291 ERROR("PRINTF_0XDECIMAL", 6292 "Prefixing 0x with decimal output is defective\n" . $herecurr); 6293 } 6294 } 6295 6296# check for line continuations in quoted strings with odd counts of " 6297 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) { 6298 WARN("LINE_CONTINUATIONS", 6299 "Avoid line continuations in quoted strings\n" . $herecurr); 6300 } 6301 6302# warn about #if 0 6303 if ($line =~ /^.\s*\#\s*if\s+0\b/) { 6304 WARN("IF_0", 6305 "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr); 6306 } 6307 6308# warn about #if 1 6309 if ($line =~ /^.\s*\#\s*if\s+1\b/) { 6310 WARN("IF_1", 6311 "Consider removing the #if 1 and its #endif\n" . $herecurr); 6312 } 6313 6314# check for needless "if (<foo>) fn(<foo>)" uses 6315 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) { 6316 my $tested = quotemeta($1); 6317 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;'; 6318 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) { 6319 my $func = $1; 6320 if (WARN('NEEDLESS_IF', 6321 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) && 6322 $fix) { 6323 my $do_fix = 1; 6324 my $leading_tabs = ""; 6325 my $new_leading_tabs = ""; 6326 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) { 6327 $leading_tabs = $1; 6328 } else { 6329 $do_fix = 0; 6330 } 6331 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) { 6332 $new_leading_tabs = $1; 6333 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) { 6334 $do_fix = 0; 6335 } 6336 } else { 6337 $do_fix = 0; 6338 } 6339 if ($do_fix) { 6340 fix_delete_line($fixlinenr - 1, $prevrawline); 6341 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/; 6342 } 6343 } 6344 } 6345 } 6346 6347# check for unnecessary "Out of Memory" messages 6348 if ($line =~ /^\+.*\b$logFunctions\s*\(/ && 6349 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ && 6350 (defined $1 || defined $3) && 6351 $linenr > 3) { 6352 my $testval = $2; 6353 my $testline = $lines[$linenr - 3]; 6354 6355 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0); 6356# print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n"); 6357 6358 if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ && 6359 $s !~ /\b__GFP_NOWARN\b/ ) { 6360 WARN("OOM_MESSAGE", 6361 "Possible unnecessary 'out of memory' message\n" . $hereprev); 6362 } 6363 } 6364 6365# check for logging functions with KERN_<LEVEL> 6366 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ && 6367 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) { 6368 my $level = $1; 6369 if (WARN("UNNECESSARY_KERN_LEVEL", 6370 "Possible unnecessary $level\n" . $herecurr) && 6371 $fix) { 6372 $fixed[$fixlinenr] =~ s/\s*$level\s*//; 6373 } 6374 } 6375 6376# check for logging continuations 6377 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) { 6378 WARN("LOGGING_CONTINUATION", 6379 "Avoid logging continuation uses where feasible\n" . $herecurr); 6380 } 6381 6382# check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions 6383 if (defined $stat && 6384 $line =~ /\b$logFunctions\s*\(/ && 6385 index($stat, '"') >= 0) { 6386 my $lc = $stat =~ tr@\n@@; 6387 $lc = $lc + $linenr; 6388 my $stat_real = get_stat_real($linenr, $lc); 6389 pos($stat_real) = index($stat_real, '"'); 6390 while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) { 6391 my $pspec = $1; 6392 my $h = $2; 6393 my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@; 6394 if (WARN("UNNECESSARY_MODIFIER", 6395 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") && 6396 $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) { 6397 my $nspec = $pspec; 6398 $nspec =~ s/h//g; 6399 $fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/; 6400 } 6401 } 6402 } 6403 6404# check for mask then right shift without a parentheses 6405 if ($perl_version_ok && 6406 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ && 6407 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so 6408 WARN("MASK_THEN_SHIFT", 6409 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr); 6410 } 6411 6412# check for pointer comparisons to NULL 6413 if ($perl_version_ok) { 6414 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) { 6415 my $val = $1; 6416 my $equal = "!"; 6417 $equal = "" if ($4 eq "!="); 6418 if (CHK("COMPARISON_TO_NULL", 6419 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) && 6420 $fix) { 6421 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/; 6422 } 6423 } 6424 } 6425 6426# check for bad placement of section $InitAttribute (e.g.: __initdata) 6427 if ($line =~ /(\b$InitAttribute\b)/) { 6428 my $attr = $1; 6429 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) { 6430 my $ptr = $1; 6431 my $var = $2; 6432 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ && 6433 ERROR("MISPLACED_INIT", 6434 "$attr should be placed after $var\n" . $herecurr)) || 6435 ($ptr !~ /\b(union|struct)\s+$attr\b/ && 6436 WARN("MISPLACED_INIT", 6437 "$attr should be placed after $var\n" . $herecurr))) && 6438 $fix) { 6439 $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; 6440 } 6441 } 6442 } 6443 6444# check for $InitAttributeData (ie: __initdata) with const 6445 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) { 6446 my $attr = $1; 6447 $attr =~ /($InitAttributePrefix)(.*)/; 6448 my $attr_prefix = $1; 6449 my $attr_type = $2; 6450 if (ERROR("INIT_ATTRIBUTE", 6451 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) && 6452 $fix) { 6453 $fixed[$fixlinenr] =~ 6454 s/$InitAttributeData/${attr_prefix}initconst/; 6455 } 6456 } 6457 6458# check for $InitAttributeConst (ie: __initconst) without const 6459 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) { 6460 my $attr = $1; 6461 if (ERROR("INIT_ATTRIBUTE", 6462 "Use of $attr requires a separate use of const\n" . $herecurr) && 6463 $fix) { 6464 my $lead = $fixed[$fixlinenr] =~ 6465 /(^\+\s*(?:static\s+))/; 6466 $lead = rtrim($1); 6467 $lead = "$lead " if ($lead !~ /^\+$/); 6468 $lead = "${lead}const "; 6469 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/; 6470 } 6471 } 6472 6473# check for __read_mostly with const non-pointer (should just be const) 6474 if ($line =~ /\b__read_mostly\b/ && 6475 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) { 6476 if (ERROR("CONST_READ_MOSTLY", 6477 "Invalid use of __read_mostly with const type\n" . $herecurr) && 6478 $fix) { 6479 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//; 6480 } 6481 } 6482 6483# don't use __constant_<foo> functions outside of include/uapi/ 6484 if ($realfile !~ m@^include/uapi/@ && 6485 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) { 6486 my $constant_func = $1; 6487 my $func = $constant_func; 6488 $func =~ s/^__constant_//; 6489 if (WARN("CONSTANT_CONVERSION", 6490 "$constant_func should be $func\n" . $herecurr) && 6491 $fix) { 6492 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g; 6493 } 6494 } 6495 6496# prefer usleep_range over udelay 6497 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) { 6498 my $delay = $1; 6499 # ignore udelay's < 10, however 6500 if (! ($delay < 10) ) { 6501 CHK("USLEEP_RANGE", 6502 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr); 6503 } 6504 if ($delay > 2000) { 6505 WARN("LONG_UDELAY", 6506 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr); 6507 } 6508 } 6509 6510# warn about unexpectedly long msleep's 6511 if ($line =~ /\bmsleep\s*\((\d+)\);/) { 6512 if ($1 < 20) { 6513 WARN("MSLEEP", 6514 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr); 6515 } 6516 } 6517 6518# check for comparisons of jiffies 6519 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) { 6520 WARN("JIFFIES_COMPARISON", 6521 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr); 6522 } 6523 6524# check for comparisons of get_jiffies_64() 6525 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) { 6526 WARN("JIFFIES_COMPARISON", 6527 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr); 6528 } 6529 6530# warn about #ifdefs in C files 6531# if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) { 6532# print "#ifdef in C files should be avoided\n"; 6533# print "$herecurr"; 6534# $clean = 0; 6535# } 6536 6537# warn about spacing in #ifdefs 6538 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) { 6539 if (ERROR("SPACING", 6540 "exactly one space required after that #$1\n" . $herecurr) && 6541 $fix) { 6542 $fixed[$fixlinenr] =~ 6543 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /; 6544 } 6545 6546 } 6547 6548# check for spinlock_t definitions without a comment. 6549 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ || 6550 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) { 6551 my $which = $1; 6552 if (!ctx_has_comment($first_line, $linenr)) { 6553 CHK("UNCOMMENTED_DEFINITION", 6554 "$1 definition without comment\n" . $herecurr); 6555 } 6556 } 6557# check for memory barriers without a comment. 6558 6559 my $barriers = qr{ 6560 mb| 6561 rmb| 6562 wmb 6563 }x; 6564 my $barrier_stems = qr{ 6565 mb__before_atomic| 6566 mb__after_atomic| 6567 store_release| 6568 load_acquire| 6569 store_mb| 6570 (?:$barriers) 6571 }x; 6572 my $all_barriers = qr{ 6573 (?:$barriers)| 6574 smp_(?:$barrier_stems)| 6575 virt_(?:$barrier_stems) 6576 }x; 6577 6578 if ($line =~ /\b(?:$all_barriers)\s*\(/) { 6579 if (!ctx_has_comment($first_line, $linenr)) { 6580 WARN("MEMORY_BARRIER", 6581 "memory barrier without comment\n" . $herecurr); 6582 } 6583 } 6584 6585 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x; 6586 6587 if ($realfile !~ m@^include/asm-generic/@ && 6588 $realfile !~ m@/barrier\.h$@ && 6589 $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ && 6590 $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) { 6591 WARN("MEMORY_BARRIER", 6592 "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr); 6593 } 6594 6595# check for waitqueue_active without a comment. 6596 if ($line =~ /\bwaitqueue_active\s*\(/) { 6597 if (!ctx_has_comment($first_line, $linenr)) { 6598 WARN("WAITQUEUE_ACTIVE", 6599 "waitqueue_active without comment\n" . $herecurr); 6600 } 6601 } 6602 6603# check for data_race without a comment. 6604 if ($line =~ /\bdata_race\s*\(/) { 6605 if (!ctx_has_comment($first_line, $linenr)) { 6606 WARN("DATA_RACE", 6607 "data_race without comment\n" . $herecurr); 6608 } 6609 } 6610 6611# check of hardware specific defines 6612 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) { 6613 CHK("ARCH_DEFINES", 6614 "architecture specific defines should be avoided\n" . $herecurr); 6615 } 6616 6617# check that the storage class is not after a type 6618 if ($line =~ /\b($Type)\s+($Storage)\b/) { 6619 WARN("STORAGE_CLASS", 6620 "storage class '$2' should be located before type '$1'\n" . $herecurr); 6621 } 6622# Check that the storage class is at the beginning of a declaration 6623 if ($line =~ /\b$Storage\b/ && 6624 $line !~ /^.\s*$Storage/ && 6625 $line =~ /^.\s*(.+?)\$Storage\s/ && 6626 $1 !~ /[\,\)]\s*$/) { 6627 WARN("STORAGE_CLASS", 6628 "storage class should be at the beginning of the declaration\n" . $herecurr); 6629 } 6630 6631# check the location of the inline attribute, that it is between 6632# storage class and type. 6633 if ($line =~ /\b$Type\s+$Inline\b/ || 6634 $line =~ /\b$Inline\s+$Storage\b/) { 6635 ERROR("INLINE_LOCATION", 6636 "inline keyword should sit between storage class and type\n" . $herecurr); 6637 } 6638 6639# Check for __inline__ and __inline, prefer inline 6640 if ($realfile !~ m@\binclude/uapi/@ && 6641 $line =~ /\b(__inline__|__inline)\b/) { 6642 if (WARN("INLINE", 6643 "plain inline is preferred over $1\n" . $herecurr) && 6644 $fix) { 6645 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/; 6646 6647 } 6648 } 6649 6650# Check for compiler attributes 6651 if ($realfile !~ m@\binclude/uapi/@ && 6652 $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) { 6653 my $attr = $1; 6654 $attr =~ s/\s*\(\s*(.*)\)\s*/$1/; 6655 6656 my %attr_list = ( 6657 "alias" => "__alias", 6658 "aligned" => "__aligned", 6659 "always_inline" => "__always_inline", 6660 "assume_aligned" => "__assume_aligned", 6661 "cold" => "__cold", 6662 "const" => "__attribute_const__", 6663 "copy" => "__copy", 6664 "designated_init" => "__designated_init", 6665 "externally_visible" => "__visible", 6666 "format" => "printf|scanf", 6667 "gnu_inline" => "__gnu_inline", 6668 "malloc" => "__malloc", 6669 "mode" => "__mode", 6670 "no_caller_saved_registers" => "__no_caller_saved_registers", 6671 "noclone" => "__noclone", 6672 "noinline" => "noinline", 6673 "nonstring" => "__nonstring", 6674 "noreturn" => "__noreturn", 6675 "packed" => "__packed", 6676 "pure" => "__pure", 6677 "section" => "__section", 6678 "used" => "__used", 6679 "weak" => "__weak" 6680 ); 6681 6682 while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) { 6683 my $orig_attr = $1; 6684 my $params = ''; 6685 $params = $2 if defined($2); 6686 my $curr_attr = $orig_attr; 6687 $curr_attr =~ s/^[\s_]+|[\s_]+$//g; 6688 if (exists($attr_list{$curr_attr})) { 6689 my $new = $attr_list{$curr_attr}; 6690 if ($curr_attr eq "format" && $params) { 6691 $params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/; 6692 $new = "__$1\($2"; 6693 } else { 6694 $new = "$new$params"; 6695 } 6696 if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO", 6697 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) && 6698 $fix) { 6699 my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?'; 6700 $fixed[$fixlinenr] =~ s/$remove//; 6701 $fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/; 6702 $fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/; 6703 $fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//; 6704 } 6705 } 6706 } 6707 6708 # Check for __attribute__ unused, prefer __always_unused or __maybe_unused 6709 if ($attr =~ /^_*unused/) { 6710 WARN("PREFER_DEFINED_ATTRIBUTE_MACRO", 6711 "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr); 6712 } 6713 } 6714 6715# Check for __attribute__ weak, or __weak declarations (may have link issues) 6716 if ($perl_version_ok && 6717 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ && 6718 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ || 6719 $line =~ /\b__weak\b/)) { 6720 ERROR("WEAK_DECLARATION", 6721 "Using weak declarations can have unintended link defects\n" . $herecurr); 6722 } 6723 6724# check for c99 types like uint8_t used outside of uapi/ and tools/ 6725 if ($realfile !~ m@\binclude/uapi/@ && 6726 $realfile !~ m@\btools/@ && 6727 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) { 6728 my $type = $1; 6729 if ($type =~ /\b($typeC99Typedefs)\b/) { 6730 $type = $1; 6731 my $kernel_type = 'u'; 6732 $kernel_type = 's' if ($type =~ /^_*[si]/); 6733 $type =~ /(\d+)/; 6734 $kernel_type .= $1; 6735 if (CHK("PREFER_KERNEL_TYPES", 6736 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) && 6737 $fix) { 6738 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/; 6739 } 6740 } 6741 } 6742 6743# check for cast of C90 native int or longer types constants 6744 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) { 6745 my $cast = $1; 6746 my $const = $2; 6747 my $suffix = ""; 6748 my $newconst = $const; 6749 $newconst =~ s/${Int_type}$//; 6750 $suffix .= 'U' if ($cast =~ /\bunsigned\b/); 6751 if ($cast =~ /\blong\s+long\b/) { 6752 $suffix .= 'LL'; 6753 } elsif ($cast =~ /\blong\b/) { 6754 $suffix .= 'L'; 6755 } 6756 if (WARN("TYPECAST_INT_CONSTANT", 6757 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) && 6758 $fix) { 6759 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/; 6760 } 6761 } 6762 6763# check for sizeof(&) 6764 if ($line =~ /\bsizeof\s*\(\s*\&/) { 6765 WARN("SIZEOF_ADDRESS", 6766 "sizeof(& should be avoided\n" . $herecurr); 6767 } 6768 6769# check for sizeof without parenthesis 6770 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) { 6771 if (WARN("SIZEOF_PARENTHESIS", 6772 "sizeof $1 should be sizeof($1)\n" . $herecurr) && 6773 $fix) { 6774 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex; 6775 } 6776 } 6777 6778# check for struct spinlock declarations 6779 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) { 6780 WARN("USE_SPINLOCK_T", 6781 "struct spinlock should be spinlock_t\n" . $herecurr); 6782 } 6783 6784# check for seq_printf uses that could be seq_puts 6785 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) { 6786 my $fmt = get_quoted_string($line, $rawline); 6787 $fmt =~ s/%%//g; 6788 if ($fmt !~ /%/) { 6789 if (WARN("PREFER_SEQ_PUTS", 6790 "Prefer seq_puts to seq_printf\n" . $herecurr) && 6791 $fix) { 6792 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/; 6793 } 6794 } 6795 } 6796 6797# check for vsprintf extension %p<foo> misuses 6798 if ($perl_version_ok && 6799 defined $stat && 6800 $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s && 6801 $1 !~ /^_*volatile_*$/) { 6802 my $stat_real; 6803 6804 my $lc = $stat =~ tr@\n@@; 6805 $lc = $lc + $linenr; 6806 for (my $count = $linenr; $count <= $lc; $count++) { 6807 my $specifier; 6808 my $extension; 6809 my $qualifier; 6810 my $bad_specifier = ""; 6811 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0)); 6812 $fmt =~ s/%%//g; 6813 6814 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) { 6815 $specifier = $1; 6816 $extension = $2; 6817 $qualifier = $3; 6818 if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ || 6819 ($extension eq "f" && 6820 defined $qualifier && $qualifier !~ /^w/) || 6821 ($extension eq "4" && 6822 defined $qualifier && $qualifier !~ /^cc/)) { 6823 $bad_specifier = $specifier; 6824 last; 6825 } 6826 if ($extension eq "x" && !defined($stat_real)) { 6827 if (!defined($stat_real)) { 6828 $stat_real = get_stat_real($linenr, $lc); 6829 } 6830 WARN("VSPRINTF_SPECIFIER_PX", 6831 "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n"); 6832 } 6833 } 6834 if ($bad_specifier ne "") { 6835 my $stat_real = get_stat_real($linenr, $lc); 6836 my $msg_level = \&WARN; 6837 my $ext_type = "Invalid"; 6838 my $use = ""; 6839 if ($bad_specifier =~ /p[Ff]/) { 6840 $use = " - use %pS instead"; 6841 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/); 6842 } elsif ($bad_specifier =~ /pA/) { 6843 $use = " - '%pA' is only intended to be used from Rust code"; 6844 $msg_level = \&ERROR; 6845 } 6846 6847 &{$msg_level}("VSPRINTF_POINTER_EXTENSION", 6848 "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n"); 6849 } 6850 } 6851 } 6852 6853# Check for misused memsets 6854 if ($perl_version_ok && 6855 defined $stat && 6856 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) { 6857 6858 my $ms_addr = $2; 6859 my $ms_val = $7; 6860 my $ms_size = $12; 6861 6862 if ($ms_size =~ /^(0x|)0$/i) { 6863 ERROR("MEMSET", 6864 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n"); 6865 } elsif ($ms_size =~ /^(0x|)1$/i) { 6866 WARN("MEMSET", 6867 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n"); 6868 } 6869 } 6870 6871# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar) 6872# if ($perl_version_ok && 6873# defined $stat && 6874# $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) { 6875# if (WARN("PREFER_ETHER_ADDR_COPY", 6876# "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") && 6877# $fix) { 6878# $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/; 6879# } 6880# } 6881 6882# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar) 6883# if ($perl_version_ok && 6884# defined $stat && 6885# $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) { 6886# WARN("PREFER_ETHER_ADDR_EQUAL", 6887# "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n") 6888# } 6889 6890# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr 6891# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr 6892# if ($perl_version_ok && 6893# defined $stat && 6894# $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) { 6895# 6896# my $ms_val = $7; 6897# 6898# if ($ms_val =~ /^(?:0x|)0+$/i) { 6899# if (WARN("PREFER_ETH_ZERO_ADDR", 6900# "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") && 6901# $fix) { 6902# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/; 6903# } 6904# } elsif ($ms_val =~ /^(?:0xff|255)$/i) { 6905# if (WARN("PREFER_ETH_BROADCAST_ADDR", 6906# "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") && 6907# $fix) { 6908# $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/; 6909# } 6910# } 6911# } 6912 6913# strlcpy uses that should likely be strscpy 6914 if ($line =~ /\bstrlcpy\s*\(/) { 6915 WARN("STRLCPY", 6916 "Prefer strscpy over strlcpy - see: https://lore.kernel.org/r/CAHk-=wgfRnXz0W3D37d01q3JFkr_i_uTL=V6A6G1oUZcprmknw\@mail.gmail.com/\n" . $herecurr); 6917 } 6918 6919# typecasts on min/max could be min_t/max_t 6920 if ($perl_version_ok && 6921 defined $stat && 6922 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) { 6923 if (defined $2 || defined $7) { 6924 my $call = $1; 6925 my $cast1 = deparenthesize($2); 6926 my $arg1 = $3; 6927 my $cast2 = deparenthesize($7); 6928 my $arg2 = $8; 6929 my $cast; 6930 6931 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) { 6932 $cast = "$cast1 or $cast2"; 6933 } elsif ($cast1 ne "") { 6934 $cast = $cast1; 6935 } else { 6936 $cast = $cast2; 6937 } 6938 WARN("MINMAX", 6939 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n"); 6940 } 6941 } 6942 6943# check usleep_range arguments 6944 if ($perl_version_ok && 6945 defined $stat && 6946 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) { 6947 my $min = $1; 6948 my $max = $7; 6949 if ($min eq $max) { 6950 WARN("USLEEP_RANGE", 6951 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n"); 6952 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ && 6953 $min > $max) { 6954 WARN("USLEEP_RANGE", 6955 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n"); 6956 } 6957 } 6958 6959# check for naked sscanf 6960 if ($perl_version_ok && 6961 defined $stat && 6962 $line =~ /\bsscanf\b/ && 6963 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ && 6964 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ && 6965 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) { 6966 my $lc = $stat =~ tr@\n@@; 6967 $lc = $lc + $linenr; 6968 my $stat_real = get_stat_real($linenr, $lc); 6969 WARN("NAKED_SSCANF", 6970 "unchecked sscanf return value\n" . "$here\n$stat_real\n"); 6971 } 6972 6973# check for simple sscanf that should be kstrto<foo> 6974 if ($perl_version_ok && 6975 defined $stat && 6976 $line =~ /\bsscanf\b/) { 6977 my $lc = $stat =~ tr@\n@@; 6978 $lc = $lc + $linenr; 6979 my $stat_real = get_stat_real($linenr, $lc); 6980 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) { 6981 my $format = $6; 6982 my $count = $format =~ tr@%@%@; 6983 if ($count == 1 && 6984 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) { 6985 WARN("SSCANF_TO_KSTRTO", 6986 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n"); 6987 } 6988 } 6989 } 6990 6991# check for new externs in .h files. 6992 if ($realfile =~ /\.h$/ && 6993 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) { 6994 if (CHK("AVOID_EXTERNS", 6995 "extern prototypes should be avoided in .h files\n" . $herecurr) && 6996 $fix) { 6997 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/; 6998 } 6999 } 7000 7001# check for new externs in .c files. 7002 if ($realfile =~ /\.c$/ && defined $stat && 7003 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s) 7004 { 7005 my $function_name = $1; 7006 my $paren_space = $2; 7007 7008 my $s = $stat; 7009 if (defined $cond) { 7010 substr($s, 0, length($cond), ''); 7011 } 7012 if ($s =~ /^\s*;/) 7013 { 7014 WARN("AVOID_EXTERNS", 7015 "externs should be avoided in .c files\n" . $herecurr); 7016 } 7017 7018 if ($paren_space =~ /\n/) { 7019 WARN("FUNCTION_ARGUMENTS", 7020 "arguments for function declarations should follow identifier\n" . $herecurr); 7021 } 7022 7023 } elsif ($realfile =~ /\.c$/ && defined $stat && 7024 $stat =~ /^.\s*extern\s+/) 7025 { 7026 WARN("AVOID_EXTERNS", 7027 "externs should be avoided in .c files\n" . $herecurr); 7028 } 7029 7030# check for function declarations that have arguments without identifier names 7031 if (defined $stat && 7032 $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s && 7033 $1 ne "void") { 7034 my $args = trim($1); 7035 while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) { 7036 my $arg = trim($1); 7037 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) { 7038 WARN("FUNCTION_ARGUMENTS", 7039 "function definition argument '$arg' should also have an identifier name\n" . $herecurr); 7040 } 7041 } 7042 } 7043 7044# check for function definitions 7045 if ($perl_version_ok && 7046 defined $stat && 7047 $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) { 7048 $context_function = $1; 7049 7050# check for multiline function definition with misplaced open brace 7051 my $ok = 0; 7052 my $cnt = statement_rawlines($stat); 7053 my $herectx = $here . "\n"; 7054 for (my $n = 0; $n < $cnt; $n++) { 7055 my $rl = raw_line($linenr, $n); 7056 $herectx .= $rl . "\n"; 7057 $ok = 1 if ($rl =~ /^[ \+]\{/); 7058 $ok = 1 if ($rl =~ /\{/ && $n == 0); 7059 last if $rl =~ /^[ \+].*\{/; 7060 } 7061 if (!$ok) { 7062 ERROR("OPEN_BRACE", 7063 "open brace '{' following function definitions go on the next line\n" . $herectx); 7064 } 7065 } 7066 7067# checks for new __setup's 7068 if ($rawline =~ /\b__setup\("([^"]*)"/) { 7069 my $name = $1; 7070 7071 if (!grep(/$name/, @setup_docs)) { 7072 CHK("UNDOCUMENTED_SETUP", 7073 "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr); 7074 } 7075 } 7076 7077# check for pointless casting of alloc functions 7078 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) { 7079 WARN("UNNECESSARY_CASTS", 7080 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr); 7081 } 7082 7083# alloc style 7084# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...) 7085 if ($perl_version_ok && 7086 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) { 7087 CHK("ALLOC_SIZEOF_STRUCT", 7088 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr); 7089 } 7090 7091# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc 7092 if ($perl_version_ok && 7093 defined $stat && 7094 $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) { 7095 my $oldfunc = $3; 7096 my $a1 = $4; 7097 my $a2 = $10; 7098 my $newfunc = "kmalloc_array"; 7099 $newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc"); 7100 $newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc"); 7101 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc"); 7102 my $r1 = $a1; 7103 my $r2 = $a2; 7104 if ($a1 =~ /^sizeof\s*\S/) { 7105 $r1 = $a2; 7106 $r2 = $a1; 7107 } 7108 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ && 7109 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) { 7110 my $cnt = statement_rawlines($stat); 7111 my $herectx = get_stat_here($linenr, $cnt, $here); 7112 7113 if (WARN("ALLOC_WITH_MULTIPLY", 7114 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) && 7115 $cnt == 1 && 7116 $fix) { 7117 $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e; 7118 } 7119 } 7120 } 7121 7122# check for krealloc arg reuse 7123 if ($perl_version_ok && 7124 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ && 7125 $1 eq $3) { 7126 WARN("KREALLOC_ARG_REUSE", 7127 "Reusing the krealloc arg is almost always a bug\n" . $herecurr); 7128 } 7129 7130# check for alloc argument mismatch 7131 if ($line =~ /\b((?:devm_)?(?:kcalloc|kmalloc_array))\s*\(\s*sizeof\b/) { 7132 WARN("ALLOC_ARRAY_ARGS", 7133 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr); 7134 } 7135 7136# check for multiple semicolons 7137 if ($line =~ /;\s*;\s*$/) { 7138 if (WARN("ONE_SEMICOLON", 7139 "Statements terminations use 1 semicolon\n" . $herecurr) && 7140 $fix) { 7141 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g; 7142 } 7143 } 7144 7145# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi 7146 if ($realfile !~ m@^include/uapi/@ && 7147 $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) { 7148 my $ull = ""; 7149 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i); 7150 if (CHK("BIT_MACRO", 7151 "Prefer using the BIT$ull macro\n" . $herecurr) && 7152 $fix) { 7153 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/; 7154 } 7155 } 7156 7157# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too) 7158 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) { 7159 WARN("IS_ENABLED_CONFIG", 7160 "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr); 7161 } 7162 7163# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE 7164 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) { 7165 my $config = $1; 7166 if (WARN("PREFER_IS_ENABLED", 7167 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) && 7168 $fix) { 7169 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)"; 7170 } 7171 } 7172 7173# check for /* fallthrough */ like comment, prefer fallthrough; 7174 my @fallthroughs = ( 7175 'fallthrough', 7176 '@fallthrough@', 7177 'lint -fallthrough[ \t]*', 7178 'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)', 7179 '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?', 7180 'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?', 7181 'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?', 7182 ); 7183 if ($raw_comment ne '') { 7184 foreach my $ft (@fallthroughs) { 7185 if ($raw_comment =~ /$ft/) { 7186 my $msg_level = \&WARN; 7187 $msg_level = \&CHK if ($file); 7188 &{$msg_level}("PREFER_FALLTHROUGH", 7189 "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr); 7190 last; 7191 } 7192 } 7193 } 7194 7195# check for switch/default statements without a break; 7196 if ($perl_version_ok && 7197 defined $stat && 7198 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) { 7199 my $cnt = statement_rawlines($stat); 7200 my $herectx = get_stat_here($linenr, $cnt, $here); 7201 7202 WARN("DEFAULT_NO_BREAK", 7203 "switch default: should use break\n" . $herectx); 7204 } 7205 7206# check for gcc specific __FUNCTION__ 7207 if ($line =~ /\b__FUNCTION__\b/) { 7208 if (WARN("USE_FUNC", 7209 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) && 7210 $fix) { 7211 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g; 7212 } 7213 } 7214 7215# check for uses of __DATE__, __TIME__, __TIMESTAMP__ 7216 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) { 7217 ERROR("DATE_TIME", 7218 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr); 7219 } 7220 7221# check for use of yield() 7222 if ($line =~ /\byield\s*\(\s*\)/) { 7223 WARN("YIELD", 7224 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr); 7225 } 7226 7227# check for comparisons against true and false 7228 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) { 7229 my $lead = $1; 7230 my $arg = $2; 7231 my $test = $3; 7232 my $otype = $4; 7233 my $trail = $5; 7234 my $op = "!"; 7235 7236 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i); 7237 7238 my $type = lc($otype); 7239 if ($type =~ /^(?:true|false)$/) { 7240 if (("$test" eq "==" && "$type" eq "true") || 7241 ("$test" eq "!=" && "$type" eq "false")) { 7242 $op = ""; 7243 } 7244 7245 CHK("BOOL_COMPARISON", 7246 "Using comparison to $otype is error prone\n" . $herecurr); 7247 7248## maybe suggesting a correct construct would better 7249## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr); 7250 7251 } 7252 } 7253 7254# check for semaphores initialized locked 7255 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) { 7256 WARN("CONSIDER_COMPLETION", 7257 "consider using a completion\n" . $herecurr); 7258 } 7259 7260# recommend kstrto* over simple_strto* and strict_strto* 7261 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) { 7262 WARN("CONSIDER_KSTRTO", 7263 "$1 is obsolete, use k$3 instead\n" . $herecurr); 7264 } 7265 7266# check for __initcall(), use device_initcall() explicitly or more appropriate function please 7267 if ($line =~ /^.\s*__initcall\s*\(/) { 7268 WARN("USE_DEVICE_INITCALL", 7269 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr); 7270 } 7271 7272# check for spin_is_locked(), suggest lockdep instead 7273 if ($line =~ /\bspin_is_locked\(/) { 7274 WARN("USE_LOCKDEP", 7275 "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr); 7276 } 7277 7278# check for deprecated apis 7279 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) { 7280 my $deprecated_api = $1; 7281 my $new_api = $deprecated_apis{$deprecated_api}; 7282 WARN("DEPRECATED_API", 7283 "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr); 7284 } 7285 7286# check for various structs that are normally const (ops, kgdb, device_tree) 7287# and avoid what seem like struct definitions 'struct foo {' 7288 if (defined($const_structs) && 7289 $line !~ /\bconst\b/ && 7290 $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) { 7291 WARN("CONST_STRUCT", 7292 "struct $1 should normally be const\n" . $herecurr); 7293 } 7294 7295# use of NR_CPUS is usually wrong 7296# ignore definitions of NR_CPUS and usage to define arrays as likely right 7297# ignore designated initializers using NR_CPUS 7298 if ($line =~ /\bNR_CPUS\b/ && 7299 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ && 7300 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ && 7301 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ && 7302 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ && 7303 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ && 7304 $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/) 7305 { 7306 WARN("NR_CPUS", 7307 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr); 7308 } 7309 7310# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong. 7311 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) { 7312 ERROR("DEFINE_ARCH_HAS", 7313 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr); 7314 } 7315 7316# likely/unlikely comparisons similar to "(likely(foo) > 0)" 7317 if ($perl_version_ok && 7318 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) { 7319 WARN("LIKELY_MISUSE", 7320 "Using $1 should generally have parentheses around the comparison\n" . $herecurr); 7321 } 7322 7323# return sysfs_emit(foo, fmt, ...) fmt without newline 7324 if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ && 7325 substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) { 7326 my $offset = $+[6] - 1; 7327 if (WARN("SYSFS_EMIT", 7328 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) && 7329 $fix) { 7330 substr($fixed[$fixlinenr], $offset, 0) = '\\n'; 7331 } 7332 } 7333 7334# nested likely/unlikely calls 7335 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) { 7336 WARN("LIKELY_MISUSE", 7337 "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr); 7338 } 7339 7340# whine mightly about in_atomic 7341 if ($line =~ /\bin_atomic\s*\(/) { 7342 if ($realfile =~ m@^drivers/@) { 7343 ERROR("IN_ATOMIC", 7344 "do not use in_atomic in drivers\n" . $herecurr); 7345 } elsif ($realfile !~ m@^kernel/@) { 7346 WARN("IN_ATOMIC", 7347 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr); 7348 } 7349 } 7350 7351# check for lockdep_set_novalidate_class 7352 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ || 7353 $line =~ /__lockdep_no_validate__\s*\)/ ) { 7354 if ($realfile !~ m@^kernel/lockdep@ && 7355 $realfile !~ m@^include/linux/lockdep@ && 7356 $realfile !~ m@^drivers/base/core@) { 7357 ERROR("LOCKDEP", 7358 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr); 7359 } 7360 } 7361 7362 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ || 7363 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) { 7364 WARN("EXPORTED_WORLD_WRITABLE", 7365 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr); 7366 } 7367 7368# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO> 7369# and whether or not function naming is typical and if 7370# DEVICE_ATTR permissions uses are unusual too 7371 if ($perl_version_ok && 7372 defined $stat && 7373 $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) { 7374 my $var = $1; 7375 my $perms = $2; 7376 my $show = $3; 7377 my $store = $4; 7378 my $octal_perms = perms_to_octal($perms); 7379 if ($show =~ /^${var}_show$/ && 7380 $store =~ /^${var}_store$/ && 7381 $octal_perms eq "0644") { 7382 if (WARN("DEVICE_ATTR_RW", 7383 "Use DEVICE_ATTR_RW\n" . $herecurr) && 7384 $fix) { 7385 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/; 7386 } 7387 } elsif ($show =~ /^${var}_show$/ && 7388 $store =~ /^NULL$/ && 7389 $octal_perms eq "0444") { 7390 if (WARN("DEVICE_ATTR_RO", 7391 "Use DEVICE_ATTR_RO\n" . $herecurr) && 7392 $fix) { 7393 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/; 7394 } 7395 } elsif ($show =~ /^NULL$/ && 7396 $store =~ /^${var}_store$/ && 7397 $octal_perms eq "0200") { 7398 if (WARN("DEVICE_ATTR_WO", 7399 "Use DEVICE_ATTR_WO\n" . $herecurr) && 7400 $fix) { 7401 $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/; 7402 } 7403 } elsif ($octal_perms eq "0644" || 7404 $octal_perms eq "0444" || 7405 $octal_perms eq "0200") { 7406 my $newshow = "$show"; 7407 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show"); 7408 my $newstore = $store; 7409 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store"); 7410 my $rename = ""; 7411 if ($show ne $newshow) { 7412 $rename .= " '$show' to '$newshow'"; 7413 } 7414 if ($store ne $newstore) { 7415 $rename .= " '$store' to '$newstore'"; 7416 } 7417 WARN("DEVICE_ATTR_FUNCTIONS", 7418 "Consider renaming function(s)$rename\n" . $herecurr); 7419 } else { 7420 WARN("DEVICE_ATTR_PERMS", 7421 "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr); 7422 } 7423 } 7424 7425# Mode permission misuses where it seems decimal should be octal 7426# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop 7427# o Ignore module_param*(...) uses with a decimal 0 permission as that has a 7428# specific definition of not visible in sysfs. 7429# o Ignore proc_create*(...) uses with a decimal 0 permission as that means 7430# use the default permissions 7431 if ($perl_version_ok && 7432 defined $stat && 7433 $line =~ /$mode_perms_search/) { 7434 foreach my $entry (@mode_permission_funcs) { 7435 my $func = $entry->[0]; 7436 my $arg_pos = $entry->[1]; 7437 7438 my $lc = $stat =~ tr@\n@@; 7439 $lc = $lc + $linenr; 7440 my $stat_real = get_stat_real($linenr, $lc); 7441 7442 my $skip_args = ""; 7443 if ($arg_pos > 1) { 7444 $arg_pos--; 7445 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}"; 7446 } 7447 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]"; 7448 if ($stat =~ /$test/) { 7449 my $val = $1; 7450 $val = $6 if ($skip_args ne ""); 7451 if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") && 7452 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) || 7453 ($val =~ /^$Octal$/ && length($val) ne 4))) { 7454 ERROR("NON_OCTAL_PERMISSIONS", 7455 "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real); 7456 } 7457 if ($val =~ /^$Octal$/ && (oct($val) & 02)) { 7458 ERROR("EXPORTED_WORLD_WRITABLE", 7459 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real); 7460 } 7461 } 7462 } 7463 } 7464 7465# check for uses of S_<PERMS> that could be octal for readability 7466 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) { 7467 my $oval = $1; 7468 my $octal = perms_to_octal($oval); 7469 if (WARN("SYMBOLIC_PERMS", 7470 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) && 7471 $fix) { 7472 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/; 7473 } 7474 } 7475 7476# validate content of MODULE_LICENSE against list from include/linux/module.h 7477 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) { 7478 my $extracted_string = get_quoted_string($line, $rawline); 7479 my $valid_licenses = qr{ 7480 GPL| 7481 GPL\ v2| 7482 GPL\ and\ additional\ rights| 7483 Dual\ BSD/GPL| 7484 Dual\ MIT/GPL| 7485 Dual\ MPL/GPL| 7486 Proprietary 7487 }x; 7488 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) { 7489 WARN("MODULE_LICENSE", 7490 "unknown module license " . $extracted_string . "\n" . $herecurr); 7491 } 7492 if (!$file && $extracted_string eq '"GPL v2"') { 7493 if (WARN("MODULE_LICENSE", 7494 "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) && 7495 $fix) { 7496 $fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/; 7497 } 7498 } 7499 } 7500 7501# check for sysctl duplicate constants 7502 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) { 7503 WARN("DUPLICATED_SYSCTL_CONST", 7504 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr); 7505 } 7506 } 7507 7508 # If we have no input at all, then there is nothing to report on 7509 # so just keep quiet. 7510 if ($#rawlines == -1) { 7511 exit(0); 7512 } 7513 7514 # In mailback mode only produce a report in the negative, for 7515 # things that appear to be patches. 7516 if ($mailback && ($clean == 1 || !$is_patch)) { 7517 exit(0); 7518 } 7519 7520 # This is not a patch, and we are in 'no-patch' mode so 7521 # just keep quiet. 7522 if (!$chk_patch && !$is_patch) { 7523 exit(0); 7524 } 7525 7526 if (!$is_patch && $filename !~ /cover-letter\.patch$/) { 7527 ERROR("NOT_UNIFIED_DIFF", 7528 "Does not appear to be a unified-diff format patch\n"); 7529 } 7530 if ($is_patch && $has_commit_log && $chk_signoff) { 7531 if ($signoff == 0) { 7532 ERROR("MISSING_SIGN_OFF", 7533 "Missing Signed-off-by: line(s)\n"); 7534 } elsif ($authorsignoff != 1) { 7535 # authorsignoff values: 7536 # 0 -> missing sign off 7537 # 1 -> sign off identical 7538 # 2 -> names and addresses match, comments mismatch 7539 # 3 -> addresses match, names different 7540 # 4 -> names match, addresses different 7541 # 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match 7542 7543 my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'"; 7544 7545 if ($authorsignoff == 0) { 7546 ERROR("NO_AUTHOR_SIGN_OFF", 7547 "Missing Signed-off-by: line by nominal patch author '$author'\n"); 7548 } elsif ($authorsignoff == 2) { 7549 CHK("FROM_SIGN_OFF_MISMATCH", 7550 "From:/Signed-off-by: email comments mismatch: $sob_msg\n"); 7551 } elsif ($authorsignoff == 3) { 7552 WARN("FROM_SIGN_OFF_MISMATCH", 7553 "From:/Signed-off-by: email name mismatch: $sob_msg\n"); 7554 } elsif ($authorsignoff == 4) { 7555 WARN("FROM_SIGN_OFF_MISMATCH", 7556 "From:/Signed-off-by: email address mismatch: $sob_msg\n"); 7557 } elsif ($authorsignoff == 5) { 7558 WARN("FROM_SIGN_OFF_MISMATCH", 7559 "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n"); 7560 } 7561 } 7562 } 7563 7564 print report_dump(); 7565 if ($summary && !($clean == 1 && $quiet == 1)) { 7566 print "$filename " if ($summary_file); 7567 print "total: $cnt_error errors, $cnt_warn warnings, " . 7568 (($check)? "$cnt_chk checks, " : "") . 7569 "$cnt_lines lines checked\n"; 7570 } 7571 7572 if ($quiet == 0) { 7573 # If there were any defects found and not already fixing them 7574 if (!$clean and !$fix) { 7575 print << "EOM" 7576 7577NOTE: For some of the reported defects, checkpatch may be able to 7578 mechanically convert to the typical style using --fix or --fix-inplace. 7579EOM 7580 } 7581 # If there were whitespace errors which cleanpatch can fix 7582 # then suggest that. 7583 if ($rpt_cleaners) { 7584 $rpt_cleaners = 0; 7585 print << "EOM" 7586 7587NOTE: Whitespace errors detected. 7588 You may wish to use scripts/cleanpatch or scripts/cleanfile 7589EOM 7590 } 7591 } 7592 7593 if ($clean == 0 && $fix && 7594 ("@rawlines" ne "@fixed" || 7595 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) { 7596 my $newfile = $filename; 7597 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace); 7598 my $linecount = 0; 7599 my $f; 7600 7601 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted); 7602 7603 open($f, '>', $newfile) 7604 or die "$P: Can't open $newfile for write\n"; 7605 foreach my $fixed_line (@fixed) { 7606 $linecount++; 7607 if ($file) { 7608 if ($linecount > 3) { 7609 $fixed_line =~ s/^\+//; 7610 print $f $fixed_line . "\n"; 7611 } 7612 } else { 7613 print $f $fixed_line . "\n"; 7614 } 7615 } 7616 close($f); 7617 7618 if (!$quiet) { 7619 print << "EOM"; 7620 7621Wrote EXPERIMENTAL --fix correction(s) to '$newfile' 7622 7623Do _NOT_ trust the results written to this file. 7624Do _NOT_ submit these changes without inspecting them for correctness. 7625 7626This EXPERIMENTAL file is simply a convenience to help rewrite patches. 7627No warranties, expressed or implied... 7628EOM 7629 } 7630 } 7631 7632 if ($quiet == 0) { 7633 print "\n"; 7634 if ($clean == 1) { 7635 print "$vname has no obvious style problems and is ready for submission.\n"; 7636 } else { 7637 print "$vname has style problems, please review.\n"; 7638 } 7639 } 7640 return $clean; 7641} 7642