checkpatch: remove false warning for commit reference
[muen/linux.git] / 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 use strict;
9 use warnings;
10 use POSIX;
11 use File::Basename;
12 use Cwd 'abs_path';
13 use Term::ANSIColor qw(:constants);
14
15 my $P = $0;
16 my $D = dirname(abs_path($P));
17
18 my $V = '0.32';
19
20 use Getopt::Long qw(:config no_auto_abbrev);
21
22 my $quiet = 0;
23 my $tree = 1;
24 my $chk_signoff = 1;
25 my $chk_patch = 1;
26 my $tst_only;
27 my $emacs = 0;
28 my $terse = 0;
29 my $showfile = 0;
30 my $file = 0;
31 my $git = 0;
32 my %git_commits = ();
33 my $check = 0;
34 my $check_orig = 0;
35 my $summary = 1;
36 my $mailback = 0;
37 my $summary_file = 0;
38 my $show_types = 0;
39 my $list_types = 0;
40 my $fix = 0;
41 my $fix_inplace = 0;
42 my $root;
43 my %debug;
44 my %camelcase = ();
45 my %use_type = ();
46 my @use = ();
47 my %ignore_type = ();
48 my @ignore = ();
49 my $help = 0;
50 my $configuration_file = ".checkpatch.conf";
51 my $max_line_length = 80;
52 my $ignore_perl_version = 0;
53 my $minimum_perl_version = 5.10.0;
54 my $min_conf_desc_length = 4;
55 my $spelling_file = "$D/spelling.txt";
56 my $codespell = 0;
57 my $codespellfile = "/usr/share/codespell/dictionary.txt";
58 my $conststructsfile = "$D/const_structs.checkpatch";
59 my $typedefsfile = "";
60 my $color = 1;
61 my $allow_c99_comments = 1;
62
63 sub help {
64         my ($exitcode) = @_;
65
66         print << "EOM";
67 Usage: $P [OPTION]... [FILE]...
68 Version: $V
69
70 Options:
71   -q, --quiet                quiet
72   --no-tree                  run without a kernel tree
73   --no-signoff               do not check for 'Signed-off-by' line
74   --patch                    treat FILE as patchfile (default)
75   --emacs                    emacs compile window format
76   --terse                    one line per report
77   --showfile                 emit diffed file position, not input file position
78   -g, --git                  treat FILE as a single commit or git revision range
79                              single git commit with:
80                                <rev>
81                                <rev>^
82                                <rev>~n
83                              multiple git commits with:
84                                <rev1>..<rev2>
85                                <rev1>...<rev2>
86                                <rev>-<count>
87                              git merges are ignored
88   -f, --file                 treat FILE as regular source file
89   --subjective, --strict     enable more subjective tests
90   --list-types               list the possible message types
91   --types TYPE(,TYPE2...)    show only these comma separated message types
92   --ignore TYPE(,TYPE2...)   ignore various comma separated message types
93   --show-types               show the specific message type in the output
94   --max-line-length=n        set the maximum line length, if exceeded, warn
95   --min-conf-desc-length=n   set the min description length, if shorter, warn
96   --root=PATH                PATH to the kernel tree root
97   --no-summary               suppress the per-file summary
98   --mailback                 only produce a report in case of warnings/errors
99   --summary-file             include the filename in summary
100   --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
101                              'values', 'possible', 'type', and 'attr' (default
102                              is all off)
103   --test-only=WORD           report only warnings/errors containing WORD
104                              literally
105   --fix                      EXPERIMENTAL - may create horrible results
106                              If correctable single-line errors exist, create
107                              "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
108                              with potential errors corrected to the preferred
109                              checkpatch style
110   --fix-inplace              EXPERIMENTAL - may create horrible results
111                              Is the same as --fix, but overwrites the input
112                              file.  It's your fault if there's no backup or git
113   --ignore-perl-version      override checking of perl version.  expect
114                              runtime errors.
115   --codespell                Use the codespell dictionary for spelling/typos
116                              (default:/usr/share/codespell/dictionary.txt)
117   --codespellfile            Use this codespell dictionary
118   --typedefsfile             Read additional types from this file
119   --color                    Use colors when output is STDOUT (default: on)
120   -h, --help, --version      display this help and exit
121
122 When FILE is - read standard input.
123 EOM
124
125         exit($exitcode);
126 }
127
128 sub uniq {
129         my %seen;
130         return grep { !$seen{$_}++ } @_;
131 }
132
133 sub list_types {
134         my ($exitcode) = @_;
135
136         my $count = 0;
137
138         local $/ = undef;
139
140         open(my $script, '<', abs_path($P)) or
141             die "$P: Can't read '$P' $!\n";
142
143         my $text = <$script>;
144         close($script);
145
146         my @types = ();
147         for ($text =~ /\b(?:(?:CHK|WARN|ERROR)\s*\(\s*"([^"]+)")/g) {
148                 push (@types, $_);
149         }
150         @types = sort(uniq(@types));
151         print("#\tMessage type\n\n");
152         foreach my $type (@types) {
153                 print(++$count . "\t" . $type . "\n");
154         }
155
156         exit($exitcode);
157 }
158
159 my $conf = which_conf($configuration_file);
160 if (-f $conf) {
161         my @conf_args;
162         open(my $conffile, '<', "$conf")
163             or warn "$P: Can't find a readable $configuration_file file $!\n";
164
165         while (<$conffile>) {
166                 my $line = $_;
167
168                 $line =~ s/\s*\n?$//g;
169                 $line =~ s/^\s*//g;
170                 $line =~ s/\s+/ /g;
171
172                 next if ($line =~ m/^\s*#/);
173                 next if ($line =~ m/^\s*$/);
174
175                 my @words = split(" ", $line);
176                 foreach my $word (@words) {
177                         last if ($word =~ m/^#/);
178                         push (@conf_args, $word);
179                 }
180         }
181         close($conffile);
182         unshift(@ARGV, @conf_args) if @conf_args;
183 }
184
185 GetOptions(
186         'q|quiet+'      => \$quiet,
187         'tree!'         => \$tree,
188         'signoff!'      => \$chk_signoff,
189         'patch!'        => \$chk_patch,
190         'emacs!'        => \$emacs,
191         'terse!'        => \$terse,
192         'showfile!'     => \$showfile,
193         'f|file!'       => \$file,
194         'g|git!'        => \$git,
195         'subjective!'   => \$check,
196         'strict!'       => \$check,
197         'ignore=s'      => \@ignore,
198         'types=s'       => \@use,
199         'show-types!'   => \$show_types,
200         'list-types!'   => \$list_types,
201         'max-line-length=i' => \$max_line_length,
202         'min-conf-desc-length=i' => \$min_conf_desc_length,
203         'root=s'        => \$root,
204         'summary!'      => \$summary,
205         'mailback!'     => \$mailback,
206         'summary-file!' => \$summary_file,
207         'fix!'          => \$fix,
208         'fix-inplace!'  => \$fix_inplace,
209         'ignore-perl-version!' => \$ignore_perl_version,
210         'debug=s'       => \%debug,
211         'test-only=s'   => \$tst_only,
212         'codespell!'    => \$codespell,
213         'codespellfile=s'       => \$codespellfile,
214         'typedefsfile=s'        => \$typedefsfile,
215         'color!'        => \$color,
216         'h|help'        => \$help,
217         'version'       => \$help
218 ) or help(1);
219
220 help(0) if ($help);
221
222 list_types(0) if ($list_types);
223
224 $fix = 1 if ($fix_inplace);
225 $check_orig = $check;
226
227 my $exit = 0;
228
229 if ($^V && $^V lt $minimum_perl_version) {
230         printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
231         if (!$ignore_perl_version) {
232                 exit(1);
233         }
234 }
235
236 #if no filenames are given, push '-' to read patch from stdin
237 if ($#ARGV < 0) {
238         push(@ARGV, '-');
239 }
240
241 sub hash_save_array_words {
242         my ($hashRef, $arrayRef) = @_;
243
244         my @array = split(/,/, join(',', @$arrayRef));
245         foreach my $word (@array) {
246                 $word =~ s/\s*\n?$//g;
247                 $word =~ s/^\s*//g;
248                 $word =~ s/\s+/ /g;
249                 $word =~ tr/[a-z]/[A-Z]/;
250
251                 next if ($word =~ m/^\s*#/);
252                 next if ($word =~ m/^\s*$/);
253
254                 $hashRef->{$word}++;
255         }
256 }
257
258 sub hash_show_words {
259         my ($hashRef, $prefix) = @_;
260
261         if (keys %$hashRef) {
262                 print "\nNOTE: $prefix message types:";
263                 foreach my $word (sort keys %$hashRef) {
264                         print " $word";
265                 }
266                 print "\n";
267         }
268 }
269
270 hash_save_array_words(\%ignore_type, \@ignore);
271 hash_save_array_words(\%use_type, \@use);
272
273 my $dbg_values = 0;
274 my $dbg_possible = 0;
275 my $dbg_type = 0;
276 my $dbg_attr = 0;
277 for my $key (keys %debug) {
278         ## no critic
279         eval "\${dbg_$key} = '$debug{$key}';";
280         die "$@" if ($@);
281 }
282
283 my $rpt_cleaners = 0;
284
285 if ($terse) {
286         $emacs = 1;
287         $quiet++;
288 }
289
290 if ($tree) {
291         if (defined $root) {
292                 if (!top_of_kernel_tree($root)) {
293                         die "$P: $root: --root does not point at a valid tree\n";
294                 }
295         } else {
296                 if (top_of_kernel_tree('.')) {
297                         $root = '.';
298                 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
299                                                 top_of_kernel_tree($1)) {
300                         $root = $1;
301                 }
302         }
303
304         if (!defined $root) {
305                 print "Must be run from the top-level dir. of a kernel tree\n";
306                 exit(2);
307         }
308 }
309
310 my $emitted_corrupt = 0;
311
312 our $Ident      = qr{
313                         [A-Za-z_][A-Za-z\d_]*
314                         (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
315                 }x;
316 our $Storage    = qr{extern|static|asmlinkage};
317 our $Sparse     = qr{
318                         __user|
319                         __kernel|
320                         __force|
321                         __iomem|
322                         __must_check|
323                         __init_refok|
324                         __kprobes|
325                         __ref|
326                         __rcu|
327                         __private
328                 }x;
329 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
330 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
331 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
332 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
333 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
334
335 # Notes to $Attribute:
336 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
337 our $Attribute  = qr{
338                         const|
339                         __percpu|
340                         __nocast|
341                         __safe|
342                         __bitwise|
343                         __packed__|
344                         __packed2__|
345                         __naked|
346                         __maybe_unused|
347                         __always_unused|
348                         __noreturn|
349                         __used|
350                         __cold|
351                         __pure|
352                         __noclone|
353                         __deprecated|
354                         __read_mostly|
355                         __kprobes|
356                         $InitAttribute|
357                         ____cacheline_aligned|
358                         ____cacheline_aligned_in_smp|
359                         ____cacheline_internodealigned_in_smp|
360                         __weak
361                   }x;
362 our $Modifier;
363 our $Inline     = qr{inline|__always_inline|noinline|__inline|__inline__};
364 our $Member     = qr{->$Ident|\.$Ident|\[[^]]*\]};
365 our $Lval       = qr{$Ident(?:$Member)*};
366
367 our $Int_type   = qr{(?i)llu|ull|ll|lu|ul|l|u};
368 our $Binary     = qr{(?i)0b[01]+$Int_type?};
369 our $Hex        = qr{(?i)0x[0-9a-f]+$Int_type?};
370 our $Int        = qr{[0-9]+$Int_type?};
371 our $Octal      = qr{0[0-7]+$Int_type?};
372 our $String     = qr{"[X\t]*"};
373 our $Float_hex  = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
374 our $Float_dec  = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
375 our $Float_int  = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
376 our $Float      = qr{$Float_hex|$Float_dec|$Float_int};
377 our $Constant   = qr{$Float|$Binary|$Octal|$Hex|$Int};
378 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
379 our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
380 our $Arithmetic = qr{\+|-|\*|\/|%};
381 our $Operators  = qr{
382                         <=|>=|==|!=|
383                         =>|->|<<|>>|<|>|!|~|
384                         &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
385                   }x;
386
387 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
388
389 our $BasicType;
390 our $NonptrType;
391 our $NonptrTypeMisordered;
392 our $NonptrTypeWithAttr;
393 our $Type;
394 our $TypeMisordered;
395 our $Declare;
396 our $DeclareMisordered;
397
398 our $NON_ASCII_UTF8     = qr{
399         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
400         |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
401         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
402         |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
403         |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
404         | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
405         |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
406 }x;
407
408 our $UTF8       = qr{
409         [\x09\x0A\x0D\x20-\x7E]              # ASCII
410         | $NON_ASCII_UTF8
411 }x;
412
413 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
414 our $typeOtherOSTypedefs = qr{(?x:
415         u_(?:char|short|int|long) |          # bsd
416         u(?:nchar|short|int|long)            # sysv
417 )};
418 our $typeKernelTypedefs = qr{(?x:
419         (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
420         atomic_t
421 )};
422 our $typeTypedefs = qr{(?x:
423         $typeC99Typedefs\b|
424         $typeOtherOSTypedefs\b|
425         $typeKernelTypedefs\b
426 )};
427
428 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
429
430 our $logFunctions = qr{(?x:
431         printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
432         (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
433         WARN(?:_RATELIMIT|_ONCE|)|
434         panic|
435         MODULE_[A-Z_]+|
436         seq_vprintf|seq_printf|seq_puts
437 )};
438
439 our $signature_tags = qr{(?xi:
440         Signed-off-by:|
441         Acked-by:|
442         Tested-by:|
443         Reviewed-by:|
444         Reported-by:|
445         Suggested-by:|
446         To:|
447         Cc:
448 )};
449
450 our @typeListMisordered = (
451         qr{char\s+(?:un)?signed},
452         qr{int\s+(?:(?:un)?signed\s+)?short\s},
453         qr{int\s+short(?:\s+(?:un)?signed)},
454         qr{short\s+int(?:\s+(?:un)?signed)},
455         qr{(?:un)?signed\s+int\s+short},
456         qr{short\s+(?:un)?signed},
457         qr{long\s+int\s+(?:un)?signed},
458         qr{int\s+long\s+(?:un)?signed},
459         qr{long\s+(?:un)?signed\s+int},
460         qr{int\s+(?:un)?signed\s+long},
461         qr{int\s+(?:un)?signed},
462         qr{int\s+long\s+long\s+(?:un)?signed},
463         qr{long\s+long\s+int\s+(?:un)?signed},
464         qr{long\s+long\s+(?:un)?signed\s+int},
465         qr{long\s+long\s+(?:un)?signed},
466         qr{long\s+(?:un)?signed},
467 );
468
469 our @typeList = (
470         qr{void},
471         qr{(?:(?:un)?signed\s+)?char},
472         qr{(?:(?:un)?signed\s+)?short\s+int},
473         qr{(?:(?:un)?signed\s+)?short},
474         qr{(?:(?:un)?signed\s+)?int},
475         qr{(?:(?:un)?signed\s+)?long\s+int},
476         qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
477         qr{(?:(?:un)?signed\s+)?long\s+long},
478         qr{(?:(?:un)?signed\s+)?long},
479         qr{(?:un)?signed},
480         qr{float},
481         qr{double},
482         qr{bool},
483         qr{struct\s+$Ident},
484         qr{union\s+$Ident},
485         qr{enum\s+$Ident},
486         qr{${Ident}_t},
487         qr{${Ident}_handler},
488         qr{${Ident}_handler_fn},
489         @typeListMisordered,
490 );
491
492 our $C90_int_types = qr{(?x:
493         long\s+long\s+int\s+(?:un)?signed|
494         long\s+long\s+(?:un)?signed\s+int|
495         long\s+long\s+(?:un)?signed|
496         (?:(?:un)?signed\s+)?long\s+long\s+int|
497         (?:(?:un)?signed\s+)?long\s+long|
498         int\s+long\s+long\s+(?:un)?signed|
499         int\s+(?:(?:un)?signed\s+)?long\s+long|
500
501         long\s+int\s+(?:un)?signed|
502         long\s+(?:un)?signed\s+int|
503         long\s+(?:un)?signed|
504         (?:(?:un)?signed\s+)?long\s+int|
505         (?:(?:un)?signed\s+)?long|
506         int\s+long\s+(?:un)?signed|
507         int\s+(?:(?:un)?signed\s+)?long|
508
509         int\s+(?:un)?signed|
510         (?:(?:un)?signed\s+)?int
511 )};
512
513 our @typeListFile = ();
514 our @typeListWithAttr = (
515         @typeList,
516         qr{struct\s+$InitAttribute\s+$Ident},
517         qr{union\s+$InitAttribute\s+$Ident},
518 );
519
520 our @modifierList = (
521         qr{fastcall},
522 );
523 our @modifierListFile = ();
524
525 our @mode_permission_funcs = (
526         ["module_param", 3],
527         ["module_param_(?:array|named|string)", 4],
528         ["module_param_array_named", 5],
529         ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
530         ["proc_create(?:_data|)", 2],
531         ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
532         ["IIO_DEV_ATTR_[A-Z_]+", 1],
533         ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
534         ["SENSOR_TEMPLATE(?:_2|)", 3],
535         ["__ATTR", 2],
536 );
537
538 #Create a search pattern for all these functions to speed up a loop below
539 our $mode_perms_search = "";
540 foreach my $entry (@mode_permission_funcs) {
541         $mode_perms_search .= '|' if ($mode_perms_search ne "");
542         $mode_perms_search .= $entry->[0];
543 }
544
545 our $mode_perms_world_writable = qr{
546         S_IWUGO         |
547         S_IWOTH         |
548         S_IRWXUGO       |
549         S_IALLUGO       |
550         0[0-7][0-7][2367]
551 }x;
552
553 our %mode_permission_string_types = (
554         "S_IRWXU" => 0700,
555         "S_IRUSR" => 0400,
556         "S_IWUSR" => 0200,
557         "S_IXUSR" => 0100,
558         "S_IRWXG" => 0070,
559         "S_IRGRP" => 0040,
560         "S_IWGRP" => 0020,
561         "S_IXGRP" => 0010,
562         "S_IRWXO" => 0007,
563         "S_IROTH" => 0004,
564         "S_IWOTH" => 0002,
565         "S_IXOTH" => 0001,
566         "S_IRWXUGO" => 0777,
567         "S_IRUGO" => 0444,
568         "S_IWUGO" => 0222,
569         "S_IXUGO" => 0111,
570 );
571
572 #Create a search pattern for all these strings to speed up a loop below
573 our $mode_perms_string_search = "";
574 foreach my $entry (keys %mode_permission_string_types) {
575         $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
576         $mode_perms_string_search .= $entry;
577 }
578
579 our $allowed_asm_includes = qr{(?x:
580         irq|
581         memory|
582         time|
583         reboot
584 )};
585 # memory.h: ARM has a custom one
586
587 # Load common spelling mistakes and build regular expression list.
588 my $misspellings;
589 my %spelling_fix;
590
591 if (open(my $spelling, '<', $spelling_file)) {
592         while (<$spelling>) {
593                 my $line = $_;
594
595                 $line =~ s/\s*\n?$//g;
596                 $line =~ s/^\s*//g;
597
598                 next if ($line =~ m/^\s*#/);
599                 next if ($line =~ m/^\s*$/);
600
601                 my ($suspect, $fix) = split(/\|\|/, $line);
602
603                 $spelling_fix{$suspect} = $fix;
604         }
605         close($spelling);
606 } else {
607         warn "No typos will be found - file '$spelling_file': $!\n";
608 }
609
610 if ($codespell) {
611         if (open(my $spelling, '<', $codespellfile)) {
612                 while (<$spelling>) {
613                         my $line = $_;
614
615                         $line =~ s/\s*\n?$//g;
616                         $line =~ s/^\s*//g;
617
618                         next if ($line =~ m/^\s*#/);
619                         next if ($line =~ m/^\s*$/);
620                         next if ($line =~ m/, disabled/i);
621
622                         $line =~ s/,.*$//;
623
624                         my ($suspect, $fix) = split(/->/, $line);
625
626                         $spelling_fix{$suspect} = $fix;
627                 }
628                 close($spelling);
629         } else {
630                 warn "No codespell typos will be found - file '$codespellfile': $!\n";
631         }
632 }
633
634 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
635
636 sub read_words {
637         my ($wordsRef, $file) = @_;
638
639         if (open(my $words, '<', $file)) {
640                 while (<$words>) {
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                         if ($line =~ /\s/) {
649                                 print("$file: '$line' invalid - ignored\n");
650                                 next;
651                         }
652
653                         $$wordsRef .= '|' if ($$wordsRef ne "");
654                         $$wordsRef .= $line;
655                 }
656                 close($file);
657                 return 1;
658         }
659
660         return 0;
661 }
662
663 my $const_structs = "";
664 read_words(\$const_structs, $conststructsfile)
665     or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
666
667 my $typeOtherTypedefs = "";
668 if (length($typedefsfile)) {
669         read_words(\$typeOtherTypedefs, $typedefsfile)
670             or warn "No additional types will be considered - file '$typedefsfile': $!\n";
671 }
672 $typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
673
674 sub build_types {
675         my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
676         my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
677         my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
678         my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
679         $Modifier       = qr{(?:$Attribute|$Sparse|$mods)};
680         $BasicType      = qr{
681                                 (?:$typeTypedefs\b)|
682                                 (?:${all}\b)
683                 }x;
684         $NonptrType     = qr{
685                         (?:$Modifier\s+|const\s+)*
686                         (?:
687                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
688                                 (?:$typeTypedefs\b)|
689                                 (?:${all}\b)
690                         )
691                         (?:\s+$Modifier|\s+const)*
692                   }x;
693         $NonptrTypeMisordered   = qr{
694                         (?:$Modifier\s+|const\s+)*
695                         (?:
696                                 (?:${Misordered}\b)
697                         )
698                         (?:\s+$Modifier|\s+const)*
699                   }x;
700         $NonptrTypeWithAttr     = qr{
701                         (?:$Modifier\s+|const\s+)*
702                         (?:
703                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
704                                 (?:$typeTypedefs\b)|
705                                 (?:${allWithAttr}\b)
706                         )
707                         (?:\s+$Modifier|\s+const)*
708                   }x;
709         $Type   = qr{
710                         $NonptrType
711                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
712                         (?:\s+$Inline|\s+$Modifier)*
713                   }x;
714         $TypeMisordered = qr{
715                         $NonptrTypeMisordered
716                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
717                         (?:\s+$Inline|\s+$Modifier)*
718                   }x;
719         $Declare        = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
720         $DeclareMisordered      = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
721 }
722 build_types();
723
724 our $Typecast   = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
725
726 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
727 # requires at least perl version v5.10.0
728 # Any use must be runtime checked with $^V
729
730 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
731 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
732 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
733
734 our $declaration_macros = qr{(?x:
735         (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
736         (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
737         (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
738 )};
739
740 sub deparenthesize {
741         my ($string) = @_;
742         return "" if (!defined($string));
743
744         while ($string =~ /^\s*\(.*\)\s*$/) {
745                 $string =~ s@^\s*\(\s*@@;
746                 $string =~ s@\s*\)\s*$@@;
747         }
748
749         $string =~ s@\s+@ @g;
750
751         return $string;
752 }
753
754 sub seed_camelcase_file {
755         my ($file) = @_;
756
757         return if (!(-f $file));
758
759         local $/;
760
761         open(my $include_file, '<', "$file")
762             or warn "$P: Can't read '$file' $!\n";
763         my $text = <$include_file>;
764         close($include_file);
765
766         my @lines = split('\n', $text);
767
768         foreach my $line (@lines) {
769                 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
770                 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
771                         $camelcase{$1} = 1;
772                 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
773                         $camelcase{$1} = 1;
774                 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
775                         $camelcase{$1} = 1;
776                 }
777         }
778 }
779
780 sub is_maintained_obsolete {
781         my ($filename) = @_;
782
783         return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
784
785         my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
786
787         return $status =~ /obsolete/i;
788 }
789
790 my $camelcase_seeded = 0;
791 sub seed_camelcase_includes {
792         return if ($camelcase_seeded);
793
794         my $files;
795         my $camelcase_cache = "";
796         my @include_files = ();
797
798         $camelcase_seeded = 1;
799
800         if (-e ".git") {
801                 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
802                 chomp $git_last_include_commit;
803                 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
804         } else {
805                 my $last_mod_date = 0;
806                 $files = `find $root/include -name "*.h"`;
807                 @include_files = split('\n', $files);
808                 foreach my $file (@include_files) {
809                         my $date = POSIX::strftime("%Y%m%d%H%M",
810                                                    localtime((stat $file)[9]));
811                         $last_mod_date = $date if ($last_mod_date < $date);
812                 }
813                 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
814         }
815
816         if ($camelcase_cache ne "" && -f $camelcase_cache) {
817                 open(my $camelcase_file, '<', "$camelcase_cache")
818                     or warn "$P: Can't read '$camelcase_cache' $!\n";
819                 while (<$camelcase_file>) {
820                         chomp;
821                         $camelcase{$_} = 1;
822                 }
823                 close($camelcase_file);
824
825                 return;
826         }
827
828         if (-e ".git") {
829                 $files = `git ls-files "include/*.h"`;
830                 @include_files = split('\n', $files);
831         }
832
833         foreach my $file (@include_files) {
834                 seed_camelcase_file($file);
835         }
836
837         if ($camelcase_cache ne "") {
838                 unlink glob ".checkpatch-camelcase.*";
839                 open(my $camelcase_file, '>', "$camelcase_cache")
840                     or warn "$P: Can't write '$camelcase_cache' $!\n";
841                 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
842                         print $camelcase_file ("$_\n");
843                 }
844                 close($camelcase_file);
845         }
846 }
847
848 sub git_commit_info {
849         my ($commit, $id, $desc) = @_;
850
851         return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
852
853         my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
854         $output =~ s/^\s*//gm;
855         my @lines = split("\n", $output);
856
857         return ($id, $desc) if ($#lines < 0);
858
859         if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
860 # Maybe one day convert this block of bash into something that returns
861 # all matching commit ids, but it's very slow...
862 #
863 #               echo "checking commits $1..."
864 #               git rev-list --remotes | grep -i "^$1" |
865 #               while read line ; do
866 #                   git log --format='%H %s' -1 $line |
867 #                   echo "commit $(cut -c 1-12,41-)"
868 #               done
869         } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
870                 $id = undef;
871         } else {
872                 $id = substr($lines[0], 0, 12);
873                 $desc = substr($lines[0], 41);
874         }
875
876         return ($id, $desc);
877 }
878
879 $chk_signoff = 0 if ($file);
880
881 my @rawlines = ();
882 my @lines = ();
883 my @fixed = ();
884 my @fixed_inserted = ();
885 my @fixed_deleted = ();
886 my $fixlinenr = -1;
887
888 # If input is git commits, extract all commits from the commit expressions.
889 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
890 die "$P: No git repository found\n" if ($git && !-e ".git");
891
892 if ($git) {
893         my @commits = ();
894         foreach my $commit_expr (@ARGV) {
895                 my $git_range;
896                 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
897                         $git_range = "-$2 $1";
898                 } elsif ($commit_expr =~ m/\.\./) {
899                         $git_range = "$commit_expr";
900                 } else {
901                         $git_range = "-1 $commit_expr";
902                 }
903                 my $lines = `git log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
904                 foreach my $line (split(/\n/, $lines)) {
905                         $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
906                         next if (!defined($1) || !defined($2));
907                         my $sha1 = $1;
908                         my $subject = $2;
909                         unshift(@commits, $sha1);
910                         $git_commits{$sha1} = $subject;
911                 }
912         }
913         die "$P: no git commits after extraction!\n" if (@commits == 0);
914         @ARGV = @commits;
915 }
916
917 my $vname;
918 for my $filename (@ARGV) {
919         my $FILE;
920         if ($git) {
921                 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
922                         die "$P: $filename: git format-patch failed - $!\n";
923         } elsif ($file) {
924                 open($FILE, '-|', "diff -u /dev/null $filename") ||
925                         die "$P: $filename: diff failed - $!\n";
926         } elsif ($filename eq '-') {
927                 open($FILE, '<&STDIN');
928         } else {
929                 open($FILE, '<', "$filename") ||
930                         die "$P: $filename: open failed - $!\n";
931         }
932         if ($filename eq '-') {
933                 $vname = 'Your patch';
934         } elsif ($git) {
935                 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
936         } else {
937                 $vname = $filename;
938         }
939         while (<$FILE>) {
940                 chomp;
941                 push(@rawlines, $_);
942         }
943         close($FILE);
944
945         if ($#ARGV > 0 && $quiet == 0) {
946                 print '-' x length($vname) . "\n";
947                 print "$vname\n";
948                 print '-' x length($vname) . "\n";
949         }
950
951         if (!process($filename)) {
952                 $exit = 1;
953         }
954         @rawlines = ();
955         @lines = ();
956         @fixed = ();
957         @fixed_inserted = ();
958         @fixed_deleted = ();
959         $fixlinenr = -1;
960         @modifierListFile = ();
961         @typeListFile = ();
962         build_types();
963 }
964
965 if (!$quiet) {
966         hash_show_words(\%use_type, "Used");
967         hash_show_words(\%ignore_type, "Ignored");
968
969         if ($^V lt 5.10.0) {
970                 print << "EOM"
971
972 NOTE: perl $^V is not modern enough to detect all possible issues.
973       An upgrade to at least perl v5.10.0 is suggested.
974 EOM
975         }
976         if ($exit) {
977                 print << "EOM"
978
979 NOTE: If any of the errors are false positives, please report
980       them to the maintainer, see CHECKPATCH in MAINTAINERS.
981 EOM
982         }
983 }
984
985 exit($exit);
986
987 sub top_of_kernel_tree {
988         my ($root) = @_;
989
990         my @tree_check = (
991                 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
992                 "README", "Documentation", "arch", "include", "drivers",
993                 "fs", "init", "ipc", "kernel", "lib", "scripts",
994         );
995
996         foreach my $check (@tree_check) {
997                 if (! -e $root . '/' . $check) {
998                         return 0;
999                 }
1000         }
1001         return 1;
1002 }
1003
1004 sub parse_email {
1005         my ($formatted_email) = @_;
1006
1007         my $name = "";
1008         my $address = "";
1009         my $comment = "";
1010
1011         if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1012                 $name = $1;
1013                 $address = $2;
1014                 $comment = $3 if defined $3;
1015         } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1016                 $address = $1;
1017                 $comment = $2 if defined $2;
1018         } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1019                 $address = $1;
1020                 $comment = $2 if defined $2;
1021                 $formatted_email =~ s/$address.*$//;
1022                 $name = $formatted_email;
1023                 $name = trim($name);
1024                 $name =~ s/^\"|\"$//g;
1025                 # If there's a name left after stripping spaces and
1026                 # leading quotes, and the address doesn't have both
1027                 # leading and trailing angle brackets, the address
1028                 # is invalid. ie:
1029                 #   "joe smith joe@smith.com" bad
1030                 #   "joe smith <joe@smith.com" bad
1031                 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1032                         $name = "";
1033                         $address = "";
1034                         $comment = "";
1035                 }
1036         }
1037
1038         $name = trim($name);
1039         $name =~ s/^\"|\"$//g;
1040         $address = trim($address);
1041         $address =~ s/^\<|\>$//g;
1042
1043         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1044                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1045                 $name = "\"$name\"";
1046         }
1047
1048         return ($name, $address, $comment);
1049 }
1050
1051 sub format_email {
1052         my ($name, $address) = @_;
1053
1054         my $formatted_email;
1055
1056         $name = trim($name);
1057         $name =~ s/^\"|\"$//g;
1058         $address = trim($address);
1059
1060         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1061                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1062                 $name = "\"$name\"";
1063         }
1064
1065         if ("$name" eq "") {
1066                 $formatted_email = "$address";
1067         } else {
1068                 $formatted_email = "$name <$address>";
1069         }
1070
1071         return $formatted_email;
1072 }
1073
1074 sub which {
1075         my ($bin) = @_;
1076
1077         foreach my $path (split(/:/, $ENV{PATH})) {
1078                 if (-e "$path/$bin") {
1079                         return "$path/$bin";
1080                 }
1081         }
1082
1083         return "";
1084 }
1085
1086 sub which_conf {
1087         my ($conf) = @_;
1088
1089         foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1090                 if (-e "$path/$conf") {
1091                         return "$path/$conf";
1092                 }
1093         }
1094
1095         return "";
1096 }
1097
1098 sub expand_tabs {
1099         my ($str) = @_;
1100
1101         my $res = '';
1102         my $n = 0;
1103         for my $c (split(//, $str)) {
1104                 if ($c eq "\t") {
1105                         $res .= ' ';
1106                         $n++;
1107                         for (; ($n % 8) != 0; $n++) {
1108                                 $res .= ' ';
1109                         }
1110                         next;
1111                 }
1112                 $res .= $c;
1113                 $n++;
1114         }
1115
1116         return $res;
1117 }
1118 sub copy_spacing {
1119         (my $res = shift) =~ tr/\t/ /c;
1120         return $res;
1121 }
1122
1123 sub line_stats {
1124         my ($line) = @_;
1125
1126         # Drop the diff line leader and expand tabs
1127         $line =~ s/^.//;
1128         $line = expand_tabs($line);
1129
1130         # Pick the indent from the front of the line.
1131         my ($white) = ($line =~ /^(\s*)/);
1132
1133         return (length($line), length($white));
1134 }
1135
1136 my $sanitise_quote = '';
1137
1138 sub sanitise_line_reset {
1139         my ($in_comment) = @_;
1140
1141         if ($in_comment) {
1142                 $sanitise_quote = '*/';
1143         } else {
1144                 $sanitise_quote = '';
1145         }
1146 }
1147 sub sanitise_line {
1148         my ($line) = @_;
1149
1150         my $res = '';
1151         my $l = '';
1152
1153         my $qlen = 0;
1154         my $off = 0;
1155         my $c;
1156
1157         # Always copy over the diff marker.
1158         $res = substr($line, 0, 1);
1159
1160         for ($off = 1; $off < length($line); $off++) {
1161                 $c = substr($line, $off, 1);
1162
1163                 # Comments we are wacking completly including the begin
1164                 # and end, all to $;.
1165                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1166                         $sanitise_quote = '*/';
1167
1168                         substr($res, $off, 2, "$;$;");
1169                         $off++;
1170                         next;
1171                 }
1172                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1173                         $sanitise_quote = '';
1174                         substr($res, $off, 2, "$;$;");
1175                         $off++;
1176                         next;
1177                 }
1178                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1179                         $sanitise_quote = '//';
1180
1181                         substr($res, $off, 2, $sanitise_quote);
1182                         $off++;
1183                         next;
1184                 }
1185
1186                 # A \ in a string means ignore the next character.
1187                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1188                     $c eq "\\") {
1189                         substr($res, $off, 2, 'XX');
1190                         $off++;
1191                         next;
1192                 }
1193                 # Regular quotes.
1194                 if ($c eq "'" || $c eq '"') {
1195                         if ($sanitise_quote eq '') {
1196                                 $sanitise_quote = $c;
1197
1198                                 substr($res, $off, 1, $c);
1199                                 next;
1200                         } elsif ($sanitise_quote eq $c) {
1201                                 $sanitise_quote = '';
1202                         }
1203                 }
1204
1205                 #print "c<$c> SQ<$sanitise_quote>\n";
1206                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1207                         substr($res, $off, 1, $;);
1208                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1209                         substr($res, $off, 1, $;);
1210                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1211                         substr($res, $off, 1, 'X');
1212                 } else {
1213                         substr($res, $off, 1, $c);
1214                 }
1215         }
1216
1217         if ($sanitise_quote eq '//') {
1218                 $sanitise_quote = '';
1219         }
1220
1221         # The pathname on a #include may be surrounded by '<' and '>'.
1222         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1223                 my $clean = 'X' x length($1);
1224                 $res =~ s@\<.*\>@<$clean>@;
1225
1226         # The whole of a #error is a string.
1227         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1228                 my $clean = 'X' x length($1);
1229                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1230         }
1231
1232         if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1233                 my $match = $1;
1234                 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1235         }
1236
1237         return $res;
1238 }
1239
1240 sub get_quoted_string {
1241         my ($line, $rawline) = @_;
1242
1243         return "" if ($line !~ m/($String)/g);
1244         return substr($rawline, $-[0], $+[0] - $-[0]);
1245 }
1246
1247 sub ctx_statement_block {
1248         my ($linenr, $remain, $off) = @_;
1249         my $line = $linenr - 1;
1250         my $blk = '';
1251         my $soff = $off;
1252         my $coff = $off - 1;
1253         my $coff_set = 0;
1254
1255         my $loff = 0;
1256
1257         my $type = '';
1258         my $level = 0;
1259         my @stack = ();
1260         my $p;
1261         my $c;
1262         my $len = 0;
1263
1264         my $remainder;
1265         while (1) {
1266                 @stack = (['', 0]) if ($#stack == -1);
1267
1268                 #warn "CSB: blk<$blk> remain<$remain>\n";
1269                 # If we are about to drop off the end, pull in more
1270                 # context.
1271                 if ($off >= $len) {
1272                         for (; $remain > 0; $line++) {
1273                                 last if (!defined $lines[$line]);
1274                                 next if ($lines[$line] =~ /^-/);
1275                                 $remain--;
1276                                 $loff = $len;
1277                                 $blk .= $lines[$line] . "\n";
1278                                 $len = length($blk);
1279                                 $line++;
1280                                 last;
1281                         }
1282                         # Bail if there is no further context.
1283                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1284                         if ($off >= $len) {
1285                                 last;
1286                         }
1287                         if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1288                                 $level++;
1289                                 $type = '#';
1290                         }
1291                 }
1292                 $p = $c;
1293                 $c = substr($blk, $off, 1);
1294                 $remainder = substr($blk, $off);
1295
1296                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1297
1298                 # Handle nested #if/#else.
1299                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1300                         push(@stack, [ $type, $level ]);
1301                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1302                         ($type, $level) = @{$stack[$#stack - 1]};
1303                 } elsif ($remainder =~ /^#\s*endif\b/) {
1304                         ($type, $level) = @{pop(@stack)};
1305                 }
1306
1307                 # Statement ends at the ';' or a close '}' at the
1308                 # outermost level.
1309                 if ($level == 0 && $c eq ';') {
1310                         last;
1311                 }
1312
1313                 # An else is really a conditional as long as its not else if
1314                 if ($level == 0 && $coff_set == 0 &&
1315                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1316                                 $remainder =~ /^(else)(?:\s|{)/ &&
1317                                 $remainder !~ /^else\s+if\b/) {
1318                         $coff = $off + length($1) - 1;
1319                         $coff_set = 1;
1320                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1321                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1322                 }
1323
1324                 if (($type eq '' || $type eq '(') && $c eq '(') {
1325                         $level++;
1326                         $type = '(';
1327                 }
1328                 if ($type eq '(' && $c eq ')') {
1329                         $level--;
1330                         $type = ($level != 0)? '(' : '';
1331
1332                         if ($level == 0 && $coff < $soff) {
1333                                 $coff = $off;
1334                                 $coff_set = 1;
1335                                 #warn "CSB: mark coff<$coff>\n";
1336                         }
1337                 }
1338                 if (($type eq '' || $type eq '{') && $c eq '{') {
1339                         $level++;
1340                         $type = '{';
1341                 }
1342                 if ($type eq '{' && $c eq '}') {
1343                         $level--;
1344                         $type = ($level != 0)? '{' : '';
1345
1346                         if ($level == 0) {
1347                                 if (substr($blk, $off + 1, 1) eq ';') {
1348                                         $off++;
1349                                 }
1350                                 last;
1351                         }
1352                 }
1353                 # Preprocessor commands end at the newline unless escaped.
1354                 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1355                         $level--;
1356                         $type = '';
1357                         $off++;
1358                         last;
1359                 }
1360                 $off++;
1361         }
1362         # We are truly at the end, so shuffle to the next line.
1363         if ($off == $len) {
1364                 $loff = $len + 1;
1365                 $line++;
1366                 $remain--;
1367         }
1368
1369         my $statement = substr($blk, $soff, $off - $soff + 1);
1370         my $condition = substr($blk, $soff, $coff - $soff + 1);
1371
1372         #warn "STATEMENT<$statement>\n";
1373         #warn "CONDITION<$condition>\n";
1374
1375         #print "coff<$coff> soff<$off> loff<$loff>\n";
1376
1377         return ($statement, $condition,
1378                         $line, $remain + 1, $off - $loff + 1, $level);
1379 }
1380
1381 sub statement_lines {
1382         my ($stmt) = @_;
1383
1384         # Strip the diff line prefixes and rip blank lines at start and end.
1385         $stmt =~ s/(^|\n)./$1/g;
1386         $stmt =~ s/^\s*//;
1387         $stmt =~ s/\s*$//;
1388
1389         my @stmt_lines = ($stmt =~ /\n/g);
1390
1391         return $#stmt_lines + 2;
1392 }
1393
1394 sub statement_rawlines {
1395         my ($stmt) = @_;
1396
1397         my @stmt_lines = ($stmt =~ /\n/g);
1398
1399         return $#stmt_lines + 2;
1400 }
1401
1402 sub statement_block_size {
1403         my ($stmt) = @_;
1404
1405         $stmt =~ s/(^|\n)./$1/g;
1406         $stmt =~ s/^\s*{//;
1407         $stmt =~ s/}\s*$//;
1408         $stmt =~ s/^\s*//;
1409         $stmt =~ s/\s*$//;
1410
1411         my @stmt_lines = ($stmt =~ /\n/g);
1412         my @stmt_statements = ($stmt =~ /;/g);
1413
1414         my $stmt_lines = $#stmt_lines + 2;
1415         my $stmt_statements = $#stmt_statements + 1;
1416
1417         if ($stmt_lines > $stmt_statements) {
1418                 return $stmt_lines;
1419         } else {
1420                 return $stmt_statements;
1421         }
1422 }
1423
1424 sub ctx_statement_full {
1425         my ($linenr, $remain, $off) = @_;
1426         my ($statement, $condition, $level);
1427
1428         my (@chunks);
1429
1430         # Grab the first conditional/block pair.
1431         ($statement, $condition, $linenr, $remain, $off, $level) =
1432                                 ctx_statement_block($linenr, $remain, $off);
1433         #print "F: c<$condition> s<$statement> remain<$remain>\n";
1434         push(@chunks, [ $condition, $statement ]);
1435         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1436                 return ($level, $linenr, @chunks);
1437         }
1438
1439         # Pull in the following conditional/block pairs and see if they
1440         # could continue the statement.
1441         for (;;) {
1442                 ($statement, $condition, $linenr, $remain, $off, $level) =
1443                                 ctx_statement_block($linenr, $remain, $off);
1444                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1445                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1446                 #print "C: push\n";
1447                 push(@chunks, [ $condition, $statement ]);
1448         }
1449
1450         return ($level, $linenr, @chunks);
1451 }
1452
1453 sub ctx_block_get {
1454         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1455         my $line;
1456         my $start = $linenr - 1;
1457         my $blk = '';
1458         my @o;
1459         my @c;
1460         my @res = ();
1461
1462         my $level = 0;
1463         my @stack = ($level);
1464         for ($line = $start; $remain > 0; $line++) {
1465                 next if ($rawlines[$line] =~ /^-/);
1466                 $remain--;
1467
1468                 $blk .= $rawlines[$line];
1469
1470                 # Handle nested #if/#else.
1471                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1472                         push(@stack, $level);
1473                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1474                         $level = $stack[$#stack - 1];
1475                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1476                         $level = pop(@stack);
1477                 }
1478
1479                 foreach my $c (split(//, $lines[$line])) {
1480                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
1481                         if ($off > 0) {
1482                                 $off--;
1483                                 next;
1484                         }
1485
1486                         if ($c eq $close && $level > 0) {
1487                                 $level--;
1488                                 last if ($level == 0);
1489                         } elsif ($c eq $open) {
1490                                 $level++;
1491                         }
1492                 }
1493
1494                 if (!$outer || $level <= 1) {
1495                         push(@res, $rawlines[$line]);
1496                 }
1497
1498                 last if ($level == 0);
1499         }
1500
1501         return ($level, @res);
1502 }
1503 sub ctx_block_outer {
1504         my ($linenr, $remain) = @_;
1505
1506         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1507         return @r;
1508 }
1509 sub ctx_block {
1510         my ($linenr, $remain) = @_;
1511
1512         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1513         return @r;
1514 }
1515 sub ctx_statement {
1516         my ($linenr, $remain, $off) = @_;
1517
1518         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1519         return @r;
1520 }
1521 sub ctx_block_level {
1522         my ($linenr, $remain) = @_;
1523
1524         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1525 }
1526 sub ctx_statement_level {
1527         my ($linenr, $remain, $off) = @_;
1528
1529         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1530 }
1531
1532 sub ctx_locate_comment {
1533         my ($first_line, $end_line) = @_;
1534
1535         # Catch a comment on the end of the line itself.
1536         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1537         return $current_comment if (defined $current_comment);
1538
1539         # Look through the context and try and figure out if there is a
1540         # comment.
1541         my $in_comment = 0;
1542         $current_comment = '';
1543         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1544                 my $line = $rawlines[$linenr - 1];
1545                 #warn "           $line\n";
1546                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1547                         $in_comment = 1;
1548                 }
1549                 if ($line =~ m@/\*@) {
1550                         $in_comment = 1;
1551                 }
1552                 if (!$in_comment && $current_comment ne '') {
1553                         $current_comment = '';
1554                 }
1555                 $current_comment .= $line . "\n" if ($in_comment);
1556                 if ($line =~ m@\*/@) {
1557                         $in_comment = 0;
1558                 }
1559         }
1560
1561         chomp($current_comment);
1562         return($current_comment);
1563 }
1564 sub ctx_has_comment {
1565         my ($first_line, $end_line) = @_;
1566         my $cmt = ctx_locate_comment($first_line, $end_line);
1567
1568         ##print "LINE: $rawlines[$end_line - 1 ]\n";
1569         ##print "CMMT: $cmt\n";
1570
1571         return ($cmt ne '');
1572 }
1573
1574 sub raw_line {
1575         my ($linenr, $cnt) = @_;
1576
1577         my $offset = $linenr - 1;
1578         $cnt++;
1579
1580         my $line;
1581         while ($cnt) {
1582                 $line = $rawlines[$offset++];
1583                 next if (defined($line) && $line =~ /^-/);
1584                 $cnt--;
1585         }
1586
1587         return $line;
1588 }
1589
1590 sub cat_vet {
1591         my ($vet) = @_;
1592         my ($res, $coded);
1593
1594         $res = '';
1595         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1596                 $res .= $1;
1597                 if ($2 ne '') {
1598                         $coded = sprintf("^%c", unpack('C', $2) + 64);
1599                         $res .= $coded;
1600                 }
1601         }
1602         $res =~ s/$/\$/;
1603
1604         return $res;
1605 }
1606
1607 my $av_preprocessor = 0;
1608 my $av_pending;
1609 my @av_paren_type;
1610 my $av_pend_colon;
1611
1612 sub annotate_reset {
1613         $av_preprocessor = 0;
1614         $av_pending = '_';
1615         @av_paren_type = ('E');
1616         $av_pend_colon = 'O';
1617 }
1618
1619 sub annotate_values {
1620         my ($stream, $type) = @_;
1621
1622         my $res;
1623         my $var = '_' x length($stream);
1624         my $cur = $stream;
1625
1626         print "$stream\n" if ($dbg_values > 1);
1627
1628         while (length($cur)) {
1629                 @av_paren_type = ('E') if ($#av_paren_type < 0);
1630                 print " <" . join('', @av_paren_type) .
1631                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
1632                 if ($cur =~ /^(\s+)/o) {
1633                         print "WS($1)\n" if ($dbg_values > 1);
1634                         if ($1 =~ /\n/ && $av_preprocessor) {
1635                                 $type = pop(@av_paren_type);
1636                                 $av_preprocessor = 0;
1637                         }
1638
1639                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1640                         print "CAST($1)\n" if ($dbg_values > 1);
1641                         push(@av_paren_type, $type);
1642                         $type = 'c';
1643
1644                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1645                         print "DECLARE($1)\n" if ($dbg_values > 1);
1646                         $type = 'T';
1647
1648                 } elsif ($cur =~ /^($Modifier)\s*/) {
1649                         print "MODIFIER($1)\n" if ($dbg_values > 1);
1650                         $type = 'T';
1651
1652                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1653                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1654                         $av_preprocessor = 1;
1655                         push(@av_paren_type, $type);
1656                         if ($2 ne '') {
1657                                 $av_pending = 'N';
1658                         }
1659                         $type = 'E';
1660
1661                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1662                         print "UNDEF($1)\n" if ($dbg_values > 1);
1663                         $av_preprocessor = 1;
1664                         push(@av_paren_type, $type);
1665
1666                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1667                         print "PRE_START($1)\n" if ($dbg_values > 1);
1668                         $av_preprocessor = 1;
1669
1670                         push(@av_paren_type, $type);
1671                         push(@av_paren_type, $type);
1672                         $type = 'E';
1673
1674                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1675                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1676                         $av_preprocessor = 1;
1677
1678                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1679
1680                         $type = 'E';
1681
1682                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1683                         print "PRE_END($1)\n" if ($dbg_values > 1);
1684
1685                         $av_preprocessor = 1;
1686
1687                         # Assume all arms of the conditional end as this
1688                         # one does, and continue as if the #endif was not here.
1689                         pop(@av_paren_type);
1690                         push(@av_paren_type, $type);
1691                         $type = 'E';
1692
1693                 } elsif ($cur =~ /^(\\\n)/o) {
1694                         print "PRECONT($1)\n" if ($dbg_values > 1);
1695
1696                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1697                         print "ATTR($1)\n" if ($dbg_values > 1);
1698                         $av_pending = $type;
1699                         $type = 'N';
1700
1701                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1702                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1703                         if (defined $2) {
1704                                 $av_pending = 'V';
1705                         }
1706                         $type = 'N';
1707
1708                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1709                         print "COND($1)\n" if ($dbg_values > 1);
1710                         $av_pending = 'E';
1711                         $type = 'N';
1712
1713                 } elsif ($cur =~/^(case)/o) {
1714                         print "CASE($1)\n" if ($dbg_values > 1);
1715                         $av_pend_colon = 'C';
1716                         $type = 'N';
1717
1718                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1719                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1720                         $type = 'N';
1721
1722                 } elsif ($cur =~ /^(\()/o) {
1723                         print "PAREN('$1')\n" if ($dbg_values > 1);
1724                         push(@av_paren_type, $av_pending);
1725                         $av_pending = '_';
1726                         $type = 'N';
1727
1728                 } elsif ($cur =~ /^(\))/o) {
1729                         my $new_type = pop(@av_paren_type);
1730                         if ($new_type ne '_') {
1731                                 $type = $new_type;
1732                                 print "PAREN('$1') -> $type\n"
1733                                                         if ($dbg_values > 1);
1734                         } else {
1735                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1736                         }
1737
1738                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1739                         print "FUNC($1)\n" if ($dbg_values > 1);
1740                         $type = 'V';
1741                         $av_pending = 'V';
1742
1743                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1744                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1745                                 $av_pend_colon = 'B';
1746                         } elsif ($type eq 'E') {
1747                                 $av_pend_colon = 'L';
1748                         }
1749                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1750                         $type = 'V';
1751
1752                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1753                         print "IDENT($1)\n" if ($dbg_values > 1);
1754                         $type = 'V';
1755
1756                 } elsif ($cur =~ /^($Assignment)/o) {
1757                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1758                         $type = 'N';
1759
1760                 } elsif ($cur =~/^(;|{|})/) {
1761                         print "END($1)\n" if ($dbg_values > 1);
1762                         $type = 'E';
1763                         $av_pend_colon = 'O';
1764
1765                 } elsif ($cur =~/^(,)/) {
1766                         print "COMMA($1)\n" if ($dbg_values > 1);
1767                         $type = 'C';
1768
1769                 } elsif ($cur =~ /^(\?)/o) {
1770                         print "QUESTION($1)\n" if ($dbg_values > 1);
1771                         $type = 'N';
1772
1773                 } elsif ($cur =~ /^(:)/o) {
1774                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1775
1776                         substr($var, length($res), 1, $av_pend_colon);
1777                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1778                                 $type = 'E';
1779                         } else {
1780                                 $type = 'N';
1781                         }
1782                         $av_pend_colon = 'O';
1783
1784                 } elsif ($cur =~ /^(\[)/o) {
1785                         print "CLOSE($1)\n" if ($dbg_values > 1);
1786                         $type = 'N';
1787
1788                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1789                         my $variant;
1790
1791                         print "OPV($1)\n" if ($dbg_values > 1);
1792                         if ($type eq 'V') {
1793                                 $variant = 'B';
1794                         } else {
1795                                 $variant = 'U';
1796                         }
1797
1798                         substr($var, length($res), 1, $variant);
1799                         $type = 'N';
1800
1801                 } elsif ($cur =~ /^($Operators)/o) {
1802                         print "OP($1)\n" if ($dbg_values > 1);
1803                         if ($1 ne '++' && $1 ne '--') {
1804                                 $type = 'N';
1805                         }
1806
1807                 } elsif ($cur =~ /(^.)/o) {
1808                         print "C($1)\n" if ($dbg_values > 1);
1809                 }
1810                 if (defined $1) {
1811                         $cur = substr($cur, length($1));
1812                         $res .= $type x length($1);
1813                 }
1814         }
1815
1816         return ($res, $var);
1817 }
1818
1819 sub possible {
1820         my ($possible, $line) = @_;
1821         my $notPermitted = qr{(?:
1822                 ^(?:
1823                         $Modifier|
1824                         $Storage|
1825                         $Type|
1826                         DEFINE_\S+
1827                 )$|
1828                 ^(?:
1829                         goto|
1830                         return|
1831                         case|
1832                         else|
1833                         asm|__asm__|
1834                         do|
1835                         \#|
1836                         \#\#|
1837                 )(?:\s|$)|
1838                 ^(?:typedef|struct|enum)\b
1839             )}x;
1840         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1841         if ($possible !~ $notPermitted) {
1842                 # Check for modifiers.
1843                 $possible =~ s/\s*$Storage\s*//g;
1844                 $possible =~ s/\s*$Sparse\s*//g;
1845                 if ($possible =~ /^\s*$/) {
1846
1847                 } elsif ($possible =~ /\s/) {
1848                         $possible =~ s/\s*$Type\s*//g;
1849                         for my $modifier (split(' ', $possible)) {
1850                                 if ($modifier !~ $notPermitted) {
1851                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1852                                         push(@modifierListFile, $modifier);
1853                                 }
1854                         }
1855
1856                 } else {
1857                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1858                         push(@typeListFile, $possible);
1859                 }
1860                 build_types();
1861         } else {
1862                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1863         }
1864 }
1865
1866 my $prefix = '';
1867
1868 sub show_type {
1869         my ($type) = @_;
1870
1871         $type =~ tr/[a-z]/[A-Z]/;
1872
1873         return defined $use_type{$type} if (scalar keys %use_type > 0);
1874
1875         return !defined $ignore_type{$type};
1876 }
1877
1878 sub report {
1879         my ($level, $type, $msg) = @_;
1880
1881         if (!show_type($type) ||
1882             (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1883                 return 0;
1884         }
1885         my $output = '';
1886         if (-t STDOUT && $color) {
1887                 if ($level eq 'ERROR') {
1888                         $output .= RED;
1889                 } elsif ($level eq 'WARNING') {
1890                         $output .= YELLOW;
1891                 } else {
1892                         $output .= GREEN;
1893                 }
1894         }
1895         $output .= $prefix . $level . ':';
1896         if ($show_types) {
1897                 $output .= BLUE if (-t STDOUT && $color);
1898                 $output .= "$type:";
1899         }
1900         $output .= RESET if (-t STDOUT && $color);
1901         $output .= ' ' . $msg . "\n";
1902
1903         if ($showfile) {
1904                 my @lines = split("\n", $output, -1);
1905                 splice(@lines, 1, 1);
1906                 $output = join("\n", @lines);
1907         }
1908         $output = (split('\n', $output))[0] . "\n" if ($terse);
1909
1910         push(our @report, $output);
1911
1912         return 1;
1913 }
1914
1915 sub report_dump {
1916         our @report;
1917 }
1918
1919 sub fixup_current_range {
1920         my ($lineRef, $offset, $length) = @_;
1921
1922         if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1923                 my $o = $1;
1924                 my $l = $2;
1925                 my $no = $o + $offset;
1926                 my $nl = $l + $length;
1927                 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1928         }
1929 }
1930
1931 sub fix_inserted_deleted_lines {
1932         my ($linesRef, $insertedRef, $deletedRef) = @_;
1933
1934         my $range_last_linenr = 0;
1935         my $delta_offset = 0;
1936
1937         my $old_linenr = 0;
1938         my $new_linenr = 0;
1939
1940         my $next_insert = 0;
1941         my $next_delete = 0;
1942
1943         my @lines = ();
1944
1945         my $inserted = @{$insertedRef}[$next_insert++];
1946         my $deleted = @{$deletedRef}[$next_delete++];
1947
1948         foreach my $old_line (@{$linesRef}) {
1949                 my $save_line = 1;
1950                 my $line = $old_line;   #don't modify the array
1951                 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) {      #new filename
1952                         $delta_offset = 0;
1953                 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) {    #new hunk
1954                         $range_last_linenr = $new_linenr;
1955                         fixup_current_range(\$line, $delta_offset, 0);
1956                 }
1957
1958                 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1959                         $deleted = @{$deletedRef}[$next_delete++];
1960                         $save_line = 0;
1961                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1962                 }
1963
1964                 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1965                         push(@lines, ${$inserted}{'LINE'});
1966                         $inserted = @{$insertedRef}[$next_insert++];
1967                         $new_linenr++;
1968                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1969                 }
1970
1971                 if ($save_line) {
1972                         push(@lines, $line);
1973                         $new_linenr++;
1974                 }
1975
1976                 $old_linenr++;
1977         }
1978
1979         return @lines;
1980 }
1981
1982 sub fix_insert_line {
1983         my ($linenr, $line) = @_;
1984
1985         my $inserted = {
1986                 LINENR => $linenr,
1987                 LINE => $line,
1988         };
1989         push(@fixed_inserted, $inserted);
1990 }
1991
1992 sub fix_delete_line {
1993         my ($linenr, $line) = @_;
1994
1995         my $deleted = {
1996                 LINENR => $linenr,
1997                 LINE => $line,
1998         };
1999
2000         push(@fixed_deleted, $deleted);
2001 }
2002
2003 sub ERROR {
2004         my ($type, $msg) = @_;
2005
2006         if (report("ERROR", $type, $msg)) {
2007                 our $clean = 0;
2008                 our $cnt_error++;
2009                 return 1;
2010         }
2011         return 0;
2012 }
2013 sub WARN {
2014         my ($type, $msg) = @_;
2015
2016         if (report("WARNING", $type, $msg)) {
2017                 our $clean = 0;
2018                 our $cnt_warn++;
2019                 return 1;
2020         }
2021         return 0;
2022 }
2023 sub CHK {
2024         my ($type, $msg) = @_;
2025
2026         if ($check && report("CHECK", $type, $msg)) {
2027                 our $clean = 0;
2028                 our $cnt_chk++;
2029                 return 1;
2030         }
2031         return 0;
2032 }
2033
2034 sub check_absolute_file {
2035         my ($absolute, $herecurr) = @_;
2036         my $file = $absolute;
2037
2038         ##print "absolute<$absolute>\n";
2039
2040         # See if any suffix of this path is a path within the tree.
2041         while ($file =~ s@^[^/]*/@@) {
2042                 if (-f "$root/$file") {
2043                         ##print "file<$file>\n";
2044                         last;
2045                 }
2046         }
2047         if (! -f _)  {
2048                 return 0;
2049         }
2050
2051         # It is, so see if the prefix is acceptable.
2052         my $prefix = $absolute;
2053         substr($prefix, -length($file)) = '';
2054
2055         ##print "prefix<$prefix>\n";
2056         if ($prefix ne ".../") {
2057                 WARN("USE_RELATIVE_PATH",
2058                      "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2059         }
2060 }
2061
2062 sub trim {
2063         my ($string) = @_;
2064
2065         $string =~ s/^\s+|\s+$//g;
2066
2067         return $string;
2068 }
2069
2070 sub ltrim {
2071         my ($string) = @_;
2072
2073         $string =~ s/^\s+//;
2074
2075         return $string;
2076 }
2077
2078 sub rtrim {
2079         my ($string) = @_;
2080
2081         $string =~ s/\s+$//;
2082
2083         return $string;
2084 }
2085
2086 sub string_find_replace {
2087         my ($string, $find, $replace) = @_;
2088
2089         $string =~ s/$find/$replace/g;
2090
2091         return $string;
2092 }
2093
2094 sub tabify {
2095         my ($leading) = @_;
2096
2097         my $source_indent = 8;
2098         my $max_spaces_before_tab = $source_indent - 1;
2099         my $spaces_to_tab = " " x $source_indent;
2100
2101         #convert leading spaces to tabs
2102         1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2103         #Remove spaces before a tab
2104         1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2105
2106         return "$leading";
2107 }
2108
2109 sub pos_last_openparen {
2110         my ($line) = @_;
2111
2112         my $pos = 0;
2113
2114         my $opens = $line =~ tr/\(/\(/;
2115         my $closes = $line =~ tr/\)/\)/;
2116
2117         my $last_openparen = 0;
2118
2119         if (($opens == 0) || ($closes >= $opens)) {
2120                 return -1;
2121         }
2122
2123         my $len = length($line);
2124
2125         for ($pos = 0; $pos < $len; $pos++) {
2126                 my $string = substr($line, $pos);
2127                 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2128                         $pos += length($1) - 1;
2129                 } elsif (substr($line, $pos, 1) eq '(') {
2130                         $last_openparen = $pos;
2131                 } elsif (index($string, '(') == -1) {
2132                         last;
2133                 }
2134         }
2135
2136         return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2137 }
2138
2139 sub process {
2140         my $filename = shift;
2141
2142         my $linenr=0;
2143         my $prevline="";
2144         my $prevrawline="";
2145         my $stashline="";
2146         my $stashrawline="";
2147
2148         my $length;
2149         my $indent;
2150         my $previndent=0;
2151         my $stashindent=0;
2152
2153         our $clean = 1;
2154         my $signoff = 0;
2155         my $is_patch = 0;
2156         my $in_header_lines = $file ? 0 : 1;
2157         my $in_commit_log = 0;          #Scanning lines before patch
2158         my $has_commit_log = 0;         #Encountered lines before patch
2159         my $commit_log_possible_stack_dump = 0;
2160         my $commit_log_long_line = 0;
2161         my $commit_log_has_diff = 0;
2162         my $reported_maintainer_file = 0;
2163         my $non_utf8_charset = 0;
2164
2165         my $last_blank_line = 0;
2166         my $last_coalesced_string_linenr = -1;
2167
2168         our @report = ();
2169         our $cnt_lines = 0;
2170         our $cnt_error = 0;
2171         our $cnt_warn = 0;
2172         our $cnt_chk = 0;
2173
2174         # Trace the real file/line as we go.
2175         my $realfile = '';
2176         my $realline = 0;
2177         my $realcnt = 0;
2178         my $here = '';
2179         my $context_function;           #undef'd unless there's a known function
2180         my $in_comment = 0;
2181         my $comment_edge = 0;
2182         my $first_line = 0;
2183         my $p1_prefix = '';
2184
2185         my $prev_values = 'E';
2186
2187         # suppression flags
2188         my %suppress_ifbraces;
2189         my %suppress_whiletrailers;
2190         my %suppress_export;
2191         my $suppress_statement = 0;
2192
2193         my %signatures = ();
2194
2195         # Pre-scan the patch sanitizing the lines.
2196         # Pre-scan the patch looking for any __setup documentation.
2197         #
2198         my @setup_docs = ();
2199         my $setup_docs = 0;
2200
2201         my $camelcase_file_seeded = 0;
2202
2203         sanitise_line_reset();
2204         my $line;
2205         foreach my $rawline (@rawlines) {
2206                 $linenr++;
2207                 $line = $rawline;
2208
2209                 push(@fixed, $rawline) if ($fix);
2210
2211                 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2212                         $setup_docs = 0;
2213                         if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2214                                 $setup_docs = 1;
2215                         }
2216                         #next;
2217                 }
2218                 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2219                         $realline=$1-1;
2220                         if (defined $2) {
2221                                 $realcnt=$3+1;
2222                         } else {
2223                                 $realcnt=1+1;
2224                         }
2225                         $in_comment = 0;
2226
2227                         # Guestimate if this is a continuing comment.  Run
2228                         # the context looking for a comment "edge".  If this
2229                         # edge is a close comment then we must be in a comment
2230                         # at context start.
2231                         my $edge;
2232                         my $cnt = $realcnt;
2233                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2234                                 next if (defined $rawlines[$ln - 1] &&
2235                                          $rawlines[$ln - 1] =~ /^-/);
2236                                 $cnt--;
2237                                 #print "RAW<$rawlines[$ln - 1]>\n";
2238                                 last if (!defined $rawlines[$ln - 1]);
2239                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2240                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2241                                         ($edge) = $1;
2242                                         last;
2243                                 }
2244                         }
2245                         if (defined $edge && $edge eq '*/') {
2246                                 $in_comment = 1;
2247                         }
2248
2249                         # Guestimate if this is a continuing comment.  If this
2250                         # is the start of a diff block and this line starts
2251                         # ' *' then it is very likely a comment.
2252                         if (!defined $edge &&
2253                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2254                         {
2255                                 $in_comment = 1;
2256                         }
2257
2258                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2259                         sanitise_line_reset($in_comment);
2260
2261                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2262                         # Standardise the strings and chars within the input to
2263                         # simplify matching -- only bother with positive lines.
2264                         $line = sanitise_line($rawline);
2265                 }
2266                 push(@lines, $line);
2267
2268                 if ($realcnt > 1) {
2269                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
2270                 } else {
2271                         $realcnt = 0;
2272                 }
2273
2274                 #print "==>$rawline\n";
2275                 #print "-->$line\n";
2276
2277                 if ($setup_docs && $line =~ /^\+/) {
2278                         push(@setup_docs, $line);
2279                 }
2280         }
2281
2282         $prefix = '';
2283
2284         $realcnt = 0;
2285         $linenr = 0;
2286         $fixlinenr = -1;
2287         foreach my $line (@lines) {
2288                 $linenr++;
2289                 $fixlinenr++;
2290                 my $sline = $line;      #copy of $line
2291                 $sline =~ s/$;/ /g;     #with comments as spaces
2292
2293                 my $rawline = $rawlines[$linenr - 1];
2294
2295 #extract the line range in the file after the patch is applied
2296                 if (!$in_commit_log &&
2297                     $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2298                         my $context = $4;
2299                         $is_patch = 1;
2300                         $first_line = $linenr + 1;
2301                         $realline=$1-1;
2302                         if (defined $2) {
2303                                 $realcnt=$3+1;
2304                         } else {
2305                                 $realcnt=1+1;
2306                         }
2307                         annotate_reset();
2308                         $prev_values = 'E';
2309
2310                         %suppress_ifbraces = ();
2311                         %suppress_whiletrailers = ();
2312                         %suppress_export = ();
2313                         $suppress_statement = 0;
2314                         if ($context =~ /\b(\w+)\s*\(/) {
2315                                 $context_function = $1;
2316                         } else {
2317                                 undef $context_function;
2318                         }
2319                         next;
2320
2321 # track the line number as we move through the hunk, note that
2322 # new versions of GNU diff omit the leading space on completely
2323 # blank context lines so we need to count that too.
2324                 } elsif ($line =~ /^( |\+|$)/) {
2325                         $realline++;
2326                         $realcnt-- if ($realcnt != 0);
2327
2328                         # Measure the line length and indent.
2329                         ($length, $indent) = line_stats($rawline);
2330
2331                         # Track the previous line.
2332                         ($prevline, $stashline) = ($stashline, $line);
2333                         ($previndent, $stashindent) = ($stashindent, $indent);
2334                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2335
2336                         #warn "line<$line>\n";
2337
2338                 } elsif ($realcnt == 1) {
2339                         $realcnt--;
2340                 }
2341
2342                 my $hunk_line = ($realcnt != 0);
2343
2344                 $here = "#$linenr: " if (!$file);
2345                 $here = "#$realline: " if ($file);
2346
2347                 my $found_file = 0;
2348                 # extract the filename as it passes
2349                 if ($line =~ /^diff --git.*?(\S+)$/) {
2350                         $realfile = $1;
2351                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2352                         $in_commit_log = 0;
2353                         $found_file = 1;
2354                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2355                         $realfile = $1;
2356                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2357                         $in_commit_log = 0;
2358
2359                         $p1_prefix = $1;
2360                         if (!$file && $tree && $p1_prefix ne '' &&
2361                             -e "$root/$p1_prefix") {
2362                                 WARN("PATCH_PREFIX",
2363                                      "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2364                         }
2365
2366                         if ($realfile =~ m@^include/asm/@) {
2367                                 ERROR("MODIFIED_INCLUDE_ASM",
2368                                       "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2369                         }
2370                         $found_file = 1;
2371                 }
2372
2373 #make up the handle for any error we report on this line
2374                 if ($showfile) {
2375                         $prefix = "$realfile:$realline: "
2376                 } elsif ($emacs) {
2377                         if ($file) {
2378                                 $prefix = "$filename:$realline: ";
2379                         } else {
2380                                 $prefix = "$filename:$linenr: ";
2381                         }
2382                 }
2383
2384                 if ($found_file) {
2385                         if (is_maintained_obsolete($realfile)) {
2386                                 WARN("OBSOLETE",
2387                                      "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy.  No unnecessary modifications please.\n");
2388                         }
2389                         if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2390                                 $check = 1;
2391                         } else {
2392                                 $check = $check_orig;
2393                         }
2394                         next;
2395                 }
2396
2397                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2398
2399                 my $hereline = "$here\n$rawline\n";
2400                 my $herecurr = "$here\n$rawline\n";
2401                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2402
2403                 $cnt_lines++ if ($realcnt != 0);
2404
2405 # Check if the commit log has what seems like a diff which can confuse patch
2406                 if ($in_commit_log && !$commit_log_has_diff &&
2407                     (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2408                       $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2409                      $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2410                      $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2411                         ERROR("DIFF_IN_COMMIT_MSG",
2412                               "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2413                         $commit_log_has_diff = 1;
2414                 }
2415
2416 # Check for incorrect file permissions
2417                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2418                         my $permhere = $here . "FILE: $realfile\n";
2419                         if ($realfile !~ m@scripts/@ &&
2420                             $realfile !~ /\.(py|pl|awk|sh)$/) {
2421                                 ERROR("EXECUTE_PERMISSIONS",
2422                                       "do not set execute permissions for source files\n" . $permhere);
2423                         }
2424                 }
2425
2426 # Check the patch for a signoff:
2427                 if ($line =~ /^\s*signed-off-by:/i) {
2428                         $signoff++;
2429                         $in_commit_log = 0;
2430                 }
2431
2432 # Check if MAINTAINERS is being updated.  If so, there's probably no need to
2433 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2434                 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2435                         $reported_maintainer_file = 1;
2436                 }
2437
2438 # Check signature styles
2439                 if (!$in_header_lines &&
2440                     $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2441                         my $space_before = $1;
2442                         my $sign_off = $2;
2443                         my $space_after = $3;
2444                         my $email = $4;
2445                         my $ucfirst_sign_off = ucfirst(lc($sign_off));
2446
2447                         if ($sign_off !~ /$signature_tags/) {
2448                                 WARN("BAD_SIGN_OFF",
2449                                      "Non-standard signature: $sign_off\n" . $herecurr);
2450                         }
2451                         if (defined $space_before && $space_before ne "") {
2452                                 if (WARN("BAD_SIGN_OFF",
2453                                          "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2454                                     $fix) {
2455                                         $fixed[$fixlinenr] =
2456                                             "$ucfirst_sign_off $email";
2457                                 }
2458                         }
2459                         if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2460                                 if (WARN("BAD_SIGN_OFF",
2461                                          "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2462                                     $fix) {
2463                                         $fixed[$fixlinenr] =
2464                                             "$ucfirst_sign_off $email";
2465                                 }
2466
2467                         }
2468                         if (!defined $space_after || $space_after ne " ") {
2469                                 if (WARN("BAD_SIGN_OFF",
2470                                          "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2471                                     $fix) {
2472                                         $fixed[$fixlinenr] =
2473                                             "$ucfirst_sign_off $email";
2474                                 }
2475                         }
2476
2477                         my ($email_name, $email_address, $comment) = parse_email($email);
2478                         my $suggested_email = format_email(($email_name, $email_address));
2479                         if ($suggested_email eq "") {
2480                                 ERROR("BAD_SIGN_OFF",
2481                                       "Unrecognized email address: '$email'\n" . $herecurr);
2482                         } else {
2483                                 my $dequoted = $suggested_email;
2484                                 $dequoted =~ s/^"//;
2485                                 $dequoted =~ s/" </ </;
2486                                 # Don't force email to have quotes
2487                                 # Allow just an angle bracketed address
2488                                 if ("$dequoted$comment" ne $email &&
2489                                     "<$email_address>$comment" ne $email &&
2490                                     "$suggested_email$comment" ne $email) {
2491                                         WARN("BAD_SIGN_OFF",
2492                                              "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2493                                 }
2494                         }
2495
2496 # Check for duplicate signatures
2497                         my $sig_nospace = $line;
2498                         $sig_nospace =~ s/\s//g;
2499                         $sig_nospace = lc($sig_nospace);
2500                         if (defined $signatures{$sig_nospace}) {
2501                                 WARN("BAD_SIGN_OFF",
2502                                      "Duplicate signature\n" . $herecurr);
2503                         } else {
2504                                 $signatures{$sig_nospace} = 1;
2505                         }
2506                 }
2507
2508 # Check email subject for common tools that don't need to be mentioned
2509                 if ($in_header_lines &&
2510                     $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2511                         WARN("EMAIL_SUBJECT",
2512                              "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2513                 }
2514
2515 # Check for old stable address
2516                 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2517                         ERROR("STABLE_ADDRESS",
2518                               "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2519                 }
2520
2521 # Check for unwanted Gerrit info
2522                 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2523                         ERROR("GERRIT_CHANGE_ID",
2524                               "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2525                 }
2526
2527 # Check if the commit log is in a possible stack dump
2528                 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2529                     ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2530                      $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2531                                         # timestamp
2532                      $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2533                                         # stack dump address
2534                         $commit_log_possible_stack_dump = 1;
2535                 }
2536
2537 # Check for line lengths > 75 in commit log, warn once
2538                 if ($in_commit_log && !$commit_log_long_line &&
2539                     length($line) > 75 &&
2540                     !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2541                                         # file delta changes
2542                       $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2543                                         # filename then :
2544                       $line =~ /^\s*(?:Fixes:|Link:)/i ||
2545                                         # A Fixes: or Link: line
2546                       $commit_log_possible_stack_dump)) {
2547                         WARN("COMMIT_LOG_LONG_LINE",
2548                              "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2549                         $commit_log_long_line = 1;
2550                 }
2551
2552 # Reset possible stack dump if a blank line is found
2553                 if ($in_commit_log && $commit_log_possible_stack_dump &&
2554                     $line =~ /^\s*$/) {
2555                         $commit_log_possible_stack_dump = 0;
2556                 }
2557
2558 # Check for git id commit length and improperly formed commit descriptions
2559                 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2560                     $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2561                     $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2562                     ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2563                      ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2564                       $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2565                       $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2566                         my $init_char = "c";
2567                         my $orig_commit = "";
2568                         my $short = 1;
2569                         my $long = 0;
2570                         my $case = 1;
2571                         my $space = 1;
2572                         my $hasdesc = 0;
2573                         my $hasparens = 0;
2574                         my $id = '0123456789ab';
2575                         my $orig_desc = "commit description";
2576                         my $description = "";
2577
2578                         if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2579                                 $init_char = $1;
2580                                 $orig_commit = lc($2);
2581                         } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2582                                 $orig_commit = lc($1);
2583                         }
2584
2585                         $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2586                         $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2587                         $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2588                         $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2589                         if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2590                                 $orig_desc = $1;
2591                                 $hasparens = 1;
2592                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2593                                  defined $rawlines[$linenr] &&
2594                                  $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2595                                 $orig_desc = $1;
2596                                 $hasparens = 1;
2597                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2598                                  defined $rawlines[$linenr] &&
2599                                  $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2600                                 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2601                                 $orig_desc = $1;
2602                                 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2603                                 $orig_desc .= " " . $1;
2604                                 $hasparens = 1;
2605                         }
2606
2607                         ($id, $description) = git_commit_info($orig_commit,
2608                                                               $id, $orig_desc);
2609
2610                         if (defined($id) &&
2611                            ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2612                                 ERROR("GIT_COMMIT_ID",
2613                                       "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2614                         }
2615                 }
2616
2617 # Check for added, moved or deleted files
2618                 if (!$reported_maintainer_file && !$in_commit_log &&
2619                     ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2620                      $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2621                      ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2622                       (defined($1) || defined($2))))) {
2623                         $is_patch = 1;
2624                         $reported_maintainer_file = 1;
2625                         WARN("FILE_PATH_CHANGES",
2626                              "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2627                 }
2628
2629 # Check for wrappage within a valid hunk of the file
2630                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2631                         ERROR("CORRUPTED_PATCH",
2632                               "patch seems to be corrupt (line wrapped?)\n" .
2633                                 $herecurr) if (!$emitted_corrupt++);
2634                 }
2635
2636 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2637                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2638                     $rawline !~ m/^$UTF8*$/) {
2639                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2640
2641                         my $blank = copy_spacing($rawline);
2642                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2643                         my $hereptr = "$hereline$ptr\n";
2644
2645                         CHK("INVALID_UTF8",
2646                             "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2647                 }
2648
2649 # Check if it's the start of a commit log
2650 # (not a header line and we haven't seen the patch filename)
2651                 if ($in_header_lines && $realfile =~ /^$/ &&
2652                     !($rawline =~ /^\s+(?:\S|$)/ ||
2653                       $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2654                         $in_header_lines = 0;
2655                         $in_commit_log = 1;
2656                         $has_commit_log = 1;
2657                 }
2658
2659 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2660 # declined it, i.e defined some charset where it is missing.
2661                 if ($in_header_lines &&
2662                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2663                     $1 !~ /utf-8/i) {
2664                         $non_utf8_charset = 1;
2665                 }
2666
2667                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2668                     $rawline =~ /$NON_ASCII_UTF8/) {
2669                         WARN("UTF8_BEFORE_PATCH",
2670                             "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2671                 }
2672
2673 # Check for absolute kernel paths in commit message
2674                 if ($tree && $in_commit_log) {
2675                         while ($line =~ m{(?:^|\s)(/\S*)}g) {
2676                                 my $file = $1;
2677
2678                                 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2679                                     check_absolute_file($1, $herecurr)) {
2680                                         #
2681                                 } else {
2682                                         check_absolute_file($file, $herecurr);
2683                                 }
2684                         }
2685                 }
2686
2687 # Check for various typo / spelling mistakes
2688                 if (defined($misspellings) &&
2689                     ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2690                         while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2691                                 my $typo = $1;
2692                                 my $typo_fix = $spelling_fix{lc($typo)};
2693                                 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2694                                 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2695                                 my $msg_type = \&WARN;
2696                                 $msg_type = \&CHK if ($file);
2697                                 if (&{$msg_type}("TYPO_SPELLING",
2698                                                  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2699                                     $fix) {
2700                                         $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2701                                 }
2702                         }
2703                 }
2704
2705 # ignore non-hunk lines and lines being removed
2706                 next if (!$hunk_line || $line =~ /^-/);
2707
2708 #trailing whitespace
2709                 if ($line =~ /^\+.*\015/) {
2710                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2711                         if (ERROR("DOS_LINE_ENDINGS",
2712                                   "DOS line endings\n" . $herevet) &&
2713                             $fix) {
2714                                 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2715                         }
2716                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2717                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2718                         if (ERROR("TRAILING_WHITESPACE",
2719                                   "trailing whitespace\n" . $herevet) &&
2720                             $fix) {
2721                                 $fixed[$fixlinenr] =~ s/\s+$//;
2722                         }
2723
2724                         $rpt_cleaners = 1;
2725                 }
2726
2727 # Check for FSF mailing addresses.
2728                 if ($rawline =~ /\bwrite to the Free/i ||
2729                     $rawline =~ /\b675\s+Mass\s+Ave/i ||
2730                     $rawline =~ /\b59\s+Temple\s+Pl/i ||
2731                     $rawline =~ /\b51\s+Franklin\s+St/i) {
2732                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2733                         my $msg_type = \&ERROR;
2734                         $msg_type = \&CHK if ($file);
2735                         &{$msg_type}("FSF_MAILING_ADDRESS",
2736                                      "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)
2737                 }
2738
2739 # check for Kconfig help text having a real description
2740 # Only applies when adding the entry originally, after that we do not have
2741 # sufficient context to determine whether it is indeed long enough.
2742                 if ($realfile =~ /Kconfig/ &&
2743                     $line =~ /^\+\s*config\s+/) {
2744                         my $length = 0;
2745                         my $cnt = $realcnt;
2746                         my $ln = $linenr + 1;
2747                         my $f;
2748                         my $is_start = 0;
2749                         my $is_end = 0;
2750                         for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2751                                 $f = $lines[$ln - 1];
2752                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2753                                 $is_end = $lines[$ln - 1] =~ /^\+/;
2754
2755                                 next if ($f =~ /^-/);
2756                                 last if (!$file && $f =~ /^\@\@/);
2757
2758                                 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2759                                         $is_start = 1;
2760                                 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2761                                         $length = -1;
2762                                 }
2763
2764                                 $f =~ s/^.//;
2765                                 $f =~ s/#.*//;
2766                                 $f =~ s/^\s+//;
2767                                 next if ($f =~ /^$/);
2768                                 if ($f =~ /^\s*config\s/) {
2769                                         $is_end = 1;
2770                                         last;
2771                                 }
2772                                 $length++;
2773                         }
2774                         if ($is_start && $is_end && $length < $min_conf_desc_length) {
2775                                 WARN("CONFIG_DESCRIPTION",
2776                                      "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2777                         }
2778                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2779                 }
2780
2781 # check for MAINTAINERS entries that don't have the right form
2782                 if ($realfile =~ /^MAINTAINERS$/ &&
2783                     $rawline =~ /^\+[A-Z]:/ &&
2784                     $rawline !~ /^\+[A-Z]:\t\S/) {
2785                         if (WARN("MAINTAINERS_STYLE",
2786                                  "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
2787                             $fix) {
2788                                 $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
2789                         }
2790                 }
2791
2792 # discourage the use of boolean for type definition attributes of Kconfig options
2793                 if ($realfile =~ /Kconfig/ &&
2794                     $line =~ /^\+\s*\bboolean\b/) {
2795                         WARN("CONFIG_TYPE_BOOLEAN",
2796                              "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2797                 }
2798
2799                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2800                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2801                         my $flag = $1;
2802                         my $replacement = {
2803                                 'EXTRA_AFLAGS' =>   'asflags-y',
2804                                 'EXTRA_CFLAGS' =>   'ccflags-y',
2805                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
2806                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
2807                         };
2808
2809                         WARN("DEPRECATED_VARIABLE",
2810                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2811                 }
2812
2813 # check for DT compatible documentation
2814                 if (defined $root &&
2815                         (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2816                          ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2817
2818                         my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2819
2820                         my $dt_path = $root . "/Documentation/devicetree/bindings/";
2821                         my $vp_file = $dt_path . "vendor-prefixes.txt";
2822
2823                         foreach my $compat (@compats) {
2824                                 my $compat2 = $compat;
2825                                 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2826                                 my $compat3 = $compat;
2827                                 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2828                                 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2829                                 if ( $? >> 8 ) {
2830                                         WARN("UNDOCUMENTED_DT_STRING",
2831                                              "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2832                                 }
2833
2834                                 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2835                                 my $vendor = $1;
2836                                 `grep -Eq "^$vendor\\b" $vp_file`;
2837                                 if ( $? >> 8 ) {
2838                                         WARN("UNDOCUMENTED_DT_STRING",
2839                                              "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2840                                 }
2841                         }
2842                 }
2843
2844 # check we are in a valid source file if not then ignore this hunk
2845                 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
2846
2847 # line length limit (with some exclusions)
2848 #
2849 # There are a few types of lines that may extend beyond $max_line_length:
2850 #       logging functions like pr_info that end in a string
2851 #       lines with a single string
2852 #       #defines that are a single string
2853 #
2854 # There are 3 different line length message types:
2855 # LONG_LINE_COMMENT     a comment starts before but extends beyond $max_linelength
2856 # LONG_LINE_STRING      a string starts before but extends beyond $max_line_length
2857 # LONG_LINE             all other lines longer than $max_line_length
2858 #
2859 # if LONG_LINE is ignored, the other 2 types are also ignored
2860 #
2861
2862                 if ($line =~ /^\+/ && $length > $max_line_length) {
2863                         my $msg_type = "LONG_LINE";
2864
2865                         # Check the allowed long line types first
2866
2867                         # logging functions that end in a string that starts
2868                         # before $max_line_length
2869                         if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2870                             length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2871                                 $msg_type = "";
2872
2873                         # lines with only strings (w/ possible termination)
2874                         # #defines with only strings
2875                         } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2876                                  $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
2877                                 $msg_type = "";
2878
2879                         # EFI_GUID is another special case
2880                         } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/) {
2881                                 $msg_type = "";
2882
2883                         # Otherwise set the alternate message types
2884
2885                         # a comment starts before $max_line_length
2886                         } elsif ($line =~ /($;[\s$;]*)$/ &&
2887                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2888                                 $msg_type = "LONG_LINE_COMMENT"
2889
2890                         # a quoted string starts before $max_line_length
2891                         } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
2892                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2893                                 $msg_type = "LONG_LINE_STRING"
2894                         }
2895
2896                         if ($msg_type ne "" &&
2897                             (show_type("LONG_LINE") || show_type($msg_type))) {
2898                                 WARN($msg_type,
2899                                      "line over $max_line_length characters\n" . $herecurr);
2900                         }
2901                 }
2902
2903 # check for adding lines without a newline.
2904                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2905                         WARN("MISSING_EOF_NEWLINE",
2906                              "adding a line without newline at end of file\n" . $herecurr);
2907                 }
2908
2909 # Blackfin: use hi/lo macros
2910                 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2911                         if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2912                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2913                                 ERROR("LO_MACRO",
2914                                       "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2915                         }
2916                         if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2917                                 my $herevet = "$here\n" . cat_vet($line) . "\n";
2918                                 ERROR("HI_MACRO",
2919                                       "use the HI() macro, not (... >> 16)\n" . $herevet);
2920                         }
2921                 }
2922
2923 # check we are in a valid source file C or perl if not then ignore this hunk
2924                 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2925
2926 # at the beginning of a line any tabs must come first and anything
2927 # more than 8 must use tabs.
2928                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2929                     $rawline =~ /^\+\s*        \s*/) {
2930                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2931                         $rpt_cleaners = 1;
2932                         if (ERROR("CODE_INDENT",
2933                                   "code indent should use tabs where possible\n" . $herevet) &&
2934                             $fix) {
2935                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2936                         }
2937                 }
2938
2939 # check for space before tabs.
2940                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2941                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2942                         if (WARN("SPACE_BEFORE_TAB",
2943                                 "please, no space before tabs\n" . $herevet) &&
2944                             $fix) {
2945                                 while ($fixed[$fixlinenr] =~
2946                                            s/(^\+.*) {8,8}\t/$1\t\t/) {}
2947                                 while ($fixed[$fixlinenr] =~
2948                                            s/(^\+.*) +\t/$1\t/) {}
2949                         }
2950                 }
2951
2952 # check for && or || at the start of a line
2953                 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2954                         CHK("LOGICAL_CONTINUATIONS",
2955                             "Logical continuations should be on the previous line\n" . $hereprev);
2956                 }
2957
2958 # check indentation starts on a tab stop
2959                 if ($^V && $^V ge 5.10.0 &&
2960                     $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$))/) {
2961                         my $indent = length($1);
2962                         if ($indent % 8) {
2963                                 if (WARN("TABSTOP",
2964                                          "Statements should start on a tabstop\n" . $herecurr) &&
2965                                     $fix) {
2966                                         $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
2967                                 }
2968                         }
2969                 }
2970
2971 # check multi-line statement indentation matches previous line
2972                 if ($^V && $^V ge 5.10.0 &&
2973                     $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2974                         $prevline =~ /^\+(\t*)(.*)$/;
2975                         my $oldindent = $1;
2976                         my $rest = $2;
2977
2978                         my $pos = pos_last_openparen($rest);
2979                         if ($pos >= 0) {
2980                                 $line =~ /^(\+| )([ \t]*)/;
2981                                 my $newindent = $2;
2982
2983                                 my $goodtabindent = $oldindent .
2984                                         "\t" x ($pos / 8) .
2985                                         " "  x ($pos % 8);
2986                                 my $goodspaceindent = $oldindent . " "  x $pos;
2987
2988                                 if ($newindent ne $goodtabindent &&
2989                                     $newindent ne $goodspaceindent) {
2990
2991                                         if (CHK("PARENTHESIS_ALIGNMENT",
2992                                                 "Alignment should match open parenthesis\n" . $hereprev) &&
2993                                             $fix && $line =~ /^\+/) {
2994                                                 $fixed[$fixlinenr] =~
2995                                                     s/^\+[ \t]*/\+$goodtabindent/;
2996                                         }
2997                                 }
2998                         }
2999                 }
3000
3001 # check for space after cast like "(int) foo" or "(struct foo) bar"
3002 # avoid checking a few false positives:
3003 #   "sizeof(<type>)" or "__alignof__(<type>)"
3004 #   function pointer declarations like "(*foo)(int) = bar;"
3005 #   structure definitions like "(struct foo) { 0 };"
3006 #   multiline macros that define functions
3007 #   known attributes or the __attribute__ keyword
3008                 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3009                     (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3010                         if (CHK("SPACING",
3011                                 "No space is necessary after a cast\n" . $herecurr) &&
3012                             $fix) {
3013                                 $fixed[$fixlinenr] =~
3014                                     s/(\(\s*$Type\s*\))[ \t]+/$1/;
3015                         }
3016                 }
3017
3018 # Block comment styles
3019 # Networking with an initial /*
3020                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3021                     $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3022                     $rawline =~ /^\+[ \t]*\*/ &&
3023                     $realline > 2) {
3024                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3025                              "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3026                 }
3027
3028 # Block comments use * on subsequent lines
3029                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3030                     $prevrawline =~ /^\+.*?\/\*/ &&             #starting /*
3031                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
3032                     $rawline =~ /^\+/ &&                        #line is new
3033                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
3034                         WARN("BLOCK_COMMENT_STYLE",
3035                              "Block comments use * on subsequent lines\n" . $hereprev);
3036                 }
3037
3038 # Block comments use */ on trailing lines
3039                 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
3040                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
3041                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
3042                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
3043                         WARN("BLOCK_COMMENT_STYLE",
3044                              "Block comments use a trailing */ on a separate line\n" . $herecurr);
3045                 }
3046
3047 # Block comment * alignment
3048                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3049                     $line =~ /^\+[ \t]*$;/ &&                   #leading comment
3050                     $rawline =~ /^\+[ \t]*\*/ &&                #leading *
3051                     (($prevrawline =~ /^\+.*?\/\*/ &&           #leading /*
3052                       $prevrawline !~ /\*\/[ \t]*$/) ||         #no trailing */
3053                      $prevrawline =~ /^\+[ \t]*\*/)) {          #leading *
3054                         my $oldindent;
3055                         $prevrawline =~ m@^\+([ \t]*/?)\*@;
3056                         if (defined($1)) {
3057                                 $oldindent = expand_tabs($1);
3058                         } else {
3059                                 $prevrawline =~ m@^\+(.*/?)\*@;
3060                                 $oldindent = expand_tabs($1);
3061                         }
3062                         $rawline =~ m@^\+([ \t]*)\*@;
3063                         my $newindent = $1;
3064                         $newindent = expand_tabs($newindent);
3065                         if (length($oldindent) ne length($newindent)) {
3066                                 WARN("BLOCK_COMMENT_STYLE",
3067                                      "Block comments should align the * on each line\n" . $hereprev);
3068                         }
3069                 }
3070
3071 # check for missing blank lines after struct/union declarations
3072 # with exceptions for various attributes and macros
3073                 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3074                     $line =~ /^\+/ &&
3075                     !($line =~ /^\+\s*$/ ||
3076                       $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3077                       $line =~ /^\+\s*MODULE_/i ||
3078                       $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3079                       $line =~ /^\+[a-z_]*init/ ||
3080                       $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3081                       $line =~ /^\+\s*DECLARE/ ||
3082                       $line =~ /^\+\s*__setup/)) {
3083                         if (CHK("LINE_SPACING",
3084                                 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3085                             $fix) {
3086                                 fix_insert_line($fixlinenr, "\+");
3087                         }
3088                 }
3089
3090 # check for multiple consecutive blank lines
3091                 if ($prevline =~ /^[\+ ]\s*$/ &&
3092                     $line =~ /^\+\s*$/ &&
3093                     $last_blank_line != ($linenr - 1)) {
3094                         if (CHK("LINE_SPACING",
3095                                 "Please don't use multiple blank lines\n" . $hereprev) &&
3096                             $fix) {
3097                                 fix_delete_line($fixlinenr, $rawline);
3098                         }
3099
3100                         $last_blank_line = $linenr;
3101                 }
3102
3103 # check for missing blank lines after declarations
3104                 if ($sline =~ /^\+\s+\S/ &&                     #Not at char 1
3105                         # actual declarations
3106                     ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3107                         # function pointer declarations
3108                      $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3109                         # foo bar; where foo is some local typedef or #define
3110                      $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3111                         # known declaration macros
3112                      $prevline =~ /^\+\s+$declaration_macros/) &&
3113                         # for "else if" which can look like "$Ident $Ident"
3114                     !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3115                         # other possible extensions of declaration lines
3116                       $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3117                         # not starting a section or a macro "\" extended line
3118                       $prevline =~ /(?:\{\s*|\\)$/) &&
3119                         # looks like a declaration
3120                     !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3121                         # function pointer declarations
3122                       $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3123                         # foo bar; where foo is some local typedef or #define
3124                       $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3125                         # known declaration macros
3126                       $sline =~ /^\+\s+$declaration_macros/ ||
3127                         # start of struct or union or enum
3128                       $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
3129                         # start or end of block or continuation of declaration
3130                       $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3131                         # bitfield continuation
3132                       $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3133                         # other possible extensions of declaration lines
3134                       $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3135                         # indentation of previous and current line are the same
3136                     (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3137                         if (WARN("LINE_SPACING",
3138                                  "Missing a blank line after declarations\n" . $hereprev) &&
3139                             $fix) {
3140                                 fix_insert_line($fixlinenr, "\+");
3141                         }
3142                 }
3143
3144 # check for spaces at the beginning of a line.
3145 # Exceptions:
3146 #  1) within comments
3147 #  2) indented preprocessor commands
3148 #  3) hanging labels
3149                 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
3150                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3151                         if (WARN("LEADING_SPACE",
3152                                  "please, no spaces at the start of a line\n" . $herevet) &&
3153                             $fix) {
3154                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3155                         }
3156                 }
3157
3158 # check we are in a valid C source file if not then ignore this hunk
3159                 next if ($realfile !~ /\.(h|c)$/);
3160
3161 # check if this appears to be the start function declaration, save the name
3162                 if ($sline =~ /^\+\{\s*$/ &&