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