Debian Codegraph @

util/lint/checkpatch.pl

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