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