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