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