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