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