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