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