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