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

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)