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