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