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