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