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