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