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