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