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