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