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