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

Linking to existing account procedure

If you already have an account and want to add another login method you MUST first sign in with your existing account and then change URL to read https://review.openocd.org/login/?link to get to this page again but this time it'll work for linking. Thank you.

SSH host keys fingerprints

1024 SHA256:YKx8b7u5ZWdcbp7/4AeXNaqElP49m6QrwfXaqQGJAOk gerrit-code-review@openocd.zylin.com (DSA)
384 SHA256:jHIbSQa4REvwCFG4cq5LBlBLxmxSqelQPem/EXIrxjk gerrit-code-review@openocd.org (ECDSA)
521 SHA256:UAOPYkU9Fjtcao0Ul/Rrlnj/OsQvt+pgdYSZ4jOYdgs gerrit-code-review@openocd.org (ECDSA)
256 SHA256:A13M5QlnozFOvTllybRZH6vm7iSt0XLxbA48yfc2yfY gerrit-code-review@openocd.org (ECDSA)
256 SHA256:spYMBqEYoAOtK7yZBrcwE8ZpYt6b68Cfh9yEVetvbXg gerrit-code-review@openocd.org (ED25519)
+--[ED25519 256]--+
|=..              |
|+o..   .         |
|*.o   . .        |
|+B . . .         |
|Bo. = o S        |
|Oo.+ + =         |
|oB=.* = . o      |
| =+=.+   + E     |
|. .=o   . o      |
+----[SHA256]-----+
2048 SHA256:0Onrb7/PHjpo6iVZ7xQX2riKN83FJ3KGU0TvI0TaFG4 gerrit-code-review@openocd.zylin.com (RSA)