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