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