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