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