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