target: Perform PROTECT sanity checks for WRITE_SAME
[linux/fpc-iii.git] / scripts / checkpatch.pl
blobf0bb6d60c07b182686ff203ca3c4fee90e954ab8
1 #!/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
8 use strict;
9 use POSIX;
10 use File::Basename;
11 use Cwd 'abs_path';
13 my $P = $0;
14 my $D = dirname(abs_path($P));
16 my $V = '0.32';
18 use Getopt::Long qw(:config no_auto_abbrev);
20 my $quiet = 0;
21 my $tree = 1;
22 my $chk_signoff = 1;
23 my $chk_patch = 1;
24 my $tst_only;
25 my $emacs = 0;
26 my $terse = 0;
27 my $file = 0;
28 my $check = 0;
29 my $check_orig = 0;
30 my $summary = 1;
31 my $mailback = 0;
32 my $summary_file = 0;
33 my $show_types = 0;
34 my $fix = 0;
35 my $fix_inplace = 0;
36 my $root;
37 my %debug;
38 my %camelcase = ();
39 my %use_type = ();
40 my @use = ();
41 my %ignore_type = ();
42 my @ignore = ();
43 my $help = 0;
44 my $configuration_file = ".checkpatch.conf";
45 my $max_line_length = 80;
46 my $ignore_perl_version = 0;
47 my $minimum_perl_version = 5.10.0;
48 my $min_conf_desc_length = 4;
49 my $spelling_file = "$D/spelling.txt";
51 sub help {
52 my ($exitcode) = @_;
54 print << "EOM";
55 Usage: $P [OPTION]... [FILE]...
56 Version: $V
58 Options:
59 -q, --quiet quiet
60 --no-tree run without a kernel tree
61 --no-signoff do not check for 'Signed-off-by' line
62 --patch treat FILE as patchfile (default)
63 --emacs emacs compile window format
64 --terse one line per report
65 -f, --file treat FILE as regular source file
66 --subjective, --strict enable more subjective tests
67 --types TYPE(,TYPE2...) show only these comma separated message types
68 --ignore TYPE(,TYPE2...) ignore various comma separated message types
69 --max-line-length=n set the maximum line length, if exceeded, warn
70 --min-conf-desc-length=n set the min description length, if shorter, warn
71 --show-types show the message "types" in the output
72 --root=PATH PATH to the kernel tree root
73 --no-summary suppress the per-file summary
74 --mailback only produce a report in case of warnings/errors
75 --summary-file include the filename in summary
76 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
77 'values', 'possible', 'type', and 'attr' (default
78 is all off)
79 --test-only=WORD report only warnings/errors containing WORD
80 literally
81 --fix EXPERIMENTAL - may create horrible results
82 If correctable single-line errors exist, create
83 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
84 with potential errors corrected to the preferred
85 checkpatch style
86 --fix-inplace EXPERIMENTAL - may create horrible results
87 Is the same as --fix, but overwrites the input
88 file. It's your fault if there's no backup or git
89 --ignore-perl-version override checking of perl version. expect
90 runtime errors.
91 -h, --help, --version display this help and exit
93 When FILE is - read standard input.
94 EOM
96 exit($exitcode);
99 my $conf = which_conf($configuration_file);
100 if (-f $conf) {
101 my @conf_args;
102 open(my $conffile, '<', "$conf")
103 or warn "$P: Can't find a readable $configuration_file file $!\n";
105 while (<$conffile>) {
106 my $line = $_;
108 $line =~ s/\s*\n?$//g;
109 $line =~ s/^\s*//g;
110 $line =~ s/\s+/ /g;
112 next if ($line =~ m/^\s*#/);
113 next if ($line =~ m/^\s*$/);
115 my @words = split(" ", $line);
116 foreach my $word (@words) {
117 last if ($word =~ m/^#/);
118 push (@conf_args, $word);
121 close($conffile);
122 unshift(@ARGV, @conf_args) if @conf_args;
125 GetOptions(
126 'q|quiet+' => \$quiet,
127 'tree!' => \$tree,
128 'signoff!' => \$chk_signoff,
129 'patch!' => \$chk_patch,
130 'emacs!' => \$emacs,
131 'terse!' => \$terse,
132 'f|file!' => \$file,
133 'subjective!' => \$check,
134 'strict!' => \$check,
135 'ignore=s' => \@ignore,
136 'types=s' => \@use,
137 'show-types!' => \$show_types,
138 'max-line-length=i' => \$max_line_length,
139 'min-conf-desc-length=i' => \$min_conf_desc_length,
140 'root=s' => \$root,
141 'summary!' => \$summary,
142 'mailback!' => \$mailback,
143 'summary-file!' => \$summary_file,
144 'fix!' => \$fix,
145 'fix-inplace!' => \$fix_inplace,
146 'ignore-perl-version!' => \$ignore_perl_version,
147 'debug=s' => \%debug,
148 'test-only=s' => \$tst_only,
149 'h|help' => \$help,
150 'version' => \$help
151 ) or help(1);
153 help(0) if ($help);
155 $fix = 1 if ($fix_inplace);
156 $check_orig = $check;
158 my $exit = 0;
160 if ($^V && $^V lt $minimum_perl_version) {
161 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
162 if (!$ignore_perl_version) {
163 exit(1);
167 if ($#ARGV < 0) {
168 print "$P: no input files\n";
169 exit(1);
172 sub hash_save_array_words {
173 my ($hashRef, $arrayRef) = @_;
175 my @array = split(/,/, join(',', @$arrayRef));
176 foreach my $word (@array) {
177 $word =~ s/\s*\n?$//g;
178 $word =~ s/^\s*//g;
179 $word =~ s/\s+/ /g;
180 $word =~ tr/[a-z]/[A-Z]/;
182 next if ($word =~ m/^\s*#/);
183 next if ($word =~ m/^\s*$/);
185 $hashRef->{$word}++;
189 sub hash_show_words {
190 my ($hashRef, $prefix) = @_;
192 if ($quiet == 0 && keys %$hashRef) {
193 print "NOTE: $prefix message types:";
194 foreach my $word (sort keys %$hashRef) {
195 print " $word";
197 print "\n\n";
201 hash_save_array_words(\%ignore_type, \@ignore);
202 hash_save_array_words(\%use_type, \@use);
204 my $dbg_values = 0;
205 my $dbg_possible = 0;
206 my $dbg_type = 0;
207 my $dbg_attr = 0;
208 for my $key (keys %debug) {
209 ## no critic
210 eval "\${dbg_$key} = '$debug{$key}';";
211 die "$@" if ($@);
214 my $rpt_cleaners = 0;
216 if ($terse) {
217 $emacs = 1;
218 $quiet++;
221 if ($tree) {
222 if (defined $root) {
223 if (!top_of_kernel_tree($root)) {
224 die "$P: $root: --root does not point at a valid tree\n";
226 } else {
227 if (top_of_kernel_tree('.')) {
228 $root = '.';
229 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
230 top_of_kernel_tree($1)) {
231 $root = $1;
235 if (!defined $root) {
236 print "Must be run from the top-level dir. of a kernel tree\n";
237 exit(2);
241 my $emitted_corrupt = 0;
243 our $Ident = qr{
244 [A-Za-z_][A-Za-z\d_]*
245 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
247 our $Storage = qr{extern|static|asmlinkage};
248 our $Sparse = qr{
249 __user|
250 __kernel|
251 __force|
252 __iomem|
253 __must_check|
254 __init_refok|
255 __kprobes|
256 __ref|
257 __rcu
259 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
260 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
261 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
262 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
263 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
265 # Notes to $Attribute:
266 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
267 our $Attribute = qr{
268 const|
269 __percpu|
270 __nocast|
271 __safe|
272 __bitwise__|
273 __packed__|
274 __packed2__|
275 __naked|
276 __maybe_unused|
277 __always_unused|
278 __noreturn|
279 __used|
280 __cold|
281 __noclone|
282 __deprecated|
283 __read_mostly|
284 __kprobes|
285 $InitAttribute|
286 ____cacheline_aligned|
287 ____cacheline_aligned_in_smp|
288 ____cacheline_internodealigned_in_smp|
289 __weak
291 our $Modifier;
292 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
293 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
294 our $Lval = qr{$Ident(?:$Member)*};
296 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
297 our $Binary = qr{(?i)0b[01]+$Int_type?};
298 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
299 our $Int = qr{[0-9]+$Int_type?};
300 our $Octal = qr{0[0-7]+$Int_type?};
301 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
302 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
303 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
304 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
305 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
306 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
307 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
308 our $Arithmetic = qr{\+|-|\*|\/|%};
309 our $Operators = qr{
310 <=|>=|==|!=|
311 =>|->|<<|>>|<|>|!|~|
312 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
315 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
317 our $NonptrType;
318 our $NonptrTypeMisordered;
319 our $NonptrTypeWithAttr;
320 our $Type;
321 our $TypeMisordered;
322 our $Declare;
323 our $DeclareMisordered;
325 our $NON_ASCII_UTF8 = qr{
326 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
327 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
328 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
329 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
330 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
331 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
332 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
335 our $UTF8 = qr{
336 [\x09\x0A\x0D\x20-\x7E] # ASCII
337 | $NON_ASCII_UTF8
340 our $typeTypedefs = qr{(?x:
341 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
342 atomic_t
345 our $logFunctions = qr{(?x:
346 printk(?:_ratelimited|_once|)|
347 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
348 WARN(?:_RATELIMIT|_ONCE|)|
349 panic|
350 MODULE_[A-Z_]+|
351 seq_vprintf|seq_printf|seq_puts
354 our $signature_tags = qr{(?xi:
355 Signed-off-by:|
356 Acked-by:|
357 Tested-by:|
358 Reviewed-by:|
359 Reported-by:|
360 Suggested-by:|
361 To:|
365 our @typeListMisordered = (
366 qr{char\s+(?:un)?signed},
367 qr{int\s+(?:(?:un)?signed\s+)?short\s},
368 qr{int\s+short(?:\s+(?:un)?signed)},
369 qr{short\s+int(?:\s+(?:un)?signed)},
370 qr{(?:un)?signed\s+int\s+short},
371 qr{short\s+(?:un)?signed},
372 qr{long\s+int\s+(?:un)?signed},
373 qr{int\s+long\s+(?:un)?signed},
374 qr{long\s+(?:un)?signed\s+int},
375 qr{int\s+(?:un)?signed\s+long},
376 qr{int\s+(?:un)?signed},
377 qr{int\s+long\s+long\s+(?:un)?signed},
378 qr{long\s+long\s+int\s+(?:un)?signed},
379 qr{long\s+long\s+(?:un)?signed\s+int},
380 qr{long\s+long\s+(?:un)?signed},
381 qr{long\s+(?:un)?signed},
384 our @typeList = (
385 qr{void},
386 qr{(?:(?:un)?signed\s+)?char},
387 qr{(?:(?:un)?signed\s+)?short\s+int},
388 qr{(?:(?:un)?signed\s+)?short},
389 qr{(?:(?:un)?signed\s+)?int},
390 qr{(?:(?:un)?signed\s+)?long\s+int},
391 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
392 qr{(?:(?:un)?signed\s+)?long\s+long},
393 qr{(?:(?:un)?signed\s+)?long},
394 qr{(?:un)?signed},
395 qr{float},
396 qr{double},
397 qr{bool},
398 qr{struct\s+$Ident},
399 qr{union\s+$Ident},
400 qr{enum\s+$Ident},
401 qr{${Ident}_t},
402 qr{${Ident}_handler},
403 qr{${Ident}_handler_fn},
404 @typeListMisordered,
406 our @typeListWithAttr = (
407 @typeList,
408 qr{struct\s+$InitAttribute\s+$Ident},
409 qr{union\s+$InitAttribute\s+$Ident},
412 our @modifierList = (
413 qr{fastcall},
416 our @mode_permission_funcs = (
417 ["module_param", 3],
418 ["module_param_(?:array|named|string)", 4],
419 ["module_param_array_named", 5],
420 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
421 ["proc_create(?:_data|)", 2],
422 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
425 #Create a search pattern for all these functions to speed up a loop below
426 our $mode_perms_search = "";
427 foreach my $entry (@mode_permission_funcs) {
428 $mode_perms_search .= '|' if ($mode_perms_search ne "");
429 $mode_perms_search .= $entry->[0];
432 our $allowed_asm_includes = qr{(?x:
433 irq|
434 memory|
435 time|
436 reboot
438 # memory.h: ARM has a custom one
440 # Load common spelling mistakes and build regular expression list.
441 my $misspellings;
442 my %spelling_fix;
444 if (open(my $spelling, '<', $spelling_file)) {
445 my @spelling_list;
446 while (<$spelling>) {
447 my $line = $_;
449 $line =~ s/\s*\n?$//g;
450 $line =~ s/^\s*//g;
452 next if ($line =~ m/^\s*#/);
453 next if ($line =~ m/^\s*$/);
455 my ($suspect, $fix) = split(/\|\|/, $line);
457 push(@spelling_list, $suspect);
458 $spelling_fix{$suspect} = $fix;
460 close($spelling);
461 $misspellings = join("|", @spelling_list);
462 } else {
463 warn "No typos will be found - file '$spelling_file': $!\n";
466 sub build_types {
467 my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)";
468 my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)";
469 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
470 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
471 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
472 $NonptrType = qr{
473 (?:$Modifier\s+|const\s+)*
475 (?:typeof|__typeof__)\s*\([^\)]*\)|
476 (?:$typeTypedefs\b)|
477 (?:${all}\b)
479 (?:\s+$Modifier|\s+const)*
481 $NonptrTypeMisordered = qr{
482 (?:$Modifier\s+|const\s+)*
484 (?:${Misordered}\b)
486 (?:\s+$Modifier|\s+const)*
488 $NonptrTypeWithAttr = qr{
489 (?:$Modifier\s+|const\s+)*
491 (?:typeof|__typeof__)\s*\([^\)]*\)|
492 (?:$typeTypedefs\b)|
493 (?:${allWithAttr}\b)
495 (?:\s+$Modifier|\s+const)*
497 $Type = qr{
498 $NonptrType
499 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
500 (?:\s+$Inline|\s+$Modifier)*
502 $TypeMisordered = qr{
503 $NonptrTypeMisordered
504 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
505 (?:\s+$Inline|\s+$Modifier)*
507 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
508 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
510 build_types();
512 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
514 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
515 # requires at least perl version v5.10.0
516 # Any use must be runtime checked with $^V
518 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
519 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
520 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant)};
522 our $declaration_macros = qr{(?x:
523 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,2}\s*\(|
524 (?:$Storage\s+)?LIST_HEAD\s*\(|
525 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
528 sub deparenthesize {
529 my ($string) = @_;
530 return "" if (!defined($string));
532 while ($string =~ /^\s*\(.*\)\s*$/) {
533 $string =~ s@^\s*\(\s*@@;
534 $string =~ s@\s*\)\s*$@@;
537 $string =~ s@\s+@ @g;
539 return $string;
542 sub seed_camelcase_file {
543 my ($file) = @_;
545 return if (!(-f $file));
547 local $/;
549 open(my $include_file, '<', "$file")
550 or warn "$P: Can't read '$file' $!\n";
551 my $text = <$include_file>;
552 close($include_file);
554 my @lines = split('\n', $text);
556 foreach my $line (@lines) {
557 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
558 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
559 $camelcase{$1} = 1;
560 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
561 $camelcase{$1} = 1;
562 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
563 $camelcase{$1} = 1;
568 my $camelcase_seeded = 0;
569 sub seed_camelcase_includes {
570 return if ($camelcase_seeded);
572 my $files;
573 my $camelcase_cache = "";
574 my @include_files = ();
576 $camelcase_seeded = 1;
578 if (-e ".git") {
579 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
580 chomp $git_last_include_commit;
581 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
582 } else {
583 my $last_mod_date = 0;
584 $files = `find $root/include -name "*.h"`;
585 @include_files = split('\n', $files);
586 foreach my $file (@include_files) {
587 my $date = POSIX::strftime("%Y%m%d%H%M",
588 localtime((stat $file)[9]));
589 $last_mod_date = $date if ($last_mod_date < $date);
591 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
594 if ($camelcase_cache ne "" && -f $camelcase_cache) {
595 open(my $camelcase_file, '<', "$camelcase_cache")
596 or warn "$P: Can't read '$camelcase_cache' $!\n";
597 while (<$camelcase_file>) {
598 chomp;
599 $camelcase{$_} = 1;
601 close($camelcase_file);
603 return;
606 if (-e ".git") {
607 $files = `git ls-files "include/*.h"`;
608 @include_files = split('\n', $files);
611 foreach my $file (@include_files) {
612 seed_camelcase_file($file);
615 if ($camelcase_cache ne "") {
616 unlink glob ".checkpatch-camelcase.*";
617 open(my $camelcase_file, '>', "$camelcase_cache")
618 or warn "$P: Can't write '$camelcase_cache' $!\n";
619 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
620 print $camelcase_file ("$_\n");
622 close($camelcase_file);
626 sub git_commit_info {
627 my ($commit, $id, $desc) = @_;
629 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
631 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
632 $output =~ s/^\s*//gm;
633 my @lines = split("\n", $output);
635 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
636 # Maybe one day convert this block of bash into something that returns
637 # all matching commit ids, but it's very slow...
639 # echo "checking commits $1..."
640 # git rev-list --remotes | grep -i "^$1" |
641 # while read line ; do
642 # git log --format='%H %s' -1 $line |
643 # echo "commit $(cut -c 1-12,41-)"
644 # done
645 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
646 } else {
647 $id = substr($lines[0], 0, 12);
648 $desc = substr($lines[0], 41);
651 return ($id, $desc);
654 $chk_signoff = 0 if ($file);
656 my @rawlines = ();
657 my @lines = ();
658 my @fixed = ();
659 my @fixed_inserted = ();
660 my @fixed_deleted = ();
661 my $fixlinenr = -1;
663 my $vname;
664 for my $filename (@ARGV) {
665 my $FILE;
666 if ($file) {
667 open($FILE, '-|', "diff -u /dev/null $filename") ||
668 die "$P: $filename: diff failed - $!\n";
669 } elsif ($filename eq '-') {
670 open($FILE, '<&STDIN');
671 } else {
672 open($FILE, '<', "$filename") ||
673 die "$P: $filename: open failed - $!\n";
675 if ($filename eq '-') {
676 $vname = 'Your patch';
677 } else {
678 $vname = $filename;
680 while (<$FILE>) {
681 chomp;
682 push(@rawlines, $_);
684 close($FILE);
685 if (!process($filename)) {
686 $exit = 1;
688 @rawlines = ();
689 @lines = ();
690 @fixed = ();
691 @fixed_inserted = ();
692 @fixed_deleted = ();
693 $fixlinenr = -1;
696 exit($exit);
698 sub top_of_kernel_tree {
699 my ($root) = @_;
701 my @tree_check = (
702 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
703 "README", "Documentation", "arch", "include", "drivers",
704 "fs", "init", "ipc", "kernel", "lib", "scripts",
707 foreach my $check (@tree_check) {
708 if (! -e $root . '/' . $check) {
709 return 0;
712 return 1;
715 sub parse_email {
716 my ($formatted_email) = @_;
718 my $name = "";
719 my $address = "";
720 my $comment = "";
722 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
723 $name = $1;
724 $address = $2;
725 $comment = $3 if defined $3;
726 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
727 $address = $1;
728 $comment = $2 if defined $2;
729 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
730 $address = $1;
731 $comment = $2 if defined $2;
732 $formatted_email =~ s/$address.*$//;
733 $name = $formatted_email;
734 $name = trim($name);
735 $name =~ s/^\"|\"$//g;
736 # If there's a name left after stripping spaces and
737 # leading quotes, and the address doesn't have both
738 # leading and trailing angle brackets, the address
739 # is invalid. ie:
740 # "joe smith joe@smith.com" bad
741 # "joe smith <joe@smith.com" bad
742 if ($name ne "" && $address !~ /^<[^>]+>$/) {
743 $name = "";
744 $address = "";
745 $comment = "";
749 $name = trim($name);
750 $name =~ s/^\"|\"$//g;
751 $address = trim($address);
752 $address =~ s/^\<|\>$//g;
754 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
755 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
756 $name = "\"$name\"";
759 return ($name, $address, $comment);
762 sub format_email {
763 my ($name, $address) = @_;
765 my $formatted_email;
767 $name = trim($name);
768 $name =~ s/^\"|\"$//g;
769 $address = trim($address);
771 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
772 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
773 $name = "\"$name\"";
776 if ("$name" eq "") {
777 $formatted_email = "$address";
778 } else {
779 $formatted_email = "$name <$address>";
782 return $formatted_email;
785 sub which {
786 my ($bin) = @_;
788 foreach my $path (split(/:/, $ENV{PATH})) {
789 if (-e "$path/$bin") {
790 return "$path/$bin";
794 return "";
797 sub which_conf {
798 my ($conf) = @_;
800 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
801 if (-e "$path/$conf") {
802 return "$path/$conf";
806 return "";
809 sub expand_tabs {
810 my ($str) = @_;
812 my $res = '';
813 my $n = 0;
814 for my $c (split(//, $str)) {
815 if ($c eq "\t") {
816 $res .= ' ';
817 $n++;
818 for (; ($n % 8) != 0; $n++) {
819 $res .= ' ';
821 next;
823 $res .= $c;
824 $n++;
827 return $res;
829 sub copy_spacing {
830 (my $res = shift) =~ tr/\t/ /c;
831 return $res;
834 sub line_stats {
835 my ($line) = @_;
837 # Drop the diff line leader and expand tabs
838 $line =~ s/^.//;
839 $line = expand_tabs($line);
841 # Pick the indent from the front of the line.
842 my ($white) = ($line =~ /^(\s*)/);
844 return (length($line), length($white));
847 my $sanitise_quote = '';
849 sub sanitise_line_reset {
850 my ($in_comment) = @_;
852 if ($in_comment) {
853 $sanitise_quote = '*/';
854 } else {
855 $sanitise_quote = '';
858 sub sanitise_line {
859 my ($line) = @_;
861 my $res = '';
862 my $l = '';
864 my $qlen = 0;
865 my $off = 0;
866 my $c;
868 # Always copy over the diff marker.
869 $res = substr($line, 0, 1);
871 for ($off = 1; $off < length($line); $off++) {
872 $c = substr($line, $off, 1);
874 # Comments we are wacking completly including the begin
875 # and end, all to $;.
876 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
877 $sanitise_quote = '*/';
879 substr($res, $off, 2, "$;$;");
880 $off++;
881 next;
883 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
884 $sanitise_quote = '';
885 substr($res, $off, 2, "$;$;");
886 $off++;
887 next;
889 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
890 $sanitise_quote = '//';
892 substr($res, $off, 2, $sanitise_quote);
893 $off++;
894 next;
897 # A \ in a string means ignore the next character.
898 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
899 $c eq "\\") {
900 substr($res, $off, 2, 'XX');
901 $off++;
902 next;
904 # Regular quotes.
905 if ($c eq "'" || $c eq '"') {
906 if ($sanitise_quote eq '') {
907 $sanitise_quote = $c;
909 substr($res, $off, 1, $c);
910 next;
911 } elsif ($sanitise_quote eq $c) {
912 $sanitise_quote = '';
916 #print "c<$c> SQ<$sanitise_quote>\n";
917 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
918 substr($res, $off, 1, $;);
919 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
920 substr($res, $off, 1, $;);
921 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
922 substr($res, $off, 1, 'X');
923 } else {
924 substr($res, $off, 1, $c);
928 if ($sanitise_quote eq '//') {
929 $sanitise_quote = '';
932 # The pathname on a #include may be surrounded by '<' and '>'.
933 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
934 my $clean = 'X' x length($1);
935 $res =~ s@\<.*\>@<$clean>@;
937 # The whole of a #error is a string.
938 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
939 my $clean = 'X' x length($1);
940 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
943 return $res;
946 sub get_quoted_string {
947 my ($line, $rawline) = @_;
949 return "" if ($line !~ m/(\"[X\t]+\")/g);
950 return substr($rawline, $-[0], $+[0] - $-[0]);
953 sub ctx_statement_block {
954 my ($linenr, $remain, $off) = @_;
955 my $line = $linenr - 1;
956 my $blk = '';
957 my $soff = $off;
958 my $coff = $off - 1;
959 my $coff_set = 0;
961 my $loff = 0;
963 my $type = '';
964 my $level = 0;
965 my @stack = ();
966 my $p;
967 my $c;
968 my $len = 0;
970 my $remainder;
971 while (1) {
972 @stack = (['', 0]) if ($#stack == -1);
974 #warn "CSB: blk<$blk> remain<$remain>\n";
975 # If we are about to drop off the end, pull in more
976 # context.
977 if ($off >= $len) {
978 for (; $remain > 0; $line++) {
979 last if (!defined $lines[$line]);
980 next if ($lines[$line] =~ /^-/);
981 $remain--;
982 $loff = $len;
983 $blk .= $lines[$line] . "\n";
984 $len = length($blk);
985 $line++;
986 last;
988 # Bail if there is no further context.
989 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
990 if ($off >= $len) {
991 last;
993 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
994 $level++;
995 $type = '#';
998 $p = $c;
999 $c = substr($blk, $off, 1);
1000 $remainder = substr($blk, $off);
1002 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1004 # Handle nested #if/#else.
1005 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1006 push(@stack, [ $type, $level ]);
1007 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1008 ($type, $level) = @{$stack[$#stack - 1]};
1009 } elsif ($remainder =~ /^#\s*endif\b/) {
1010 ($type, $level) = @{pop(@stack)};
1013 # Statement ends at the ';' or a close '}' at the
1014 # outermost level.
1015 if ($level == 0 && $c eq ';') {
1016 last;
1019 # An else is really a conditional as long as its not else if
1020 if ($level == 0 && $coff_set == 0 &&
1021 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1022 $remainder =~ /^(else)(?:\s|{)/ &&
1023 $remainder !~ /^else\s+if\b/) {
1024 $coff = $off + length($1) - 1;
1025 $coff_set = 1;
1026 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1027 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1030 if (($type eq '' || $type eq '(') && $c eq '(') {
1031 $level++;
1032 $type = '(';
1034 if ($type eq '(' && $c eq ')') {
1035 $level--;
1036 $type = ($level != 0)? '(' : '';
1038 if ($level == 0 && $coff < $soff) {
1039 $coff = $off;
1040 $coff_set = 1;
1041 #warn "CSB: mark coff<$coff>\n";
1044 if (($type eq '' || $type eq '{') && $c eq '{') {
1045 $level++;
1046 $type = '{';
1048 if ($type eq '{' && $c eq '}') {
1049 $level--;
1050 $type = ($level != 0)? '{' : '';
1052 if ($level == 0) {
1053 if (substr($blk, $off + 1, 1) eq ';') {
1054 $off++;
1056 last;
1059 # Preprocessor commands end at the newline unless escaped.
1060 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1061 $level--;
1062 $type = '';
1063 $off++;
1064 last;
1066 $off++;
1068 # We are truly at the end, so shuffle to the next line.
1069 if ($off == $len) {
1070 $loff = $len + 1;
1071 $line++;
1072 $remain--;
1075 my $statement = substr($blk, $soff, $off - $soff + 1);
1076 my $condition = substr($blk, $soff, $coff - $soff + 1);
1078 #warn "STATEMENT<$statement>\n";
1079 #warn "CONDITION<$condition>\n";
1081 #print "coff<$coff> soff<$off> loff<$loff>\n";
1083 return ($statement, $condition,
1084 $line, $remain + 1, $off - $loff + 1, $level);
1087 sub statement_lines {
1088 my ($stmt) = @_;
1090 # Strip the diff line prefixes and rip blank lines at start and end.
1091 $stmt =~ s/(^|\n)./$1/g;
1092 $stmt =~ s/^\s*//;
1093 $stmt =~ s/\s*$//;
1095 my @stmt_lines = ($stmt =~ /\n/g);
1097 return $#stmt_lines + 2;
1100 sub statement_rawlines {
1101 my ($stmt) = @_;
1103 my @stmt_lines = ($stmt =~ /\n/g);
1105 return $#stmt_lines + 2;
1108 sub statement_block_size {
1109 my ($stmt) = @_;
1111 $stmt =~ s/(^|\n)./$1/g;
1112 $stmt =~ s/^\s*{//;
1113 $stmt =~ s/}\s*$//;
1114 $stmt =~ s/^\s*//;
1115 $stmt =~ s/\s*$//;
1117 my @stmt_lines = ($stmt =~ /\n/g);
1118 my @stmt_statements = ($stmt =~ /;/g);
1120 my $stmt_lines = $#stmt_lines + 2;
1121 my $stmt_statements = $#stmt_statements + 1;
1123 if ($stmt_lines > $stmt_statements) {
1124 return $stmt_lines;
1125 } else {
1126 return $stmt_statements;
1130 sub ctx_statement_full {
1131 my ($linenr, $remain, $off) = @_;
1132 my ($statement, $condition, $level);
1134 my (@chunks);
1136 # Grab the first conditional/block pair.
1137 ($statement, $condition, $linenr, $remain, $off, $level) =
1138 ctx_statement_block($linenr, $remain, $off);
1139 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1140 push(@chunks, [ $condition, $statement ]);
1141 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1142 return ($level, $linenr, @chunks);
1145 # Pull in the following conditional/block pairs and see if they
1146 # could continue the statement.
1147 for (;;) {
1148 ($statement, $condition, $linenr, $remain, $off, $level) =
1149 ctx_statement_block($linenr, $remain, $off);
1150 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1151 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1152 #print "C: push\n";
1153 push(@chunks, [ $condition, $statement ]);
1156 return ($level, $linenr, @chunks);
1159 sub ctx_block_get {
1160 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1161 my $line;
1162 my $start = $linenr - 1;
1163 my $blk = '';
1164 my @o;
1165 my @c;
1166 my @res = ();
1168 my $level = 0;
1169 my @stack = ($level);
1170 for ($line = $start; $remain > 0; $line++) {
1171 next if ($rawlines[$line] =~ /^-/);
1172 $remain--;
1174 $blk .= $rawlines[$line];
1176 # Handle nested #if/#else.
1177 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1178 push(@stack, $level);
1179 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1180 $level = $stack[$#stack - 1];
1181 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1182 $level = pop(@stack);
1185 foreach my $c (split(//, $lines[$line])) {
1186 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1187 if ($off > 0) {
1188 $off--;
1189 next;
1192 if ($c eq $close && $level > 0) {
1193 $level--;
1194 last if ($level == 0);
1195 } elsif ($c eq $open) {
1196 $level++;
1200 if (!$outer || $level <= 1) {
1201 push(@res, $rawlines[$line]);
1204 last if ($level == 0);
1207 return ($level, @res);
1209 sub ctx_block_outer {
1210 my ($linenr, $remain) = @_;
1212 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1213 return @r;
1215 sub ctx_block {
1216 my ($linenr, $remain) = @_;
1218 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1219 return @r;
1221 sub ctx_statement {
1222 my ($linenr, $remain, $off) = @_;
1224 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1225 return @r;
1227 sub ctx_block_level {
1228 my ($linenr, $remain) = @_;
1230 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1232 sub ctx_statement_level {
1233 my ($linenr, $remain, $off) = @_;
1235 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1238 sub ctx_locate_comment {
1239 my ($first_line, $end_line) = @_;
1241 # Catch a comment on the end of the line itself.
1242 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1243 return $current_comment if (defined $current_comment);
1245 # Look through the context and try and figure out if there is a
1246 # comment.
1247 my $in_comment = 0;
1248 $current_comment = '';
1249 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1250 my $line = $rawlines[$linenr - 1];
1251 #warn " $line\n";
1252 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1253 $in_comment = 1;
1255 if ($line =~ m@/\*@) {
1256 $in_comment = 1;
1258 if (!$in_comment && $current_comment ne '') {
1259 $current_comment = '';
1261 $current_comment .= $line . "\n" if ($in_comment);
1262 if ($line =~ m@\*/@) {
1263 $in_comment = 0;
1267 chomp($current_comment);
1268 return($current_comment);
1270 sub ctx_has_comment {
1271 my ($first_line, $end_line) = @_;
1272 my $cmt = ctx_locate_comment($first_line, $end_line);
1274 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1275 ##print "CMMT: $cmt\n";
1277 return ($cmt ne '');
1280 sub raw_line {
1281 my ($linenr, $cnt) = @_;
1283 my $offset = $linenr - 1;
1284 $cnt++;
1286 my $line;
1287 while ($cnt) {
1288 $line = $rawlines[$offset++];
1289 next if (defined($line) && $line =~ /^-/);
1290 $cnt--;
1293 return $line;
1296 sub cat_vet {
1297 my ($vet) = @_;
1298 my ($res, $coded);
1300 $res = '';
1301 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1302 $res .= $1;
1303 if ($2 ne '') {
1304 $coded = sprintf("^%c", unpack('C', $2) + 64);
1305 $res .= $coded;
1308 $res =~ s/$/\$/;
1310 return $res;
1313 my $av_preprocessor = 0;
1314 my $av_pending;
1315 my @av_paren_type;
1316 my $av_pend_colon;
1318 sub annotate_reset {
1319 $av_preprocessor = 0;
1320 $av_pending = '_';
1321 @av_paren_type = ('E');
1322 $av_pend_colon = 'O';
1325 sub annotate_values {
1326 my ($stream, $type) = @_;
1328 my $res;
1329 my $var = '_' x length($stream);
1330 my $cur = $stream;
1332 print "$stream\n" if ($dbg_values > 1);
1334 while (length($cur)) {
1335 @av_paren_type = ('E') if ($#av_paren_type < 0);
1336 print " <" . join('', @av_paren_type) .
1337 "> <$type> <$av_pending>" if ($dbg_values > 1);
1338 if ($cur =~ /^(\s+)/o) {
1339 print "WS($1)\n" if ($dbg_values > 1);
1340 if ($1 =~ /\n/ && $av_preprocessor) {
1341 $type = pop(@av_paren_type);
1342 $av_preprocessor = 0;
1345 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1346 print "CAST($1)\n" if ($dbg_values > 1);
1347 push(@av_paren_type, $type);
1348 $type = 'c';
1350 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1351 print "DECLARE($1)\n" if ($dbg_values > 1);
1352 $type = 'T';
1354 } elsif ($cur =~ /^($Modifier)\s*/) {
1355 print "MODIFIER($1)\n" if ($dbg_values > 1);
1356 $type = 'T';
1358 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1359 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1360 $av_preprocessor = 1;
1361 push(@av_paren_type, $type);
1362 if ($2 ne '') {
1363 $av_pending = 'N';
1365 $type = 'E';
1367 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1368 print "UNDEF($1)\n" if ($dbg_values > 1);
1369 $av_preprocessor = 1;
1370 push(@av_paren_type, $type);
1372 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1373 print "PRE_START($1)\n" if ($dbg_values > 1);
1374 $av_preprocessor = 1;
1376 push(@av_paren_type, $type);
1377 push(@av_paren_type, $type);
1378 $type = 'E';
1380 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1381 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1382 $av_preprocessor = 1;
1384 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1386 $type = 'E';
1388 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1389 print "PRE_END($1)\n" if ($dbg_values > 1);
1391 $av_preprocessor = 1;
1393 # Assume all arms of the conditional end as this
1394 # one does, and continue as if the #endif was not here.
1395 pop(@av_paren_type);
1396 push(@av_paren_type, $type);
1397 $type = 'E';
1399 } elsif ($cur =~ /^(\\\n)/o) {
1400 print "PRECONT($1)\n" if ($dbg_values > 1);
1402 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1403 print "ATTR($1)\n" if ($dbg_values > 1);
1404 $av_pending = $type;
1405 $type = 'N';
1407 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1408 print "SIZEOF($1)\n" if ($dbg_values > 1);
1409 if (defined $2) {
1410 $av_pending = 'V';
1412 $type = 'N';
1414 } elsif ($cur =~ /^(if|while|for)\b/o) {
1415 print "COND($1)\n" if ($dbg_values > 1);
1416 $av_pending = 'E';
1417 $type = 'N';
1419 } elsif ($cur =~/^(case)/o) {
1420 print "CASE($1)\n" if ($dbg_values > 1);
1421 $av_pend_colon = 'C';
1422 $type = 'N';
1424 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1425 print "KEYWORD($1)\n" if ($dbg_values > 1);
1426 $type = 'N';
1428 } elsif ($cur =~ /^(\()/o) {
1429 print "PAREN('$1')\n" if ($dbg_values > 1);
1430 push(@av_paren_type, $av_pending);
1431 $av_pending = '_';
1432 $type = 'N';
1434 } elsif ($cur =~ /^(\))/o) {
1435 my $new_type = pop(@av_paren_type);
1436 if ($new_type ne '_') {
1437 $type = $new_type;
1438 print "PAREN('$1') -> $type\n"
1439 if ($dbg_values > 1);
1440 } else {
1441 print "PAREN('$1')\n" if ($dbg_values > 1);
1444 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1445 print "FUNC($1)\n" if ($dbg_values > 1);
1446 $type = 'V';
1447 $av_pending = 'V';
1449 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1450 if (defined $2 && $type eq 'C' || $type eq 'T') {
1451 $av_pend_colon = 'B';
1452 } elsif ($type eq 'E') {
1453 $av_pend_colon = 'L';
1455 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1456 $type = 'V';
1458 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1459 print "IDENT($1)\n" if ($dbg_values > 1);
1460 $type = 'V';
1462 } elsif ($cur =~ /^($Assignment)/o) {
1463 print "ASSIGN($1)\n" if ($dbg_values > 1);
1464 $type = 'N';
1466 } elsif ($cur =~/^(;|{|})/) {
1467 print "END($1)\n" if ($dbg_values > 1);
1468 $type = 'E';
1469 $av_pend_colon = 'O';
1471 } elsif ($cur =~/^(,)/) {
1472 print "COMMA($1)\n" if ($dbg_values > 1);
1473 $type = 'C';
1475 } elsif ($cur =~ /^(\?)/o) {
1476 print "QUESTION($1)\n" if ($dbg_values > 1);
1477 $type = 'N';
1479 } elsif ($cur =~ /^(:)/o) {
1480 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1482 substr($var, length($res), 1, $av_pend_colon);
1483 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1484 $type = 'E';
1485 } else {
1486 $type = 'N';
1488 $av_pend_colon = 'O';
1490 } elsif ($cur =~ /^(\[)/o) {
1491 print "CLOSE($1)\n" if ($dbg_values > 1);
1492 $type = 'N';
1494 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1495 my $variant;
1497 print "OPV($1)\n" if ($dbg_values > 1);
1498 if ($type eq 'V') {
1499 $variant = 'B';
1500 } else {
1501 $variant = 'U';
1504 substr($var, length($res), 1, $variant);
1505 $type = 'N';
1507 } elsif ($cur =~ /^($Operators)/o) {
1508 print "OP($1)\n" if ($dbg_values > 1);
1509 if ($1 ne '++' && $1 ne '--') {
1510 $type = 'N';
1513 } elsif ($cur =~ /(^.)/o) {
1514 print "C($1)\n" if ($dbg_values > 1);
1516 if (defined $1) {
1517 $cur = substr($cur, length($1));
1518 $res .= $type x length($1);
1522 return ($res, $var);
1525 sub possible {
1526 my ($possible, $line) = @_;
1527 my $notPermitted = qr{(?:
1528 ^(?:
1529 $Modifier|
1530 $Storage|
1531 $Type|
1532 DEFINE_\S+
1534 ^(?:
1535 goto|
1536 return|
1537 case|
1538 else|
1539 asm|__asm__|
1542 \#\#|
1543 )(?:\s|$)|
1544 ^(?:typedef|struct|enum)\b
1545 )}x;
1546 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1547 if ($possible !~ $notPermitted) {
1548 # Check for modifiers.
1549 $possible =~ s/\s*$Storage\s*//g;
1550 $possible =~ s/\s*$Sparse\s*//g;
1551 if ($possible =~ /^\s*$/) {
1553 } elsif ($possible =~ /\s/) {
1554 $possible =~ s/\s*$Type\s*//g;
1555 for my $modifier (split(' ', $possible)) {
1556 if ($modifier !~ $notPermitted) {
1557 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1558 push(@modifierList, $modifier);
1562 } else {
1563 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1564 push(@typeList, $possible);
1566 build_types();
1567 } else {
1568 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1572 my $prefix = '';
1574 sub show_type {
1575 my ($type) = @_;
1577 return defined $use_type{$type} if (scalar keys %use_type > 0);
1579 return !defined $ignore_type{$type};
1582 sub report {
1583 my ($level, $type, $msg) = @_;
1585 if (!show_type($type) ||
1586 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1587 return 0;
1589 my $line;
1590 if ($show_types) {
1591 $line = "$prefix$level:$type: $msg\n";
1592 } else {
1593 $line = "$prefix$level: $msg\n";
1595 $line = (split('\n', $line))[0] . "\n" if ($terse);
1597 push(our @report, $line);
1599 return 1;
1602 sub report_dump {
1603 our @report;
1606 sub fixup_current_range {
1607 my ($lineRef, $offset, $length) = @_;
1609 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1610 my $o = $1;
1611 my $l = $2;
1612 my $no = $o + $offset;
1613 my $nl = $l + $length;
1614 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1618 sub fix_inserted_deleted_lines {
1619 my ($linesRef, $insertedRef, $deletedRef) = @_;
1621 my $range_last_linenr = 0;
1622 my $delta_offset = 0;
1624 my $old_linenr = 0;
1625 my $new_linenr = 0;
1627 my $next_insert = 0;
1628 my $next_delete = 0;
1630 my @lines = ();
1632 my $inserted = @{$insertedRef}[$next_insert++];
1633 my $deleted = @{$deletedRef}[$next_delete++];
1635 foreach my $old_line (@{$linesRef}) {
1636 my $save_line = 1;
1637 my $line = $old_line; #don't modify the array
1638 if ($line =~ /^(?:\+\+\+\|\-\-\-)\s+\S+/) { #new filename
1639 $delta_offset = 0;
1640 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1641 $range_last_linenr = $new_linenr;
1642 fixup_current_range(\$line, $delta_offset, 0);
1645 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1646 $deleted = @{$deletedRef}[$next_delete++];
1647 $save_line = 0;
1648 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1651 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1652 push(@lines, ${$inserted}{'LINE'});
1653 $inserted = @{$insertedRef}[$next_insert++];
1654 $new_linenr++;
1655 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1658 if ($save_line) {
1659 push(@lines, $line);
1660 $new_linenr++;
1663 $old_linenr++;
1666 return @lines;
1669 sub fix_insert_line {
1670 my ($linenr, $line) = @_;
1672 my $inserted = {
1673 LINENR => $linenr,
1674 LINE => $line,
1676 push(@fixed_inserted, $inserted);
1679 sub fix_delete_line {
1680 my ($linenr, $line) = @_;
1682 my $deleted = {
1683 LINENR => $linenr,
1684 LINE => $line,
1687 push(@fixed_deleted, $deleted);
1690 sub ERROR {
1691 my ($type, $msg) = @_;
1693 if (report("ERROR", $type, $msg)) {
1694 our $clean = 0;
1695 our $cnt_error++;
1696 return 1;
1698 return 0;
1700 sub WARN {
1701 my ($type, $msg) = @_;
1703 if (report("WARNING", $type, $msg)) {
1704 our $clean = 0;
1705 our $cnt_warn++;
1706 return 1;
1708 return 0;
1710 sub CHK {
1711 my ($type, $msg) = @_;
1713 if ($check && report("CHECK", $type, $msg)) {
1714 our $clean = 0;
1715 our $cnt_chk++;
1716 return 1;
1718 return 0;
1721 sub check_absolute_file {
1722 my ($absolute, $herecurr) = @_;
1723 my $file = $absolute;
1725 ##print "absolute<$absolute>\n";
1727 # See if any suffix of this path is a path within the tree.
1728 while ($file =~ s@^[^/]*/@@) {
1729 if (-f "$root/$file") {
1730 ##print "file<$file>\n";
1731 last;
1734 if (! -f _) {
1735 return 0;
1738 # It is, so see if the prefix is acceptable.
1739 my $prefix = $absolute;
1740 substr($prefix, -length($file)) = '';
1742 ##print "prefix<$prefix>\n";
1743 if ($prefix ne ".../") {
1744 WARN("USE_RELATIVE_PATH",
1745 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1749 sub trim {
1750 my ($string) = @_;
1752 $string =~ s/^\s+|\s+$//g;
1754 return $string;
1757 sub ltrim {
1758 my ($string) = @_;
1760 $string =~ s/^\s+//;
1762 return $string;
1765 sub rtrim {
1766 my ($string) = @_;
1768 $string =~ s/\s+$//;
1770 return $string;
1773 sub string_find_replace {
1774 my ($string, $find, $replace) = @_;
1776 $string =~ s/$find/$replace/g;
1778 return $string;
1781 sub tabify {
1782 my ($leading) = @_;
1784 my $source_indent = 8;
1785 my $max_spaces_before_tab = $source_indent - 1;
1786 my $spaces_to_tab = " " x $source_indent;
1788 #convert leading spaces to tabs
1789 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1790 #Remove spaces before a tab
1791 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1793 return "$leading";
1796 sub pos_last_openparen {
1797 my ($line) = @_;
1799 my $pos = 0;
1801 my $opens = $line =~ tr/\(/\(/;
1802 my $closes = $line =~ tr/\)/\)/;
1804 my $last_openparen = 0;
1806 if (($opens == 0) || ($closes >= $opens)) {
1807 return -1;
1810 my $len = length($line);
1812 for ($pos = 0; $pos < $len; $pos++) {
1813 my $string = substr($line, $pos);
1814 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1815 $pos += length($1) - 1;
1816 } elsif (substr($line, $pos, 1) eq '(') {
1817 $last_openparen = $pos;
1818 } elsif (index($string, '(') == -1) {
1819 last;
1823 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1826 sub process {
1827 my $filename = shift;
1829 my $linenr=0;
1830 my $prevline="";
1831 my $prevrawline="";
1832 my $stashline="";
1833 my $stashrawline="";
1835 my $length;
1836 my $indent;
1837 my $previndent=0;
1838 my $stashindent=0;
1840 our $clean = 1;
1841 my $signoff = 0;
1842 my $is_patch = 0;
1844 my $in_header_lines = $file ? 0 : 1;
1845 my $in_commit_log = 0; #Scanning lines before patch
1846 my $reported_maintainer_file = 0;
1847 my $non_utf8_charset = 0;
1849 my $last_blank_line = 0;
1850 my $last_coalesced_string_linenr = -1;
1852 our @report = ();
1853 our $cnt_lines = 0;
1854 our $cnt_error = 0;
1855 our $cnt_warn = 0;
1856 our $cnt_chk = 0;
1858 # Trace the real file/line as we go.
1859 my $realfile = '';
1860 my $realline = 0;
1861 my $realcnt = 0;
1862 my $here = '';
1863 my $in_comment = 0;
1864 my $comment_edge = 0;
1865 my $first_line = 0;
1866 my $p1_prefix = '';
1868 my $prev_values = 'E';
1870 # suppression flags
1871 my %suppress_ifbraces;
1872 my %suppress_whiletrailers;
1873 my %suppress_export;
1874 my $suppress_statement = 0;
1876 my %signatures = ();
1878 # Pre-scan the patch sanitizing the lines.
1879 # Pre-scan the patch looking for any __setup documentation.
1881 my @setup_docs = ();
1882 my $setup_docs = 0;
1884 my $camelcase_file_seeded = 0;
1886 sanitise_line_reset();
1887 my $line;
1888 foreach my $rawline (@rawlines) {
1889 $linenr++;
1890 $line = $rawline;
1892 push(@fixed, $rawline) if ($fix);
1894 if ($rawline=~/^\+\+\+\s+(\S+)/) {
1895 $setup_docs = 0;
1896 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1897 $setup_docs = 1;
1899 #next;
1901 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1902 $realline=$1-1;
1903 if (defined $2) {
1904 $realcnt=$3+1;
1905 } else {
1906 $realcnt=1+1;
1908 $in_comment = 0;
1910 # Guestimate if this is a continuing comment. Run
1911 # the context looking for a comment "edge". If this
1912 # edge is a close comment then we must be in a comment
1913 # at context start.
1914 my $edge;
1915 my $cnt = $realcnt;
1916 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1917 next if (defined $rawlines[$ln - 1] &&
1918 $rawlines[$ln - 1] =~ /^-/);
1919 $cnt--;
1920 #print "RAW<$rawlines[$ln - 1]>\n";
1921 last if (!defined $rawlines[$ln - 1]);
1922 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1923 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1924 ($edge) = $1;
1925 last;
1928 if (defined $edge && $edge eq '*/') {
1929 $in_comment = 1;
1932 # Guestimate if this is a continuing comment. If this
1933 # is the start of a diff block and this line starts
1934 # ' *' then it is very likely a comment.
1935 if (!defined $edge &&
1936 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1938 $in_comment = 1;
1941 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1942 sanitise_line_reset($in_comment);
1944 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1945 # Standardise the strings and chars within the input to
1946 # simplify matching -- only bother with positive lines.
1947 $line = sanitise_line($rawline);
1949 push(@lines, $line);
1951 if ($realcnt > 1) {
1952 $realcnt-- if ($line =~ /^(?:\+| |$)/);
1953 } else {
1954 $realcnt = 0;
1957 #print "==>$rawline\n";
1958 #print "-->$line\n";
1960 if ($setup_docs && $line =~ /^\+/) {
1961 push(@setup_docs, $line);
1965 $prefix = '';
1967 $realcnt = 0;
1968 $linenr = 0;
1969 $fixlinenr = -1;
1970 foreach my $line (@lines) {
1971 $linenr++;
1972 $fixlinenr++;
1973 my $sline = $line; #copy of $line
1974 $sline =~ s/$;/ /g; #with comments as spaces
1976 my $rawline = $rawlines[$linenr - 1];
1978 #extract the line range in the file after the patch is applied
1979 if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1980 $is_patch = 1;
1981 $first_line = $linenr + 1;
1982 $realline=$1-1;
1983 if (defined $2) {
1984 $realcnt=$3+1;
1985 } else {
1986 $realcnt=1+1;
1988 annotate_reset();
1989 $prev_values = 'E';
1991 %suppress_ifbraces = ();
1992 %suppress_whiletrailers = ();
1993 %suppress_export = ();
1994 $suppress_statement = 0;
1995 next;
1997 # track the line number as we move through the hunk, note that
1998 # new versions of GNU diff omit the leading space on completely
1999 # blank context lines so we need to count that too.
2000 } elsif ($line =~ /^( |\+|$)/) {
2001 $realline++;
2002 $realcnt-- if ($realcnt != 0);
2004 # Measure the line length and indent.
2005 ($length, $indent) = line_stats($rawline);
2007 # Track the previous line.
2008 ($prevline, $stashline) = ($stashline, $line);
2009 ($previndent, $stashindent) = ($stashindent, $indent);
2010 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2012 #warn "line<$line>\n";
2014 } elsif ($realcnt == 1) {
2015 $realcnt--;
2018 my $hunk_line = ($realcnt != 0);
2020 #make up the handle for any error we report on this line
2021 $prefix = "$filename:$realline: " if ($emacs && $file);
2022 $prefix = "$filename:$linenr: " if ($emacs && !$file);
2024 $here = "#$linenr: " if (!$file);
2025 $here = "#$realline: " if ($file);
2027 my $found_file = 0;
2028 # extract the filename as it passes
2029 if ($line =~ /^diff --git.*?(\S+)$/) {
2030 $realfile = $1;
2031 $realfile =~ s@^([^/]*)/@@ if (!$file);
2032 $in_commit_log = 0;
2033 $found_file = 1;
2034 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2035 $realfile = $1;
2036 $realfile =~ s@^([^/]*)/@@ if (!$file);
2037 $in_commit_log = 0;
2039 $p1_prefix = $1;
2040 if (!$file && $tree && $p1_prefix ne '' &&
2041 -e "$root/$p1_prefix") {
2042 WARN("PATCH_PREFIX",
2043 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2046 if ($realfile =~ m@^include/asm/@) {
2047 ERROR("MODIFIED_INCLUDE_ASM",
2048 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2050 $found_file = 1;
2053 if ($found_file) {
2054 if ($realfile =~ m@^(drivers/net/|net/)@) {
2055 $check = 1;
2056 } else {
2057 $check = $check_orig;
2059 next;
2062 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2064 my $hereline = "$here\n$rawline\n";
2065 my $herecurr = "$here\n$rawline\n";
2066 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2068 $cnt_lines++ if ($realcnt != 0);
2070 # Check for incorrect file permissions
2071 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2072 my $permhere = $here . "FILE: $realfile\n";
2073 if ($realfile !~ m@scripts/@ &&
2074 $realfile !~ /\.(py|pl|awk|sh)$/) {
2075 ERROR("EXECUTE_PERMISSIONS",
2076 "do not set execute permissions for source files\n" . $permhere);
2080 # Check the patch for a signoff:
2081 if ($line =~ /^\s*signed-off-by:/i) {
2082 $signoff++;
2083 $in_commit_log = 0;
2086 # Check if MAINTAINERS is being updated. If so, there's probably no need to
2087 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2088 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2089 $reported_maintainer_file = 1;
2092 # Check signature styles
2093 if (!$in_header_lines &&
2094 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2095 my $space_before = $1;
2096 my $sign_off = $2;
2097 my $space_after = $3;
2098 my $email = $4;
2099 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2101 if ($sign_off !~ /$signature_tags/) {
2102 WARN("BAD_SIGN_OFF",
2103 "Non-standard signature: $sign_off\n" . $herecurr);
2105 if (defined $space_before && $space_before ne "") {
2106 if (WARN("BAD_SIGN_OFF",
2107 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2108 $fix) {
2109 $fixed[$fixlinenr] =
2110 "$ucfirst_sign_off $email";
2113 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2114 if (WARN("BAD_SIGN_OFF",
2115 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2116 $fix) {
2117 $fixed[$fixlinenr] =
2118 "$ucfirst_sign_off $email";
2122 if (!defined $space_after || $space_after ne " ") {
2123 if (WARN("BAD_SIGN_OFF",
2124 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2125 $fix) {
2126 $fixed[$fixlinenr] =
2127 "$ucfirst_sign_off $email";
2131 my ($email_name, $email_address, $comment) = parse_email($email);
2132 my $suggested_email = format_email(($email_name, $email_address));
2133 if ($suggested_email eq "") {
2134 ERROR("BAD_SIGN_OFF",
2135 "Unrecognized email address: '$email'\n" . $herecurr);
2136 } else {
2137 my $dequoted = $suggested_email;
2138 $dequoted =~ s/^"//;
2139 $dequoted =~ s/" </ </;
2140 # Don't force email to have quotes
2141 # Allow just an angle bracketed address
2142 if ("$dequoted$comment" ne $email &&
2143 "<$email_address>$comment" ne $email &&
2144 "$suggested_email$comment" ne $email) {
2145 WARN("BAD_SIGN_OFF",
2146 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2150 # Check for duplicate signatures
2151 my $sig_nospace = $line;
2152 $sig_nospace =~ s/\s//g;
2153 $sig_nospace = lc($sig_nospace);
2154 if (defined $signatures{$sig_nospace}) {
2155 WARN("BAD_SIGN_OFF",
2156 "Duplicate signature\n" . $herecurr);
2157 } else {
2158 $signatures{$sig_nospace} = 1;
2162 # Check for old stable address
2163 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2164 ERROR("STABLE_ADDRESS",
2165 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2168 # Check for unwanted Gerrit info
2169 if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2170 ERROR("GERRIT_CHANGE_ID",
2171 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2174 # Check for improperly formed commit descriptions
2175 if ($in_commit_log &&
2176 $line =~ /\bcommit\s+[0-9a-f]{5,}/i &&
2177 !($line =~ /\b[Cc]ommit [0-9a-f]{12,40} \("/ ||
2178 ($line =~ /\b[Cc]ommit [0-9a-f]{12,40}\s*$/ &&
2179 defined $rawlines[$linenr] &&
2180 $rawlines[$linenr] =~ /^\s*\("/))) {
2181 $line =~ /\b(c)ommit\s+([0-9a-f]{5,})/i;
2182 my $init_char = $1;
2183 my $orig_commit = lc($2);
2184 my $id = '01234567890ab';
2185 my $desc = 'commit description';
2186 ($id, $desc) = git_commit_info($orig_commit, $id, $desc);
2187 ERROR("GIT_COMMIT_ID",
2188 "Please use 12 or more chars for the git commit ID like: '${init_char}ommit $id (\"$desc\")'\n" . $herecurr);
2191 # Check for added, moved or deleted files
2192 if (!$reported_maintainer_file && !$in_commit_log &&
2193 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2194 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2195 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2196 (defined($1) || defined($2))))) {
2197 $reported_maintainer_file = 1;
2198 WARN("FILE_PATH_CHANGES",
2199 "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2202 # Check for wrappage within a valid hunk of the file
2203 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2204 ERROR("CORRUPTED_PATCH",
2205 "patch seems to be corrupt (line wrapped?)\n" .
2206 $herecurr) if (!$emitted_corrupt++);
2209 # Check for absolute kernel paths.
2210 if ($tree) {
2211 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2212 my $file = $1;
2214 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2215 check_absolute_file($1, $herecurr)) {
2217 } else {
2218 check_absolute_file($file, $herecurr);
2223 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2224 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2225 $rawline !~ m/^$UTF8*$/) {
2226 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2228 my $blank = copy_spacing($rawline);
2229 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2230 my $hereptr = "$hereline$ptr\n";
2232 CHK("INVALID_UTF8",
2233 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2236 # Check if it's the start of a commit log
2237 # (not a header line and we haven't seen the patch filename)
2238 if ($in_header_lines && $realfile =~ /^$/ &&
2239 !($rawline =~ /^\s+\S/ ||
2240 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2241 $in_header_lines = 0;
2242 $in_commit_log = 1;
2245 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2246 # declined it, i.e defined some charset where it is missing.
2247 if ($in_header_lines &&
2248 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2249 $1 !~ /utf-8/i) {
2250 $non_utf8_charset = 1;
2253 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2254 $rawline =~ /$NON_ASCII_UTF8/) {
2255 WARN("UTF8_BEFORE_PATCH",
2256 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2259 # Check for various typo / spelling mistakes
2260 if (defined($misspellings) && ($in_commit_log || $line =~ /^\+/)) {
2261 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:$|[^a-z@])/gi) {
2262 my $typo = $1;
2263 my $typo_fix = $spelling_fix{lc($typo)};
2264 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2265 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2266 my $msg_type = \&WARN;
2267 $msg_type = \&CHK if ($file);
2268 if (&{$msg_type}("TYPO_SPELLING",
2269 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2270 $fix) {
2271 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2276 # ignore non-hunk lines and lines being removed
2277 next if (!$hunk_line || $line =~ /^-/);
2279 #trailing whitespace
2280 if ($line =~ /^\+.*\015/) {
2281 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2282 if (ERROR("DOS_LINE_ENDINGS",
2283 "DOS line endings\n" . $herevet) &&
2284 $fix) {
2285 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2287 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2288 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2289 if (ERROR("TRAILING_WHITESPACE",
2290 "trailing whitespace\n" . $herevet) &&
2291 $fix) {
2292 $fixed[$fixlinenr] =~ s/\s+$//;
2295 $rpt_cleaners = 1;
2298 # Check for FSF mailing addresses.
2299 if ($rawline =~ /\bwrite to the Free/i ||
2300 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2301 $rawline =~ /\b51\s+Franklin\s+St/i) {
2302 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2303 my $msg_type = \&ERROR;
2304 $msg_type = \&CHK if ($file);
2305 &{$msg_type}("FSF_MAILING_ADDRESS",
2306 "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)
2309 # check for Kconfig help text having a real description
2310 # Only applies when adding the entry originally, after that we do not have
2311 # sufficient context to determine whether it is indeed long enough.
2312 if ($realfile =~ /Kconfig/ &&
2313 $line =~ /^\+\s*config\s+/) {
2314 my $length = 0;
2315 my $cnt = $realcnt;
2316 my $ln = $linenr + 1;
2317 my $f;
2318 my $is_start = 0;
2319 my $is_end = 0;
2320 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2321 $f = $lines[$ln - 1];
2322 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2323 $is_end = $lines[$ln - 1] =~ /^\+/;
2325 next if ($f =~ /^-/);
2326 last if (!$file && $f =~ /^\@\@/);
2328 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2329 $is_start = 1;
2330 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2331 $length = -1;
2334 $f =~ s/^.//;
2335 $f =~ s/#.*//;
2336 $f =~ s/^\s+//;
2337 next if ($f =~ /^$/);
2338 if ($f =~ /^\s*config\s/) {
2339 $is_end = 1;
2340 last;
2342 $length++;
2344 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2345 WARN("CONFIG_DESCRIPTION",
2346 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2348 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2351 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2352 if ($realfile =~ /Kconfig/ &&
2353 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2354 WARN("CONFIG_EXPERIMENTAL",
2355 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2358 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2359 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2360 my $flag = $1;
2361 my $replacement = {
2362 'EXTRA_AFLAGS' => 'asflags-y',
2363 'EXTRA_CFLAGS' => 'ccflags-y',
2364 'EXTRA_CPPFLAGS' => 'cppflags-y',
2365 'EXTRA_LDFLAGS' => 'ldflags-y',
2368 WARN("DEPRECATED_VARIABLE",
2369 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2372 # check for DT compatible documentation
2373 if (defined $root &&
2374 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2375 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2377 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2379 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2380 my $vp_file = $dt_path . "vendor-prefixes.txt";
2382 foreach my $compat (@compats) {
2383 my $compat2 = $compat;
2384 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2385 my $compat3 = $compat;
2386 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2387 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2388 if ( $? >> 8 ) {
2389 WARN("UNDOCUMENTED_DT_STRING",
2390 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2393 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2394 my $vendor = $1;
2395 `grep -Eq "^$vendor\\b" $vp_file`;
2396 if ( $? >> 8 ) {
2397 WARN("UNDOCUMENTED_DT_STRING",
2398 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2403 # check we are in a valid source file if not then ignore this hunk
2404 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2406 #line length limit
2407 if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
2408 $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
2409 !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ ||
2410 $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
2411 $length > $max_line_length)
2413 WARN("LONG_LINE",
2414 "line over $max_line_length characters\n" . $herecurr);
2417 # check for adding lines without a newline.
2418 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2419 WARN("MISSING_EOF_NEWLINE",
2420 "adding a line without newline at end of file\n" . $herecurr);
2423 # Blackfin: use hi/lo macros
2424 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2425 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2426 my $herevet = "$here\n" . cat_vet($line) . "\n";
2427 ERROR("LO_MACRO",
2428 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2430 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2431 my $herevet = "$here\n" . cat_vet($line) . "\n";
2432 ERROR("HI_MACRO",
2433 "use the HI() macro, not (... >> 16)\n" . $herevet);
2437 # check we are in a valid source file C or perl if not then ignore this hunk
2438 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2440 # at the beginning of a line any tabs must come first and anything
2441 # more than 8 must use tabs.
2442 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2443 $rawline =~ /^\+\s* \s*/) {
2444 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2445 $rpt_cleaners = 1;
2446 if (ERROR("CODE_INDENT",
2447 "code indent should use tabs where possible\n" . $herevet) &&
2448 $fix) {
2449 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2453 # check for space before tabs.
2454 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2455 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2456 if (WARN("SPACE_BEFORE_TAB",
2457 "please, no space before tabs\n" . $herevet) &&
2458 $fix) {
2459 while ($fixed[$fixlinenr] =~
2460 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2461 while ($fixed[$fixlinenr] =~
2462 s/(^\+.*) +\t/$1\t/) {}
2466 # check for && or || at the start of a line
2467 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2468 CHK("LOGICAL_CONTINUATIONS",
2469 "Logical continuations should be on the previous line\n" . $hereprev);
2472 # check multi-line statement indentation matches previous line
2473 if ($^V && $^V ge 5.10.0 &&
2474 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2475 $prevline =~ /^\+(\t*)(.*)$/;
2476 my $oldindent = $1;
2477 my $rest = $2;
2479 my $pos = pos_last_openparen($rest);
2480 if ($pos >= 0) {
2481 $line =~ /^(\+| )([ \t]*)/;
2482 my $newindent = $2;
2484 my $goodtabindent = $oldindent .
2485 "\t" x ($pos / 8) .
2486 " " x ($pos % 8);
2487 my $goodspaceindent = $oldindent . " " x $pos;
2489 if ($newindent ne $goodtabindent &&
2490 $newindent ne $goodspaceindent) {
2492 if (CHK("PARENTHESIS_ALIGNMENT",
2493 "Alignment should match open parenthesis\n" . $hereprev) &&
2494 $fix && $line =~ /^\+/) {
2495 $fixed[$fixlinenr] =~
2496 s/^\+[ \t]*/\+$goodtabindent/;
2502 if ($line =~ /^\+.*(\w+\s*)?\(\s*$Type\s*\)[ \t]+(?!$Assignment|$Arithmetic|[,;\({\[\<\>])/ &&
2503 (!defined($1) || $1 !~ /sizeof\s*/)) {
2504 if (CHK("SPACING",
2505 "No space is necessary after a cast\n" . $herecurr) &&
2506 $fix) {
2507 $fixed[$fixlinenr] =~
2508 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2512 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2513 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2514 $rawline =~ /^\+[ \t]*\*/ &&
2515 $realline > 2) {
2516 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2517 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2520 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2521 $prevrawline =~ /^\+[ \t]*\/\*/ && #starting /*
2522 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2523 $rawline =~ /^\+/ && #line is new
2524 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2525 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2526 "networking block comments start with * on subsequent lines\n" . $hereprev);
2529 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2530 $rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2531 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2532 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2533 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2534 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2535 "networking block comments put the trailing */ on a separate line\n" . $herecurr);
2538 # check for missing blank lines after struct/union declarations
2539 # with exceptions for various attributes and macros
2540 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2541 $line =~ /^\+/ &&
2542 !($line =~ /^\+\s*$/ ||
2543 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2544 $line =~ /^\+\s*MODULE_/i ||
2545 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2546 $line =~ /^\+[a-z_]*init/ ||
2547 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2548 $line =~ /^\+\s*DECLARE/ ||
2549 $line =~ /^\+\s*__setup/)) {
2550 if (CHK("LINE_SPACING",
2551 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2552 $fix) {
2553 fix_insert_line($fixlinenr, "\+");
2557 # check for multiple consecutive blank lines
2558 if ($prevline =~ /^[\+ ]\s*$/ &&
2559 $line =~ /^\+\s*$/ &&
2560 $last_blank_line != ($linenr - 1)) {
2561 if (CHK("LINE_SPACING",
2562 "Please don't use multiple blank lines\n" . $hereprev) &&
2563 $fix) {
2564 fix_delete_line($fixlinenr, $rawline);
2567 $last_blank_line = $linenr;
2570 # check for missing blank lines after declarations
2571 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2572 # actual declarations
2573 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2574 # function pointer declarations
2575 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2576 # foo bar; where foo is some local typedef or #define
2577 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2578 # known declaration macros
2579 $prevline =~ /^\+\s+$declaration_macros/) &&
2580 # for "else if" which can look like "$Ident $Ident"
2581 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2582 # other possible extensions of declaration lines
2583 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2584 # not starting a section or a macro "\" extended line
2585 $prevline =~ /(?:\{\s*|\\)$/) &&
2586 # looks like a declaration
2587 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2588 # function pointer declarations
2589 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2590 # foo bar; where foo is some local typedef or #define
2591 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2592 # known declaration macros
2593 $sline =~ /^\+\s+$declaration_macros/ ||
2594 # start of struct or union or enum
2595 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2596 # start or end of block or continuation of declaration
2597 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2598 # bitfield continuation
2599 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2600 # other possible extensions of declaration lines
2601 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2602 # indentation of previous and current line are the same
2603 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2604 if (WARN("LINE_SPACING",
2605 "Missing a blank line after declarations\n" . $hereprev) &&
2606 $fix) {
2607 fix_insert_line($fixlinenr, "\+");
2611 # check for spaces at the beginning of a line.
2612 # Exceptions:
2613 # 1) within comments
2614 # 2) indented preprocessor commands
2615 # 3) hanging labels
2616 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2617 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2618 if (WARN("LEADING_SPACE",
2619 "please, no spaces at the start of a line\n" . $herevet) &&
2620 $fix) {
2621 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2625 # check we are in a valid C source file if not then ignore this hunk
2626 next if ($realfile !~ /\.(h|c)$/);
2628 # check indentation of any line with a bare else
2629 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2630 # if the previous line is a break or return and is indented 1 tab more...
2631 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2632 my $tabs = length($1) + 1;
2633 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2634 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2635 defined $lines[$linenr] &&
2636 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2637 WARN("UNNECESSARY_ELSE",
2638 "else is not generally useful after a break or return\n" . $hereprev);
2642 # check indentation of a line with a break;
2643 # if the previous line is a goto or return and is indented the same # of tabs
2644 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2645 my $tabs = $1;
2646 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2647 WARN("UNNECESSARY_BREAK",
2648 "break is not useful after a goto or return\n" . $hereprev);
2652 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2653 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2654 WARN("CONFIG_EXPERIMENTAL",
2655 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2658 # check for RCS/CVS revision markers
2659 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2660 WARN("CVS_KEYWORD",
2661 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2664 # Blackfin: don't use __builtin_bfin_[cs]sync
2665 if ($line =~ /__builtin_bfin_csync/) {
2666 my $herevet = "$here\n" . cat_vet($line) . "\n";
2667 ERROR("CSYNC",
2668 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2670 if ($line =~ /__builtin_bfin_ssync/) {
2671 my $herevet = "$here\n" . cat_vet($line) . "\n";
2672 ERROR("SSYNC",
2673 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2676 # check for old HOTPLUG __dev<foo> section markings
2677 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2678 WARN("HOTPLUG_SECTION",
2679 "Using $1 is unnecessary\n" . $herecurr);
2682 # Check for potential 'bare' types
2683 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2684 $realline_next);
2685 #print "LINE<$line>\n";
2686 if ($linenr >= $suppress_statement &&
2687 $realcnt && $sline =~ /.\s*\S/) {
2688 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2689 ctx_statement_block($linenr, $realcnt, 0);
2690 $stat =~ s/\n./\n /g;
2691 $cond =~ s/\n./\n /g;
2693 #print "linenr<$linenr> <$stat>\n";
2694 # If this statement has no statement boundaries within
2695 # it there is no point in retrying a statement scan
2696 # until we hit end of it.
2697 my $frag = $stat; $frag =~ s/;+\s*$//;
2698 if ($frag !~ /(?:{|;)/) {
2699 #print "skip<$line_nr_next>\n";
2700 $suppress_statement = $line_nr_next;
2703 # Find the real next line.
2704 $realline_next = $line_nr_next;
2705 if (defined $realline_next &&
2706 (!defined $lines[$realline_next - 1] ||
2707 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2708 $realline_next++;
2711 my $s = $stat;
2712 $s =~ s/{.*$//s;
2714 # Ignore goto labels.
2715 if ($s =~ /$Ident:\*$/s) {
2717 # Ignore functions being called
2718 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
2720 } elsif ($s =~ /^.\s*else\b/s) {
2722 # declarations always start with types
2723 } 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) {
2724 my $type = $1;
2725 $type =~ s/\s+/ /g;
2726 possible($type, "A:" . $s);
2728 # definitions in global scope can only start with types
2729 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
2730 possible($1, "B:" . $s);
2733 # any (foo ... *) is a pointer cast, and foo is a type
2734 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
2735 possible($1, "C:" . $s);
2738 # Check for any sort of function declaration.
2739 # int foo(something bar, other baz);
2740 # void (*store_gdt)(x86_descr_ptr *);
2741 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
2742 my ($name_len) = length($1);
2744 my $ctx = $s;
2745 substr($ctx, 0, $name_len + 1, '');
2746 $ctx =~ s/\)[^\)]*$//;
2748 for my $arg (split(/\s*,\s*/, $ctx)) {
2749 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
2751 possible($1, "D:" . $s);
2759 # Checks which may be anchored in the context.
2762 # Check for switch () and associated case and default
2763 # statements should be at the same indent.
2764 if ($line=~/\bswitch\s*\(.*\)/) {
2765 my $err = '';
2766 my $sep = '';
2767 my @ctx = ctx_block_outer($linenr, $realcnt);
2768 shift(@ctx);
2769 for my $ctx (@ctx) {
2770 my ($clen, $cindent) = line_stats($ctx);
2771 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
2772 $indent != $cindent) {
2773 $err .= "$sep$ctx\n";
2774 $sep = '';
2775 } else {
2776 $sep = "[...]\n";
2779 if ($err ne '') {
2780 ERROR("SWITCH_CASE_INDENT_LEVEL",
2781 "switch and case should be at the same indent\n$hereline$err");
2785 # if/while/etc brace do not go on next line, unless defining a do while loop,
2786 # or if that brace on the next line is for something else
2787 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
2788 my $pre_ctx = "$1$2";
2790 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
2792 if ($line =~ /^\+\t{6,}/) {
2793 WARN("DEEP_INDENTATION",
2794 "Too many leading tabs - consider code refactoring\n" . $herecurr);
2797 my $ctx_cnt = $realcnt - $#ctx - 1;
2798 my $ctx = join("\n", @ctx);
2800 my $ctx_ln = $linenr;
2801 my $ctx_skip = $realcnt;
2803 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
2804 defined $lines[$ctx_ln - 1] &&
2805 $lines[$ctx_ln - 1] =~ /^-/)) {
2806 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
2807 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
2808 $ctx_ln++;
2811 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
2812 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
2814 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
2815 ERROR("OPEN_BRACE",
2816 "that open brace { should be on the previous line\n" .
2817 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2819 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
2820 $ctx =~ /\)\s*\;\s*$/ &&
2821 defined $lines[$ctx_ln - 1])
2823 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
2824 if ($nindent > $indent) {
2825 WARN("TRAILING_SEMICOLON",
2826 "trailing semicolon indicates no statements, indent implies otherwise\n" .
2827 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
2832 # Check relative indent for conditionals and blocks.
2833 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
2834 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2835 ctx_statement_block($linenr, $realcnt, 0)
2836 if (!defined $stat);
2837 my ($s, $c) = ($stat, $cond);
2839 substr($s, 0, length($c), '');
2841 # Make sure we remove the line prefixes as we have
2842 # none on the first line, and are going to readd them
2843 # where necessary.
2844 $s =~ s/\n./\n/gs;
2846 # Find out how long the conditional actually is.
2847 my @newlines = ($c =~ /\n/gs);
2848 my $cond_lines = 1 + $#newlines;
2850 # We want to check the first line inside the block
2851 # starting at the end of the conditional, so remove:
2852 # 1) any blank line termination
2853 # 2) any opening brace { on end of the line
2854 # 3) any do (...) {
2855 my $continuation = 0;
2856 my $check = 0;
2857 $s =~ s/^.*\bdo\b//;
2858 $s =~ s/^\s*{//;
2859 if ($s =~ s/^\s*\\//) {
2860 $continuation = 1;
2862 if ($s =~ s/^\s*?\n//) {
2863 $check = 1;
2864 $cond_lines++;
2867 # Also ignore a loop construct at the end of a
2868 # preprocessor statement.
2869 if (($prevline =~ /^.\s*#\s*define\s/ ||
2870 $prevline =~ /\\\s*$/) && $continuation == 0) {
2871 $check = 0;
2874 my $cond_ptr = -1;
2875 $continuation = 0;
2876 while ($cond_ptr != $cond_lines) {
2877 $cond_ptr = $cond_lines;
2879 # If we see an #else/#elif then the code
2880 # is not linear.
2881 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
2882 $check = 0;
2885 # Ignore:
2886 # 1) blank lines, they should be at 0,
2887 # 2) preprocessor lines, and
2888 # 3) labels.
2889 if ($continuation ||
2890 $s =~ /^\s*?\n/ ||
2891 $s =~ /^\s*#\s*?/ ||
2892 $s =~ /^\s*$Ident\s*:/) {
2893 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
2894 if ($s =~ s/^.*?\n//) {
2895 $cond_lines++;
2900 my (undef, $sindent) = line_stats("+" . $s);
2901 my $stat_real = raw_line($linenr, $cond_lines);
2903 # Check if either of these lines are modified, else
2904 # this is not this patch's fault.
2905 if (!defined($stat_real) ||
2906 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
2907 $check = 0;
2909 if (defined($stat_real) && $cond_lines > 1) {
2910 $stat_real = "[...]\n$stat_real";
2913 #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";
2915 if ($check && (($sindent % 8) != 0 ||
2916 ($sindent <= $indent && $s ne ''))) {
2917 WARN("SUSPECT_CODE_INDENT",
2918 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
2922 # Track the 'values' across context and added lines.
2923 my $opline = $line; $opline =~ s/^./ /;
2924 my ($curr_values, $curr_vars) =
2925 annotate_values($opline . "\n", $prev_values);
2926 $curr_values = $prev_values . $curr_values;
2927 if ($dbg_values) {
2928 my $outline = $opline; $outline =~ s/\t/ /g;
2929 print "$linenr > .$outline\n";
2930 print "$linenr > $curr_values\n";
2931 print "$linenr > $curr_vars\n";
2933 $prev_values = substr($curr_values, -1);
2935 #ignore lines not being added
2936 next if ($line =~ /^[^\+]/);
2938 # TEST: allow direct testing of the type matcher.
2939 if ($dbg_type) {
2940 if ($line =~ /^.\s*$Declare\s*$/) {
2941 ERROR("TEST_TYPE",
2942 "TEST: is type\n" . $herecurr);
2943 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
2944 ERROR("TEST_NOT_TYPE",
2945 "TEST: is not type ($1 is)\n". $herecurr);
2947 next;
2949 # TEST: allow direct testing of the attribute matcher.
2950 if ($dbg_attr) {
2951 if ($line =~ /^.\s*$Modifier\s*$/) {
2952 ERROR("TEST_ATTR",
2953 "TEST: is attr\n" . $herecurr);
2954 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
2955 ERROR("TEST_NOT_ATTR",
2956 "TEST: is not attr ($1 is)\n". $herecurr);
2958 next;
2961 # check for initialisation to aggregates open brace on the next line
2962 if ($line =~ /^.\s*{/ &&
2963 $prevline =~ /(?:^|[^=])=\s*$/) {
2964 if (ERROR("OPEN_BRACE",
2965 "that open brace { should be on the previous line\n" . $hereprev) &&
2966 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
2967 fix_delete_line($fixlinenr - 1, $prevrawline);
2968 fix_delete_line($fixlinenr, $rawline);
2969 my $fixedline = $prevrawline;
2970 $fixedline =~ s/\s*=\s*$/ = {/;
2971 fix_insert_line($fixlinenr, $fixedline);
2972 $fixedline = $line;
2973 $fixedline =~ s/^(.\s*){\s*/$1/;
2974 fix_insert_line($fixlinenr, $fixedline);
2979 # Checks which are anchored on the added line.
2982 # check for malformed paths in #include statements (uses RAW line)
2983 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
2984 my $path = $1;
2985 if ($path =~ m{//}) {
2986 ERROR("MALFORMED_INCLUDE",
2987 "malformed #include filename\n" . $herecurr);
2989 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
2990 ERROR("UAPI_INCLUDE",
2991 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
2995 # no C99 // comments
2996 if ($line =~ m{//}) {
2997 if (ERROR("C99_COMMENTS",
2998 "do not use C99 // comments\n" . $herecurr) &&
2999 $fix) {
3000 my $line = $fixed[$fixlinenr];
3001 if ($line =~ /\/\/(.*)$/) {
3002 my $comment = trim($1);
3003 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3007 # Remove C99 comments.
3008 $line =~ s@//.*@@;
3009 $opline =~ s@//.*@@;
3011 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3012 # the whole statement.
3013 #print "APW <$lines[$realline_next - 1]>\n";
3014 if (defined $realline_next &&
3015 exists $lines[$realline_next - 1] &&
3016 !defined $suppress_export{$realline_next} &&
3017 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3018 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3019 # Handle definitions which produce identifiers with
3020 # a prefix:
3021 # XXX(foo);
3022 # EXPORT_SYMBOL(something_foo);
3023 my $name = $1;
3024 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3025 $name =~ /^${Ident}_$2/) {
3026 #print "FOO C name<$name>\n";
3027 $suppress_export{$realline_next} = 1;
3029 } elsif ($stat !~ /(?:
3030 \n.}\s*$|
3031 ^.DEFINE_$Ident\(\Q$name\E\)|
3032 ^.DECLARE_$Ident\(\Q$name\E\)|
3033 ^.LIST_HEAD\(\Q$name\E\)|
3034 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3035 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3036 )/x) {
3037 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3038 $suppress_export{$realline_next} = 2;
3039 } else {
3040 $suppress_export{$realline_next} = 1;
3043 if (!defined $suppress_export{$linenr} &&
3044 $prevline =~ /^.\s*$/ &&
3045 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3046 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3047 #print "FOO B <$lines[$linenr - 1]>\n";
3048 $suppress_export{$linenr} = 2;
3050 if (defined $suppress_export{$linenr} &&
3051 $suppress_export{$linenr} == 2) {
3052 WARN("EXPORT_SYMBOL",
3053 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3056 # check for global initialisers.
3057 if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) {
3058 if (ERROR("GLOBAL_INITIALISERS",
3059 "do not initialise globals to 0 or NULL\n" .
3060 $herecurr) &&
3061 $fix) {
3062 $fixed[$fixlinenr] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/;
3065 # check for static initialisers.
3066 if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
3067 if (ERROR("INITIALISED_STATIC",
3068 "do not initialise statics to 0 or NULL\n" .
3069 $herecurr) &&
3070 $fix) {
3071 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/;
3075 # check for misordered declarations of char/short/int/long with signed/unsigned
3076 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3077 my $tmp = trim($1);
3078 WARN("MISORDERED_TYPE",
3079 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3082 # check for static const char * arrays.
3083 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3084 WARN("STATIC_CONST_CHAR_ARRAY",
3085 "static const char * array should probably be static const char * const\n" .
3086 $herecurr);
3089 # check for static char foo[] = "bar" declarations.
3090 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3091 WARN("STATIC_CONST_CHAR_ARRAY",
3092 "static char array declaration should probably be static const char\n" .
3093 $herecurr);
3096 # check for non-global char *foo[] = {"bar", ...} declarations.
3097 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3098 WARN("STATIC_CONST_CHAR_ARRAY",
3099 "char * array declaration might be better as static const\n" .
3100 $herecurr);
3103 # check for function declarations without arguments like "int foo()"
3104 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3105 if (ERROR("FUNCTION_WITHOUT_ARGS",
3106 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3107 $fix) {
3108 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3112 # check for uses of DEFINE_PCI_DEVICE_TABLE
3113 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3114 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3115 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3116 $fix) {
3117 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3121 # check for new typedefs, only function parameters and sparse annotations
3122 # make sense.
3123 if ($line =~ /\btypedef\s/ &&
3124 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3125 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3126 $line !~ /\b$typeTypedefs\b/ &&
3127 $line !~ /\b__bitwise(?:__|)\b/) {
3128 WARN("NEW_TYPEDEFS",
3129 "do not add new typedefs\n" . $herecurr);
3132 # * goes on variable not on type
3133 # (char*[ const])
3134 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3135 #print "AA<$1>\n";
3136 my ($ident, $from, $to) = ($1, $2, $2);
3138 # Should start with a space.
3139 $to =~ s/^(\S)/ $1/;
3140 # Should not end with a space.
3141 $to =~ s/\s+$//;
3142 # '*'s should not have spaces between.
3143 while ($to =~ s/\*\s+\*/\*\*/) {
3146 ## print "1: from<$from> to<$to> ident<$ident>\n";
3147 if ($from ne $to) {
3148 if (ERROR("POINTER_LOCATION",
3149 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3150 $fix) {
3151 my $sub_from = $ident;
3152 my $sub_to = $ident;
3153 $sub_to =~ s/\Q$from\E/$to/;
3154 $fixed[$fixlinenr] =~
3155 s@\Q$sub_from\E@$sub_to@;
3159 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3160 #print "BB<$1>\n";
3161 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3163 # Should start with a space.
3164 $to =~ s/^(\S)/ $1/;
3165 # Should not end with a space.
3166 $to =~ s/\s+$//;
3167 # '*'s should not have spaces between.
3168 while ($to =~ s/\*\s+\*/\*\*/) {
3170 # Modifiers should have spaces.
3171 $to =~ s/(\b$Modifier$)/$1 /;
3173 ## print "2: from<$from> to<$to> ident<$ident>\n";
3174 if ($from ne $to && $ident !~ /^$Modifier$/) {
3175 if (ERROR("POINTER_LOCATION",
3176 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3177 $fix) {
3179 my $sub_from = $match;
3180 my $sub_to = $match;
3181 $sub_to =~ s/\Q$from\E/$to/;
3182 $fixed[$fixlinenr] =~
3183 s@\Q$sub_from\E@$sub_to@;
3188 # # no BUG() or BUG_ON()
3189 # if ($line =~ /\b(BUG|BUG_ON)\b/) {
3190 # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
3191 # print "$herecurr";
3192 # $clean = 0;
3195 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3196 WARN("LINUX_VERSION_CODE",
3197 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3200 # check for uses of printk_ratelimit
3201 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3202 WARN("PRINTK_RATELIMITED",
3203 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3206 # printk should use KERN_* levels. Note that follow on printk's on the
3207 # same line do not need a level, so we use the current block context
3208 # to try and find and validate the current printk. In summary the current
3209 # printk includes all preceding printk's which have no newline on the end.
3210 # we assume the first bad printk is the one to report.
3211 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3212 my $ok = 0;
3213 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3214 #print "CHECK<$lines[$ln - 1]\n";
3215 # we have a preceding printk if it ends
3216 # with "\n" ignore it, else it is to blame
3217 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3218 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3219 $ok = 1;
3221 last;
3224 if ($ok == 0) {
3225 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3226 "printk() should include KERN_ facility level\n" . $herecurr);
3230 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3231 my $orig = $1;
3232 my $level = lc($orig);
3233 $level = "warn" if ($level eq "warning");
3234 my $level2 = $level;
3235 $level2 = "dbg" if ($level eq "debug");
3236 WARN("PREFER_PR_LEVEL",
3237 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3240 if ($line =~ /\bpr_warning\s*\(/) {
3241 if (WARN("PREFER_PR_LEVEL",
3242 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3243 $fix) {
3244 $fixed[$fixlinenr] =~
3245 s/\bpr_warning\b/pr_warn/;
3249 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3250 my $orig = $1;
3251 my $level = lc($orig);
3252 $level = "warn" if ($level eq "warning");
3253 $level = "dbg" if ($level eq "debug");
3254 WARN("PREFER_DEV_LEVEL",
3255 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3258 # function brace can't be on same line, except for #defines of do while,
3259 # or if closed on same line
3260 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3261 !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
3262 if (ERROR("OPEN_BRACE",
3263 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3264 $fix) {
3265 fix_delete_line($fixlinenr, $rawline);
3266 my $fixed_line = $rawline;
3267 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3268 my $line1 = $1;
3269 my $line2 = $2;
3270 fix_insert_line($fixlinenr, ltrim($line1));
3271 fix_insert_line($fixlinenr, "\+{");
3272 if ($line2 !~ /^\s*$/) {
3273 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3278 # open braces for enum, union and struct go on the same line.
3279 if ($line =~ /^.\s*{/ &&
3280 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3281 if (ERROR("OPEN_BRACE",
3282 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3283 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3284 fix_delete_line($fixlinenr - 1, $prevrawline);
3285 fix_delete_line($fixlinenr, $rawline);
3286 my $fixedline = rtrim($prevrawline) . " {";
3287 fix_insert_line($fixlinenr, $fixedline);
3288 $fixedline = $rawline;
3289 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3290 if ($fixedline !~ /^\+\s*$/) {
3291 fix_insert_line($fixlinenr, $fixedline);
3296 # missing space after union, struct or enum definition
3297 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3298 if (WARN("SPACING",
3299 "missing space after $1 definition\n" . $herecurr) &&
3300 $fix) {
3301 $fixed[$fixlinenr] =~
3302 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3306 # Function pointer declarations
3307 # check spacing between type, funcptr, and args
3308 # canonical declaration is "type (*funcptr)(args...)"
3309 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3310 my $declare = $1;
3311 my $pre_pointer_space = $2;
3312 my $post_pointer_space = $3;
3313 my $funcname = $4;
3314 my $post_funcname_space = $5;
3315 my $pre_args_space = $6;
3317 # the $Declare variable will capture all spaces after the type
3318 # so check it for a missing trailing missing space but pointer return types
3319 # don't need a space so don't warn for those.
3320 my $post_declare_space = "";
3321 if ($declare =~ /(\s+)$/) {
3322 $post_declare_space = $1;
3323 $declare = rtrim($declare);
3325 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3326 WARN("SPACING",
3327 "missing space after return type\n" . $herecurr);
3328 $post_declare_space = " ";
3331 # unnecessary space "type (*funcptr)(args...)"
3332 # This test is not currently implemented because these declarations are
3333 # equivalent to
3334 # int foo(int bar, ...)
3335 # and this is form shouldn't/doesn't generate a checkpatch warning.
3337 # elsif ($declare =~ /\s{2,}$/) {
3338 # WARN("SPACING",
3339 # "Multiple spaces after return type\n" . $herecurr);
3342 # unnecessary space "type ( *funcptr)(args...)"
3343 if (defined $pre_pointer_space &&
3344 $pre_pointer_space =~ /^\s/) {
3345 WARN("SPACING",
3346 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3349 # unnecessary space "type (* funcptr)(args...)"
3350 if (defined $post_pointer_space &&
3351 $post_pointer_space =~ /^\s/) {
3352 WARN("SPACING",
3353 "Unnecessary space before function pointer name\n" . $herecurr);
3356 # unnecessary space "type (*funcptr )(args...)"
3357 if (defined $post_funcname_space &&
3358 $post_funcname_space =~ /^\s/) {
3359 WARN("SPACING",
3360 "Unnecessary space after function pointer name\n" . $herecurr);
3363 # unnecessary space "type (*funcptr) (args...)"
3364 if (defined $pre_args_space &&
3365 $pre_args_space =~ /^\s/) {
3366 WARN("SPACING",
3367 "Unnecessary space before function pointer arguments\n" . $herecurr);
3370 if (show_type("SPACING") && $fix) {
3371 $fixed[$fixlinenr] =~
3372 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3376 # check for spacing round square brackets; allowed:
3377 # 1. with a type on the left -- int [] a;
3378 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3379 # 3. inside a curly brace -- = { [0...10] = 5 }
3380 while ($line =~ /(.*?\s)\[/g) {
3381 my ($where, $prefix) = ($-[1], $1);
3382 if ($prefix !~ /$Type\s+$/ &&
3383 ($where != 0 || $prefix !~ /^.\s+$/) &&
3384 $prefix !~ /[{,]\s+$/) {
3385 if (ERROR("BRACKET_SPACE",
3386 "space prohibited before open square bracket '['\n" . $herecurr) &&
3387 $fix) {
3388 $fixed[$fixlinenr] =~
3389 s/^(\+.*?)\s+\[/$1\[/;
3394 # check for spaces between functions and their parentheses.
3395 while ($line =~ /($Ident)\s+\(/g) {
3396 my $name = $1;
3397 my $ctx_before = substr($line, 0, $-[1]);
3398 my $ctx = "$ctx_before$name";
3400 # Ignore those directives where spaces _are_ permitted.
3401 if ($name =~ /^(?:
3402 if|for|while|switch|return|case|
3403 volatile|__volatile__|
3404 __attribute__|format|__extension__|
3405 asm|__asm__)$/x)
3407 # cpp #define statements have non-optional spaces, ie
3408 # if there is a space between the name and the open
3409 # parenthesis it is simply not a parameter group.
3410 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3412 # cpp #elif statement condition may start with a (
3413 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3415 # If this whole things ends with a type its most
3416 # likely a typedef for a function.
3417 } elsif ($ctx =~ /$Type$/) {
3419 } else {
3420 if (WARN("SPACING",
3421 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3422 $fix) {
3423 $fixed[$fixlinenr] =~
3424 s/\b$name\s+\(/$name\(/;
3429 # Check operator spacing.
3430 if (!($line=~/\#\s*include/)) {
3431 my $fixed_line = "";
3432 my $line_fixed = 0;
3434 my $ops = qr{
3435 <<=|>>=|<=|>=|==|!=|
3436 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3437 =>|->|<<|>>|<|>|=|!|~|
3438 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3439 \?:|\?|:
3441 my @elements = split(/($ops|;)/, $opline);
3443 ## print("element count: <" . $#elements . ">\n");
3444 ## foreach my $el (@elements) {
3445 ## print("el: <$el>\n");
3446 ## }
3448 my @fix_elements = ();
3449 my $off = 0;
3451 foreach my $el (@elements) {
3452 push(@fix_elements, substr($rawline, $off, length($el)));
3453 $off += length($el);
3456 $off = 0;
3458 my $blank = copy_spacing($opline);
3459 my $last_after = -1;
3461 for (my $n = 0; $n < $#elements; $n += 2) {
3463 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3465 ## print("n: <$n> good: <$good>\n");
3467 $off += length($elements[$n]);
3469 # Pick up the preceding and succeeding characters.
3470 my $ca = substr($opline, 0, $off);
3471 my $cc = '';
3472 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3473 $cc = substr($opline, $off + length($elements[$n + 1]));
3475 my $cb = "$ca$;$cc";
3477 my $a = '';
3478 $a = 'V' if ($elements[$n] ne '');
3479 $a = 'W' if ($elements[$n] =~ /\s$/);
3480 $a = 'C' if ($elements[$n] =~ /$;$/);
3481 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3482 $a = 'O' if ($elements[$n] eq '');
3483 $a = 'E' if ($ca =~ /^\s*$/);
3485 my $op = $elements[$n + 1];
3487 my $c = '';
3488 if (defined $elements[$n + 2]) {
3489 $c = 'V' if ($elements[$n + 2] ne '');
3490 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3491 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3492 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3493 $c = 'O' if ($elements[$n + 2] eq '');
3494 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3495 } else {
3496 $c = 'E';
3499 my $ctx = "${a}x${c}";
3501 my $at = "(ctx:$ctx)";
3503 my $ptr = substr($blank, 0, $off) . "^";
3504 my $hereptr = "$hereline$ptr\n";
3506 # Pull out the value of this operator.
3507 my $op_type = substr($curr_values, $off + 1, 1);
3509 # Get the full operator variant.
3510 my $opv = $op . substr($curr_vars, $off, 1);
3512 # Ignore operators passed as parameters.
3513 if ($op_type ne 'V' &&
3514 $ca =~ /\s$/ && $cc =~ /^\s*,/) {
3516 # # Ignore comments
3517 # } elsif ($op =~ /^$;+$/) {
3519 # ; should have either the end of line or a space or \ after it
3520 } elsif ($op eq ';') {
3521 if ($ctx !~ /.x[WEBC]/ &&
3522 $cc !~ /^\\/ && $cc !~ /^;/) {
3523 if (ERROR("SPACING",
3524 "space required after that '$op' $at\n" . $hereptr)) {
3525 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3526 $line_fixed = 1;
3530 # // is a comment
3531 } elsif ($op eq '//') {
3533 # : when part of a bitfield
3534 } elsif ($opv eq ':B') {
3535 # skip the bitfield test for now
3537 # No spaces for:
3538 # ->
3539 } elsif ($op eq '->') {
3540 if ($ctx =~ /Wx.|.xW/) {
3541 if (ERROR("SPACING",
3542 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3543 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3544 if (defined $fix_elements[$n + 2]) {
3545 $fix_elements[$n + 2] =~ s/^\s+//;
3547 $line_fixed = 1;
3551 # , must not have a space before and must have a space on the right.
3552 } elsif ($op eq ',') {
3553 my $rtrim_before = 0;
3554 my $space_after = 0;
3555 if ($ctx =~ /Wx./) {
3556 if (ERROR("SPACING",
3557 "space prohibited before that '$op' $at\n" . $hereptr)) {
3558 $line_fixed = 1;
3559 $rtrim_before = 1;
3562 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3563 if (ERROR("SPACING",
3564 "space required after that '$op' $at\n" . $hereptr)) {
3565 $line_fixed = 1;
3566 $last_after = $n;
3567 $space_after = 1;
3570 if ($rtrim_before || $space_after) {
3571 if ($rtrim_before) {
3572 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3573 } else {
3574 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3576 if ($space_after) {
3577 $good .= " ";
3581 # '*' as part of a type definition -- reported already.
3582 } elsif ($opv eq '*_') {
3583 #warn "'*' is part of type\n";
3585 # unary operators should have a space before and
3586 # none after. May be left adjacent to another
3587 # unary operator, or a cast
3588 } elsif ($op eq '!' || $op eq '~' ||
3589 $opv eq '*U' || $opv eq '-U' ||
3590 $opv eq '&U' || $opv eq '&&U') {
3591 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3592 if (ERROR("SPACING",
3593 "space required before that '$op' $at\n" . $hereptr)) {
3594 if ($n != $last_after + 2) {
3595 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3596 $line_fixed = 1;
3600 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3601 # A unary '*' may be const
3603 } elsif ($ctx =~ /.xW/) {
3604 if (ERROR("SPACING",
3605 "space prohibited after that '$op' $at\n" . $hereptr)) {
3606 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3607 if (defined $fix_elements[$n + 2]) {
3608 $fix_elements[$n + 2] =~ s/^\s+//;
3610 $line_fixed = 1;
3614 # unary ++ and unary -- are allowed no space on one side.
3615 } elsif ($op eq '++' or $op eq '--') {
3616 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3617 if (ERROR("SPACING",
3618 "space required one side of that '$op' $at\n" . $hereptr)) {
3619 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3620 $line_fixed = 1;
3623 if ($ctx =~ /Wx[BE]/ ||
3624 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3625 if (ERROR("SPACING",
3626 "space prohibited before that '$op' $at\n" . $hereptr)) {
3627 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3628 $line_fixed = 1;
3631 if ($ctx =~ /ExW/) {
3632 if (ERROR("SPACING",
3633 "space prohibited after that '$op' $at\n" . $hereptr)) {
3634 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3635 if (defined $fix_elements[$n + 2]) {
3636 $fix_elements[$n + 2] =~ s/^\s+//;
3638 $line_fixed = 1;
3642 # << and >> may either have or not have spaces both sides
3643 } elsif ($op eq '<<' or $op eq '>>' or
3644 $op eq '&' or $op eq '^' or $op eq '|' or
3645 $op eq '+' or $op eq '-' or
3646 $op eq '*' or $op eq '/' or
3647 $op eq '%')
3649 if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3650 if (ERROR("SPACING",
3651 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3652 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3653 if (defined $fix_elements[$n + 2]) {
3654 $fix_elements[$n + 2] =~ s/^\s+//;
3656 $line_fixed = 1;
3660 # A colon needs no spaces before when it is
3661 # terminating a case value or a label.
3662 } elsif ($opv eq ':C' || $opv eq ':L') {
3663 if ($ctx =~ /Wx./) {
3664 if (ERROR("SPACING",
3665 "space prohibited before that '$op' $at\n" . $hereptr)) {
3666 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3667 $line_fixed = 1;
3671 # All the others need spaces both sides.
3672 } elsif ($ctx !~ /[EWC]x[CWE]/) {
3673 my $ok = 0;
3675 # Ignore email addresses <foo@bar>
3676 if (($op eq '<' &&
3677 $cc =~ /^\S+\@\S+>/) ||
3678 ($op eq '>' &&
3679 $ca =~ /<\S+\@\S+$/))
3681 $ok = 1;
3684 # messages are ERROR, but ?: are CHK
3685 if ($ok == 0) {
3686 my $msg_type = \&ERROR;
3687 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
3689 if (&{$msg_type}("SPACING",
3690 "spaces required around that '$op' $at\n" . $hereptr)) {
3691 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3692 if (defined $fix_elements[$n + 2]) {
3693 $fix_elements[$n + 2] =~ s/^\s+//;
3695 $line_fixed = 1;
3699 $off += length($elements[$n + 1]);
3701 ## print("n: <$n> GOOD: <$good>\n");
3703 $fixed_line = $fixed_line . $good;
3706 if (($#elements % 2) == 0) {
3707 $fixed_line = $fixed_line . $fix_elements[$#elements];
3710 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
3711 $fixed[$fixlinenr] = $fixed_line;
3717 # check for whitespace before a non-naked semicolon
3718 if ($line =~ /^\+.*\S\s+;\s*$/) {
3719 if (WARN("SPACING",
3720 "space prohibited before semicolon\n" . $herecurr) &&
3721 $fix) {
3722 1 while $fixed[$fixlinenr] =~
3723 s/^(\+.*\S)\s+;/$1;/;
3727 # check for multiple assignments
3728 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
3729 CHK("MULTIPLE_ASSIGNMENTS",
3730 "multiple assignments should be avoided\n" . $herecurr);
3733 ## # check for multiple declarations, allowing for a function declaration
3734 ## # continuation.
3735 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
3736 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
3738 ## # Remove any bracketed sections to ensure we do not
3739 ## # falsly report the parameters of functions.
3740 ## my $ln = $line;
3741 ## while ($ln =~ s/\([^\(\)]*\)//g) {
3742 ## }
3743 ## if ($ln =~ /,/) {
3744 ## WARN("MULTIPLE_DECLARATION",
3745 ## "declaring multiple variables together should be avoided\n" . $herecurr);
3746 ## }
3747 ## }
3749 #need space before brace following if, while, etc
3750 if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
3751 $line =~ /do{/) {
3752 if (ERROR("SPACING",
3753 "space required before the open brace '{'\n" . $herecurr) &&
3754 $fix) {
3755 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
3759 ## # check for blank lines before declarations
3760 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
3761 ## $prevrawline =~ /^.\s*$/) {
3762 ## WARN("SPACING",
3763 ## "No blank lines before declarations\n" . $hereprev);
3764 ## }
3767 # closing brace should have a space following it when it has anything
3768 # on the line
3769 if ($line =~ /}(?!(?:,|;|\)))\S/) {
3770 if (ERROR("SPACING",
3771 "space required after that close brace '}'\n" . $herecurr) &&
3772 $fix) {
3773 $fixed[$fixlinenr] =~
3774 s/}((?!(?:,|;|\)))\S)/} $1/;
3778 # check spacing on square brackets
3779 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
3780 if (ERROR("SPACING",
3781 "space prohibited after that open square bracket '['\n" . $herecurr) &&
3782 $fix) {
3783 $fixed[$fixlinenr] =~
3784 s/\[\s+/\[/;
3787 if ($line =~ /\s\]/) {
3788 if (ERROR("SPACING",
3789 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
3790 $fix) {
3791 $fixed[$fixlinenr] =~
3792 s/\s+\]/\]/;
3796 # check spacing on parentheses
3797 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
3798 $line !~ /for\s*\(\s+;/) {
3799 if (ERROR("SPACING",
3800 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
3801 $fix) {
3802 $fixed[$fixlinenr] =~
3803 s/\(\s+/\(/;
3806 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
3807 $line !~ /for\s*\(.*;\s+\)/ &&
3808 $line !~ /:\s+\)/) {
3809 if (ERROR("SPACING",
3810 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
3811 $fix) {
3812 $fixed[$fixlinenr] =~
3813 s/\s+\)/\)/;
3817 # check unnecessary parentheses around addressof/dereference single $Lvals
3818 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
3820 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
3821 my $var = $1;
3822 if (CHK("UNNECESSARY_PARENTHESES",
3823 "Unnecessary parentheses around $var\n" . $herecurr) &&
3824 $fix) {
3825 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
3829 # check for unnecessary parentheses around function pointer uses
3830 # ie: (foo->bar)(); should be foo->bar();
3831 # but not "if (foo->bar) (" to avoid some false positives
3832 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
3833 my $var = $2;
3834 if (CHK("UNNECESSARY_PARENTHESES",
3835 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
3836 $fix) {
3837 my $var2 = deparenthesize($var);
3838 $var2 =~ s/\s//g;
3839 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
3843 #goto labels aren't indented, allow a single space however
3844 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
3845 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
3846 if (WARN("INDENTED_LABEL",
3847 "labels should not be indented\n" . $herecurr) &&
3848 $fix) {
3849 $fixed[$fixlinenr] =~
3850 s/^(.)\s+/$1/;
3854 # return is not a function
3855 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
3856 my $spacing = $1;
3857 if ($^V && $^V ge 5.10.0 &&
3858 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
3859 my $value = $1;
3860 $value = deparenthesize($value);
3861 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
3862 ERROR("RETURN_PARENTHESES",
3863 "return is not a function, parentheses are not required\n" . $herecurr);
3865 } elsif ($spacing !~ /\s+/) {
3866 ERROR("SPACING",
3867 "space required before the open parenthesis '('\n" . $herecurr);
3871 # unnecessary return in a void function
3872 # at end-of-function, with the previous line a single leading tab, then return;
3873 # and the line before that not a goto label target like "out:"
3874 if ($sline =~ /^[ \+]}\s*$/ &&
3875 $prevline =~ /^\+\treturn\s*;\s*$/ &&
3876 $linenr >= 3 &&
3877 $lines[$linenr - 3] =~ /^[ +]/ &&
3878 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
3879 WARN("RETURN_VOID",
3880 "void function return statements are not generally useful\n" . $hereprev);
3883 # if statements using unnecessary parentheses - ie: if ((foo == bar))
3884 if ($^V && $^V ge 5.10.0 &&
3885 $line =~ /\bif\s*((?:\(\s*){2,})/) {
3886 my $openparens = $1;
3887 my $count = $openparens =~ tr@\(@\(@;
3888 my $msg = "";
3889 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
3890 my $comp = $4; #Not $1 because of $LvalOrFunc
3891 $msg = " - maybe == should be = ?" if ($comp eq "==");
3892 WARN("UNNECESSARY_PARENTHESES",
3893 "Unnecessary parentheses$msg\n" . $herecurr);
3897 # Return of what appears to be an errno should normally be -'ve
3898 if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
3899 my $name = $1;
3900 if ($name ne 'EOF' && $name ne 'ERROR') {
3901 WARN("USE_NEGATIVE_ERRNO",
3902 "return of an errno should typically be -ve (return -$1)\n" . $herecurr);
3906 # Need a space before open parenthesis after if, while etc
3907 if ($line =~ /\b(if|while|for|switch)\(/) {
3908 if (ERROR("SPACING",
3909 "space required before the open parenthesis '('\n" . $herecurr) &&
3910 $fix) {
3911 $fixed[$fixlinenr] =~
3912 s/\b(if|while|for|switch)\(/$1 \(/;
3916 # Check for illegal assignment in if conditional -- and check for trailing
3917 # statements after the conditional.
3918 if ($line =~ /do\s*(?!{)/) {
3919 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3920 ctx_statement_block($linenr, $realcnt, 0)
3921 if (!defined $stat);
3922 my ($stat_next) = ctx_statement_block($line_nr_next,
3923 $remain_next, $off_next);
3924 $stat_next =~ s/\n./\n /g;
3925 ##print "stat<$stat> stat_next<$stat_next>\n";
3927 if ($stat_next =~ /^\s*while\b/) {
3928 # If the statement carries leading newlines,
3929 # then count those as offsets.
3930 my ($whitespace) =
3931 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
3932 my $offset =
3933 statement_rawlines($whitespace) - 1;
3935 $suppress_whiletrailers{$line_nr_next +
3936 $offset} = 1;
3939 if (!defined $suppress_whiletrailers{$linenr} &&
3940 defined($stat) && defined($cond) &&
3941 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
3942 my ($s, $c) = ($stat, $cond);
3944 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
3945 ERROR("ASSIGN_IN_IF",
3946 "do not use assignment in if condition\n" . $herecurr);
3949 # Find out what is on the end of the line after the
3950 # conditional.
3951 substr($s, 0, length($c), '');
3952 $s =~ s/\n.*//g;
3953 $s =~ s/$;//g; # Remove any comments
3954 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
3955 $c !~ /}\s*while\s*/)
3957 # Find out how long the conditional actually is.
3958 my @newlines = ($c =~ /\n/gs);
3959 my $cond_lines = 1 + $#newlines;
3960 my $stat_real = '';
3962 $stat_real = raw_line($linenr, $cond_lines)
3963 . "\n" if ($cond_lines);
3964 if (defined($stat_real) && $cond_lines > 1) {
3965 $stat_real = "[...]\n$stat_real";
3968 ERROR("TRAILING_STATEMENTS",
3969 "trailing statements should be on next line\n" . $herecurr . $stat_real);
3973 # Check for bitwise tests written as boolean
3974 if ($line =~ /
3976 (?:\[|\(|\&\&|\|\|)
3977 \s*0[xX][0-9]+\s*
3978 (?:\&\&|\|\|)
3980 (?:\&\&|\|\|)
3981 \s*0[xX][0-9]+\s*
3982 (?:\&\&|\|\||\)|\])
3983 )/x)
3985 WARN("HEXADECIMAL_BOOLEAN_TEST",
3986 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
3989 # if and else should not have general statements after it
3990 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
3991 my $s = $1;
3992 $s =~ s/$;//g; # Remove any comments
3993 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
3994 ERROR("TRAILING_STATEMENTS",
3995 "trailing statements should be on next line\n" . $herecurr);
3998 # if should not continue a brace
3999 if ($line =~ /}\s*if\b/) {
4000 ERROR("TRAILING_STATEMENTS",
4001 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4002 $herecurr);
4004 # case and default should not have general statements after them
4005 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4006 $line !~ /\G(?:
4007 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4008 \s*return\s+
4009 )/xg)
4011 ERROR("TRAILING_STATEMENTS",
4012 "trailing statements should be on next line\n" . $herecurr);
4015 # Check for }<nl>else {, these must be at the same
4016 # indent level to be relevant to each other.
4017 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4018 $previndent == $indent) {
4019 if (ERROR("ELSE_AFTER_BRACE",
4020 "else should follow close brace '}'\n" . $hereprev) &&
4021 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4022 fix_delete_line($fixlinenr - 1, $prevrawline);
4023 fix_delete_line($fixlinenr, $rawline);
4024 my $fixedline = $prevrawline;
4025 $fixedline =~ s/}\s*$//;
4026 if ($fixedline !~ /^\+\s*$/) {
4027 fix_insert_line($fixlinenr, $fixedline);
4029 $fixedline = $rawline;
4030 $fixedline =~ s/^(.\s*)else/$1} else/;
4031 fix_insert_line($fixlinenr, $fixedline);
4035 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4036 $previndent == $indent) {
4037 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4039 # Find out what is on the end of the line after the
4040 # conditional.
4041 substr($s, 0, length($c), '');
4042 $s =~ s/\n.*//g;
4044 if ($s =~ /^\s*;/) {
4045 if (ERROR("WHILE_AFTER_BRACE",
4046 "while should follow close brace '}'\n" . $hereprev) &&
4047 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4048 fix_delete_line($fixlinenr - 1, $prevrawline);
4049 fix_delete_line($fixlinenr, $rawline);
4050 my $fixedline = $prevrawline;
4051 my $trailing = $rawline;
4052 $trailing =~ s/^\+//;
4053 $trailing = trim($trailing);
4054 $fixedline =~ s/}\s*$/} $trailing/;
4055 fix_insert_line($fixlinenr, $fixedline);
4060 #Specific variable tests
4061 while ($line =~ m{($Constant|$Lval)}g) {
4062 my $var = $1;
4064 #gcc binary extension
4065 if ($var =~ /^$Binary$/) {
4066 if (WARN("GCC_BINARY_CONSTANT",
4067 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4068 $fix) {
4069 my $hexval = sprintf("0x%x", oct($var));
4070 $fixed[$fixlinenr] =~
4071 s/\b$var\b/$hexval/;
4075 #CamelCase
4076 if ($var !~ /^$Constant$/ &&
4077 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4078 #Ignore Page<foo> variants
4079 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4080 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4081 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4082 #Ignore some three character SI units explicitly, like MiB and KHz
4083 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4084 while ($var =~ m{($Ident)}g) {
4085 my $word = $1;
4086 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4087 if ($check) {
4088 seed_camelcase_includes();
4089 if (!$file && !$camelcase_file_seeded) {
4090 seed_camelcase_file($realfile);
4091 $camelcase_file_seeded = 1;
4094 if (!defined $camelcase{$word}) {
4095 $camelcase{$word} = 1;
4096 CHK("CAMELCASE",
4097 "Avoid CamelCase: <$word>\n" . $herecurr);
4103 #no spaces allowed after \ in define
4104 if ($line =~ /\#\s*define.*\\\s+$/) {
4105 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4106 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4107 $fix) {
4108 $fixed[$fixlinenr] =~ s/\s+$//;
4112 #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
4113 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4114 my $file = "$1.h";
4115 my $checkfile = "include/linux/$file";
4116 if (-f "$root/$checkfile" &&
4117 $realfile ne $checkfile &&
4118 $1 !~ /$allowed_asm_includes/)
4120 if ($realfile =~ m{^arch/}) {
4121 CHK("ARCH_INCLUDE_LINUX",
4122 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4123 } else {
4124 WARN("INCLUDE_LINUX",
4125 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4130 # multi-statement macros should be enclosed in a do while loop, grab the
4131 # first statement and ensure its the whole macro if its not enclosed
4132 # in a known good container
4133 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4134 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4135 my $ln = $linenr;
4136 my $cnt = $realcnt;
4137 my ($off, $dstat, $dcond, $rest);
4138 my $ctx = '';
4139 my $has_flow_statement = 0;
4140 my $has_arg_concat = 0;
4141 ($dstat, $dcond, $ln, $cnt, $off) =
4142 ctx_statement_block($linenr, $realcnt, 0);
4143 $ctx = $dstat;
4144 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4145 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4147 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4148 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4150 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4151 $dstat =~ s/$;//g;
4152 $dstat =~ s/\\\n.//g;
4153 $dstat =~ s/^\s*//s;
4154 $dstat =~ s/\s*$//s;
4156 # Flatten any parentheses and braces
4157 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4158 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4159 $dstat =~ s/\[[^\[\]]*\]/1/)
4163 # Flatten any obvious string concatentation.
4164 while ($dstat =~ s/("X*")\s*$Ident/$1/ ||
4165 $dstat =~ s/$Ident\s*("X*")/$1/)
4169 my $exceptions = qr{
4170 $Declare|
4171 module_param_named|
4172 MODULE_PARM_DESC|
4173 DECLARE_PER_CPU|
4174 DEFINE_PER_CPU|
4175 __typeof__\(|
4176 union|
4177 struct|
4178 \.$Ident\s*=\s*|
4179 ^\"|\"$
4181 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4182 if ($dstat ne '' &&
4183 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4184 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4185 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4186 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4187 $dstat !~ /$exceptions/ &&
4188 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4189 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4190 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4191 $dstat !~ /^for\s*$Constant$/ && # for (...)
4192 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4193 $dstat !~ /^do\s*{/ && # do {...
4194 $dstat !~ /^\({/ && # ({...
4195 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4197 $ctx =~ s/\n*$//;
4198 my $herectx = $here . "\n";
4199 my $cnt = statement_rawlines($ctx);
4201 for (my $n = 0; $n < $cnt; $n++) {
4202 $herectx .= raw_line($linenr, $n) . "\n";
4205 if ($dstat =~ /;/) {
4206 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4207 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4208 } else {
4209 ERROR("COMPLEX_MACRO",
4210 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4214 # check for macros with flow control, but without ## concatenation
4215 # ## concatenation is commonly a macro that defines a function so ignore those
4216 if ($has_flow_statement && !$has_arg_concat) {
4217 my $herectx = $here . "\n";
4218 my $cnt = statement_rawlines($ctx);
4220 for (my $n = 0; $n < $cnt; $n++) {
4221 $herectx .= raw_line($linenr, $n) . "\n";
4223 WARN("MACRO_WITH_FLOW_CONTROL",
4224 "Macros with flow control statements should be avoided\n" . "$herectx");
4227 # check for line continuations outside of #defines, preprocessor #, and asm
4229 } else {
4230 if ($prevline !~ /^..*\\$/ &&
4231 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4232 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4233 $line =~ /^\+.*\\$/) {
4234 WARN("LINE_CONTINUATIONS",
4235 "Avoid unnecessary line continuations\n" . $herecurr);
4239 # do {} while (0) macro tests:
4240 # single-statement macros do not need to be enclosed in do while (0) loop,
4241 # macro should not end with a semicolon
4242 if ($^V && $^V ge 5.10.0 &&
4243 $realfile !~ m@/vmlinux.lds.h$@ &&
4244 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4245 my $ln = $linenr;
4246 my $cnt = $realcnt;
4247 my ($off, $dstat, $dcond, $rest);
4248 my $ctx = '';
4249 ($dstat, $dcond, $ln, $cnt, $off) =
4250 ctx_statement_block($linenr, $realcnt, 0);
4251 $ctx = $dstat;
4253 $dstat =~ s/\\\n.//g;
4255 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4256 my $stmts = $2;
4257 my $semis = $3;
4259 $ctx =~ s/\n*$//;
4260 my $cnt = statement_rawlines($ctx);
4261 my $herectx = $here . "\n";
4263 for (my $n = 0; $n < $cnt; $n++) {
4264 $herectx .= raw_line($linenr, $n) . "\n";
4267 if (($stmts =~ tr/;/;/) == 1 &&
4268 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4269 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4270 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4272 if (defined $semis && $semis ne "") {
4273 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4274 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4276 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4277 $ctx =~ s/\n*$//;
4278 my $cnt = statement_rawlines($ctx);
4279 my $herectx = $here . "\n";
4281 for (my $n = 0; $n < $cnt; $n++) {
4282 $herectx .= raw_line($linenr, $n) . "\n";
4285 WARN("TRAILING_SEMICOLON",
4286 "macros should not use a trailing semicolon\n" . "$herectx");
4290 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4291 # all assignments may have only one of the following with an assignment:
4293 # ALIGN(...)
4294 # VMLINUX_SYMBOL(...)
4295 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4296 WARN("MISSING_VMLINUX_SYMBOL",
4297 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4300 # check for redundant bracing round if etc
4301 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4302 my ($level, $endln, @chunks) =
4303 ctx_statement_full($linenr, $realcnt, 1);
4304 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4305 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4306 if ($#chunks > 0 && $level == 0) {
4307 my @allowed = ();
4308 my $allow = 0;
4309 my $seen = 0;
4310 my $herectx = $here . "\n";
4311 my $ln = $linenr - 1;
4312 for my $chunk (@chunks) {
4313 my ($cond, $block) = @{$chunk};
4315 # If the condition carries leading newlines, then count those as offsets.
4316 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4317 my $offset = statement_rawlines($whitespace) - 1;
4319 $allowed[$allow] = 0;
4320 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4322 # We have looked at and allowed this specific line.
4323 $suppress_ifbraces{$ln + $offset} = 1;
4325 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4326 $ln += statement_rawlines($block) - 1;
4328 substr($block, 0, length($cond), '');
4330 $seen++ if ($block =~ /^\s*{/);
4332 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4333 if (statement_lines($cond) > 1) {
4334 #print "APW: ALLOWED: cond<$cond>\n";
4335 $allowed[$allow] = 1;
4337 if ($block =~/\b(?:if|for|while)\b/) {
4338 #print "APW: ALLOWED: block<$block>\n";
4339 $allowed[$allow] = 1;
4341 if (statement_block_size($block) > 1) {
4342 #print "APW: ALLOWED: lines block<$block>\n";
4343 $allowed[$allow] = 1;
4345 $allow++;
4347 if ($seen) {
4348 my $sum_allowed = 0;
4349 foreach (@allowed) {
4350 $sum_allowed += $_;
4352 if ($sum_allowed == 0) {
4353 WARN("BRACES",
4354 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4355 } elsif ($sum_allowed != $allow &&
4356 $seen != $allow) {
4357 CHK("BRACES",
4358 "braces {} should be used on all arms of this statement\n" . $herectx);
4363 if (!defined $suppress_ifbraces{$linenr - 1} &&
4364 $line =~ /\b(if|while|for|else)\b/) {
4365 my $allowed = 0;
4367 # Check the pre-context.
4368 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4369 #print "APW: ALLOWED: pre<$1>\n";
4370 $allowed = 1;
4373 my ($level, $endln, @chunks) =
4374 ctx_statement_full($linenr, $realcnt, $-[0]);
4376 # Check the condition.
4377 my ($cond, $block) = @{$chunks[0]};
4378 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4379 if (defined $cond) {
4380 substr($block, 0, length($cond), '');
4382 if (statement_lines($cond) > 1) {
4383 #print "APW: ALLOWED: cond<$cond>\n";
4384 $allowed = 1;
4386 if ($block =~/\b(?:if|for|while)\b/) {
4387 #print "APW: ALLOWED: block<$block>\n";
4388 $allowed = 1;
4390 if (statement_block_size($block) > 1) {
4391 #print "APW: ALLOWED: lines block<$block>\n";
4392 $allowed = 1;
4394 # Check the post-context.
4395 if (defined $chunks[1]) {
4396 my ($cond, $block) = @{$chunks[1]};
4397 if (defined $cond) {
4398 substr($block, 0, length($cond), '');
4400 if ($block =~ /^\s*\{/) {
4401 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4402 $allowed = 1;
4405 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4406 my $herectx = $here . "\n";
4407 my $cnt = statement_rawlines($block);
4409 for (my $n = 0; $n < $cnt; $n++) {
4410 $herectx .= raw_line($linenr, $n) . "\n";
4413 WARN("BRACES",
4414 "braces {} are not necessary for single statement blocks\n" . $herectx);
4418 # check for unnecessary blank lines around braces
4419 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4420 CHK("BRACES",
4421 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev);
4423 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4424 CHK("BRACES",
4425 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev);
4428 # no volatiles please
4429 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4430 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4431 WARN("VOLATILE",
4432 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4435 # Check for user-visible strings broken across lines, which breaks the ability
4436 # to grep for the string. Make exceptions when the previous string ends in a
4437 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4438 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4439 if ($line =~ /^\+\s*"[X\t]*"/ &&
4440 $prevline =~ /"\s*$/ &&
4441 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4442 if (WARN("SPLIT_STRING",
4443 "quoted string split across lines\n" . $hereprev) &&
4444 $fix &&
4445 $prevrawline =~ /^\+.*"\s*$/ &&
4446 $last_coalesced_string_linenr != $linenr - 1) {
4447 my $extracted_string = get_quoted_string($line, $rawline);
4448 my $comma_close = "";
4449 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4450 $comma_close = $1;
4453 fix_delete_line($fixlinenr - 1, $prevrawline);
4454 fix_delete_line($fixlinenr, $rawline);
4455 my $fixedline = $prevrawline;
4456 $fixedline =~ s/"\s*$//;
4457 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4458 fix_insert_line($fixlinenr - 1, $fixedline);
4459 $fixedline = $rawline;
4460 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4461 if ($fixedline !~ /\+\s*$/) {
4462 fix_insert_line($fixlinenr, $fixedline);
4464 $last_coalesced_string_linenr = $linenr;
4468 # check for missing a space in a string concatenation
4469 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4470 WARN('MISSING_SPACE',
4471 "break quoted strings at a space character\n" . $hereprev);
4474 # check for spaces before a quoted newline
4475 if ($rawline =~ /^.*\".*\s\\n/) {
4476 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4477 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4478 $fix) {
4479 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4484 # concatenated string without spaces between elements
4485 if ($line =~ /"X+"[A-Z_]+/ || $line =~ /[A-Z_]+"X+"/) {
4486 CHK("CONCATENATED_STRING",
4487 "Concatenated strings should use spaces between elements\n" . $herecurr);
4490 # uncoalesced string fragments
4491 if ($line =~ /"X*"\s*"/) {
4492 WARN("STRING_FRAGMENTS",
4493 "Consecutive strings are generally better as a single string\n" . $herecurr);
4496 # check for %L{u,d,i} in strings
4497 my $string;
4498 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4499 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4500 $string =~ s/%%/__/g;
4501 if ($string =~ /(?<!%)%L[udi]/) {
4502 WARN("PRINTF_L",
4503 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4504 last;
4508 # check for line continuations in quoted strings with odd counts of "
4509 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4510 WARN("LINE_CONTINUATIONS",
4511 "Avoid line continuations in quoted strings\n" . $herecurr);
4514 # warn about #if 0
4515 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4516 CHK("REDUNDANT_CODE",
4517 "if this code is redundant consider removing it\n" .
4518 $herecurr);
4521 # check for needless "if (<foo>) fn(<foo>)" uses
4522 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4523 my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;';
4524 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) {
4525 WARN('NEEDLESS_IF',
4526 "$1(NULL) is safe and this check is probably not required\n" . $hereprev);
4530 # check for unnecessary "Out of Memory" messages
4531 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4532 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4533 (defined $1 || defined $3) &&
4534 $linenr > 3) {
4535 my $testval = $2;
4536 my $testline = $lines[$linenr - 3];
4538 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4539 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4541 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4542 WARN("OOM_MESSAGE",
4543 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4547 # check for logging functions with KERN_<LEVEL>
4548 if ($line !~ /printk\s*\(/ &&
4549 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4550 my $level = $1;
4551 if (WARN("UNNECESSARY_KERN_LEVEL",
4552 "Possible unnecessary $level\n" . $herecurr) &&
4553 $fix) {
4554 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4558 # check for mask then right shift without a parentheses
4559 if ($^V && $^V ge 5.10.0 &&
4560 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4561 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4562 WARN("MASK_THEN_SHIFT",
4563 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4566 # check for pointer comparisons to NULL
4567 if ($^V && $^V ge 5.10.0) {
4568 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4569 my $val = $1;
4570 my $equal = "!";
4571 $equal = "" if ($4 eq "!=");
4572 if (CHK("COMPARISON_TO_NULL",
4573 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4574 $fix) {
4575 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4580 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4581 if ($line =~ /(\b$InitAttribute\b)/) {
4582 my $attr = $1;
4583 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
4584 my $ptr = $1;
4585 my $var = $2;
4586 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
4587 ERROR("MISPLACED_INIT",
4588 "$attr should be placed after $var\n" . $herecurr)) ||
4589 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
4590 WARN("MISPLACED_INIT",
4591 "$attr should be placed after $var\n" . $herecurr))) &&
4592 $fix) {
4593 $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;
4598 # check for $InitAttributeData (ie: __initdata) with const
4599 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
4600 my $attr = $1;
4601 $attr =~ /($InitAttributePrefix)(.*)/;
4602 my $attr_prefix = $1;
4603 my $attr_type = $2;
4604 if (ERROR("INIT_ATTRIBUTE",
4605 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
4606 $fix) {
4607 $fixed[$fixlinenr] =~
4608 s/$InitAttributeData/${attr_prefix}initconst/;
4612 # check for $InitAttributeConst (ie: __initconst) without const
4613 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
4614 my $attr = $1;
4615 if (ERROR("INIT_ATTRIBUTE",
4616 "Use of $attr requires a separate use of const\n" . $herecurr) &&
4617 $fix) {
4618 my $lead = $fixed[$fixlinenr] =~
4619 /(^\+\s*(?:static\s+))/;
4620 $lead = rtrim($1);
4621 $lead = "$lead " if ($lead !~ /^\+$/);
4622 $lead = "${lead}const ";
4623 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
4627 # don't use __constant_<foo> functions outside of include/uapi/
4628 if ($realfile !~ m@^include/uapi/@ &&
4629 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
4630 my $constant_func = $1;
4631 my $func = $constant_func;
4632 $func =~ s/^__constant_//;
4633 if (WARN("CONSTANT_CONVERSION",
4634 "$constant_func should be $func\n" . $herecurr) &&
4635 $fix) {
4636 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
4640 # prefer usleep_range over udelay
4641 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
4642 my $delay = $1;
4643 # ignore udelay's < 10, however
4644 if (! ($delay < 10) ) {
4645 CHK("USLEEP_RANGE",
4646 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4648 if ($delay > 2000) {
4649 WARN("LONG_UDELAY",
4650 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
4654 # warn about unexpectedly long msleep's
4655 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
4656 if ($1 < 20) {
4657 WARN("MSLEEP",
4658 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
4662 # check for comparisons of jiffies
4663 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
4664 WARN("JIFFIES_COMPARISON",
4665 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
4668 # check for comparisons of get_jiffies_64()
4669 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
4670 WARN("JIFFIES_COMPARISON",
4671 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
4674 # warn about #ifdefs in C files
4675 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
4676 # print "#ifdef in C files should be avoided\n";
4677 # print "$herecurr";
4678 # $clean = 0;
4681 # warn about spacing in #ifdefs
4682 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
4683 if (ERROR("SPACING",
4684 "exactly one space required after that #$1\n" . $herecurr) &&
4685 $fix) {
4686 $fixed[$fixlinenr] =~
4687 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
4692 # check for spinlock_t definitions without a comment.
4693 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
4694 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
4695 my $which = $1;
4696 if (!ctx_has_comment($first_line, $linenr)) {
4697 CHK("UNCOMMENTED_DEFINITION",
4698 "$1 definition without comment\n" . $herecurr);
4701 # check for memory barriers without a comment.
4702 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
4703 if (!ctx_has_comment($first_line, $linenr)) {
4704 WARN("MEMORY_BARRIER",
4705 "memory barrier without comment\n" . $herecurr);
4708 # check of hardware specific defines
4709 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
4710 CHK("ARCH_DEFINES",
4711 "architecture specific defines should be avoided\n" . $herecurr);
4714 # Check that the storage class is at the beginning of a declaration
4715 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
4716 WARN("STORAGE_CLASS",
4717 "storage class should be at the beginning of the declaration\n" . $herecurr)
4720 # check the location of the inline attribute, that it is between
4721 # storage class and type.
4722 if ($line =~ /\b$Type\s+$Inline\b/ ||
4723 $line =~ /\b$Inline\s+$Storage\b/) {
4724 ERROR("INLINE_LOCATION",
4725 "inline keyword should sit between storage class and type\n" . $herecurr);
4728 # Check for __inline__ and __inline, prefer inline
4729 if ($realfile !~ m@\binclude/uapi/@ &&
4730 $line =~ /\b(__inline__|__inline)\b/) {
4731 if (WARN("INLINE",
4732 "plain inline is preferred over $1\n" . $herecurr) &&
4733 $fix) {
4734 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
4739 # Check for __attribute__ packed, prefer __packed
4740 if ($realfile !~ m@\binclude/uapi/@ &&
4741 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
4742 WARN("PREFER_PACKED",
4743 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
4746 # Check for __attribute__ aligned, prefer __aligned
4747 if ($realfile !~ m@\binclude/uapi/@ &&
4748 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
4749 WARN("PREFER_ALIGNED",
4750 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
4753 # Check for __attribute__ format(printf, prefer __printf
4754 if ($realfile !~ m@\binclude/uapi/@ &&
4755 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
4756 if (WARN("PREFER_PRINTF",
4757 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
4758 $fix) {
4759 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
4764 # Check for __attribute__ format(scanf, prefer __scanf
4765 if ($realfile !~ m@\binclude/uapi/@ &&
4766 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
4767 if (WARN("PREFER_SCANF",
4768 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
4769 $fix) {
4770 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
4774 # Check for __attribute__ weak, or __weak declarations (may have link issues)
4775 if ($^V && $^V ge 5.10.0 &&
4776 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
4777 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
4778 $line =~ /\b__weak\b/)) {
4779 ERROR("WEAK_DECLARATION",
4780 "Using weak declarations can have unintended link defects\n" . $herecurr);
4783 # check for sizeof(&)
4784 if ($line =~ /\bsizeof\s*\(\s*\&/) {
4785 WARN("SIZEOF_ADDRESS",
4786 "sizeof(& should be avoided\n" . $herecurr);
4789 # check for sizeof without parenthesis
4790 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
4791 if (WARN("SIZEOF_PARENTHESIS",
4792 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
4793 $fix) {
4794 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
4798 # check for struct spinlock declarations
4799 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
4800 WARN("USE_SPINLOCK_T",
4801 "struct spinlock should be spinlock_t\n" . $herecurr);
4804 # check for seq_printf uses that could be seq_puts
4805 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
4806 my $fmt = get_quoted_string($line, $rawline);
4807 if ($fmt ne "" && $fmt !~ /[^\\]\%/) {
4808 if (WARN("PREFER_SEQ_PUTS",
4809 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
4810 $fix) {
4811 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
4816 # Check for misused memsets
4817 if ($^V && $^V ge 5.10.0 &&
4818 defined $stat &&
4819 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) {
4821 my $ms_addr = $2;
4822 my $ms_val = $7;
4823 my $ms_size = $12;
4825 if ($ms_size =~ /^(0x|)0$/i) {
4826 ERROR("MEMSET",
4827 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
4828 } elsif ($ms_size =~ /^(0x|)1$/i) {
4829 WARN("MEMSET",
4830 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
4834 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
4835 if ($^V && $^V ge 5.10.0 &&
4836 $line =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/s) {
4837 if (WARN("PREFER_ETHER_ADDR_COPY",
4838 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . $herecurr) &&
4839 $fix) {
4840 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
4844 # typecasts on min/max could be min_t/max_t
4845 if ($^V && $^V ge 5.10.0 &&
4846 defined $stat &&
4847 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
4848 if (defined $2 || defined $7) {
4849 my $call = $1;
4850 my $cast1 = deparenthesize($2);
4851 my $arg1 = $3;
4852 my $cast2 = deparenthesize($7);
4853 my $arg2 = $8;
4854 my $cast;
4856 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
4857 $cast = "$cast1 or $cast2";
4858 } elsif ($cast1 ne "") {
4859 $cast = $cast1;
4860 } else {
4861 $cast = $cast2;
4863 WARN("MINMAX",
4864 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
4868 # check usleep_range arguments
4869 if ($^V && $^V ge 5.10.0 &&
4870 defined $stat &&
4871 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
4872 my $min = $1;
4873 my $max = $7;
4874 if ($min eq $max) {
4875 WARN("USLEEP_RANGE",
4876 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4877 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
4878 $min > $max) {
4879 WARN("USLEEP_RANGE",
4880 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
4884 # check for naked sscanf
4885 if ($^V && $^V ge 5.10.0 &&
4886 defined $stat &&
4887 $line =~ /\bsscanf\b/ &&
4888 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
4889 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
4890 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
4891 my $lc = $stat =~ tr@\n@@;
4892 $lc = $lc + $linenr;
4893 my $stat_real = raw_line($linenr, 0);
4894 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4895 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4897 WARN("NAKED_SSCANF",
4898 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
4901 # check for simple sscanf that should be kstrto<foo>
4902 if ($^V && $^V ge 5.10.0 &&
4903 defined $stat &&
4904 $line =~ /\bsscanf\b/) {
4905 my $lc = $stat =~ tr@\n@@;
4906 $lc = $lc + $linenr;
4907 my $stat_real = raw_line($linenr, 0);
4908 for (my $count = $linenr + 1; $count <= $lc; $count++) {
4909 $stat_real = $stat_real . "\n" . raw_line($count, 0);
4911 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
4912 my $format = $6;
4913 my $count = $format =~ tr@%@%@;
4914 if ($count == 1 &&
4915 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
4916 WARN("SSCANF_TO_KSTRTO",
4917 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
4922 # check for new externs in .h files.
4923 if ($realfile =~ /\.h$/ &&
4924 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
4925 if (CHK("AVOID_EXTERNS",
4926 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
4927 $fix) {
4928 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
4932 # check for new externs in .c files.
4933 if ($realfile =~ /\.c$/ && defined $stat &&
4934 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
4936 my $function_name = $1;
4937 my $paren_space = $2;
4939 my $s = $stat;
4940 if (defined $cond) {
4941 substr($s, 0, length($cond), '');
4943 if ($s =~ /^\s*;/ &&
4944 $function_name ne 'uninitialized_var')
4946 WARN("AVOID_EXTERNS",
4947 "externs should be avoided in .c files\n" . $herecurr);
4950 if ($paren_space =~ /\n/) {
4951 WARN("FUNCTION_ARGUMENTS",
4952 "arguments for function declarations should follow identifier\n" . $herecurr);
4955 } elsif ($realfile =~ /\.c$/ && defined $stat &&
4956 $stat =~ /^.\s*extern\s+/)
4958 WARN("AVOID_EXTERNS",
4959 "externs should be avoided in .c files\n" . $herecurr);
4962 # checks for new __setup's
4963 if ($rawline =~ /\b__setup\("([^"]*)"/) {
4964 my $name = $1;
4966 if (!grep(/$name/, @setup_docs)) {
4967 CHK("UNDOCUMENTED_SETUP",
4968 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
4972 # check for pointless casting of kmalloc return
4973 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
4974 WARN("UNNECESSARY_CASTS",
4975 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
4978 # alloc style
4979 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
4980 if ($^V && $^V ge 5.10.0 &&
4981 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
4982 CHK("ALLOC_SIZEOF_STRUCT",
4983 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
4986 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
4987 if ($^V && $^V ge 5.10.0 &&
4988 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
4989 my $oldfunc = $3;
4990 my $a1 = $4;
4991 my $a2 = $10;
4992 my $newfunc = "kmalloc_array";
4993 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
4994 my $r1 = $a1;
4995 my $r2 = $a2;
4996 if ($a1 =~ /^sizeof\s*\S/) {
4997 $r1 = $a2;
4998 $r2 = $a1;
5000 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5001 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5002 if (WARN("ALLOC_WITH_MULTIPLY",
5003 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5004 $fix) {
5005 $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;
5011 # check for krealloc arg reuse
5012 if ($^V && $^V ge 5.10.0 &&
5013 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5014 WARN("KREALLOC_ARG_REUSE",
5015 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5018 # check for alloc argument mismatch
5019 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5020 WARN("ALLOC_ARRAY_ARGS",
5021 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5024 # check for multiple semicolons
5025 if ($line =~ /;\s*;\s*$/) {
5026 if (WARN("ONE_SEMICOLON",
5027 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5028 $fix) {
5029 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5033 # check for #defines like: 1 << <digit> that could be BIT(digit)
5034 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5035 my $ull = "";
5036 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5037 if (CHK("BIT_MACRO",
5038 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5039 $fix) {
5040 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5044 # check for case / default statements not preceded by break/fallthrough/switch
5045 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5046 my $has_break = 0;
5047 my $has_statement = 0;
5048 my $count = 0;
5049 my $prevline = $linenr;
5050 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5051 $prevline--;
5052 my $rline = $rawlines[$prevline - 1];
5053 my $fline = $lines[$prevline - 1];
5054 last if ($fline =~ /^\@\@/);
5055 next if ($fline =~ /^\-/);
5056 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5057 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5058 next if ($fline =~ /^.[\s$;]*$/);
5059 $has_statement = 1;
5060 $count++;
5061 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5063 if (!$has_break && $has_statement) {
5064 WARN("MISSING_BREAK",
5065 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5069 # check for switch/default statements without a break;
5070 if ($^V && $^V ge 5.10.0 &&
5071 defined $stat &&
5072 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5073 my $ctx = '';
5074 my $herectx = $here . "\n";
5075 my $cnt = statement_rawlines($stat);
5076 for (my $n = 0; $n < $cnt; $n++) {
5077 $herectx .= raw_line($linenr, $n) . "\n";
5079 WARN("DEFAULT_NO_BREAK",
5080 "switch default: should use break\n" . $herectx);
5083 # check for gcc specific __FUNCTION__
5084 if ($line =~ /\b__FUNCTION__\b/) {
5085 if (WARN("USE_FUNC",
5086 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5087 $fix) {
5088 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5092 # check for use of yield()
5093 if ($line =~ /\byield\s*\(\s*\)/) {
5094 WARN("YIELD",
5095 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5098 # check for comparisons against true and false
5099 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5100 my $lead = $1;
5101 my $arg = $2;
5102 my $test = $3;
5103 my $otype = $4;
5104 my $trail = $5;
5105 my $op = "!";
5107 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5109 my $type = lc($otype);
5110 if ($type =~ /^(?:true|false)$/) {
5111 if (("$test" eq "==" && "$type" eq "true") ||
5112 ("$test" eq "!=" && "$type" eq "false")) {
5113 $op = "";
5116 CHK("BOOL_COMPARISON",
5117 "Using comparison to $otype is error prone\n" . $herecurr);
5119 ## maybe suggesting a correct construct would better
5120 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5125 # check for semaphores initialized locked
5126 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5127 WARN("CONSIDER_COMPLETION",
5128 "consider using a completion\n" . $herecurr);
5131 # recommend kstrto* over simple_strto* and strict_strto*
5132 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5133 WARN("CONSIDER_KSTRTO",
5134 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5137 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5138 if ($line =~ /^.\s*__initcall\s*\(/) {
5139 WARN("USE_DEVICE_INITCALL",
5140 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5143 # check for various ops structs, ensure they are const.
5144 my $struct_ops = qr{acpi_dock_ops|
5145 address_space_operations|
5146 backlight_ops|
5147 block_device_operations|
5148 dentry_operations|
5149 dev_pm_ops|
5150 dma_map_ops|
5151 extent_io_ops|
5152 file_lock_operations|
5153 file_operations|
5154 hv_ops|
5155 ide_dma_ops|
5156 intel_dvo_dev_ops|
5157 item_operations|
5158 iwl_ops|
5159 kgdb_arch|
5160 kgdb_io|
5161 kset_uevent_ops|
5162 lock_manager_operations|
5163 microcode_ops|
5164 mtrr_ops|
5165 neigh_ops|
5166 nlmsvc_binding|
5167 pci_raw_ops|
5168 pipe_buf_operations|
5169 platform_hibernation_ops|
5170 platform_suspend_ops|
5171 proto_ops|
5172 rpc_pipe_ops|
5173 seq_operations|
5174 snd_ac97_build_ops|
5175 soc_pcmcia_socket_ops|
5176 stacktrace_ops|
5177 sysfs_ops|
5178 tty_operations|
5179 usb_mon_operations|
5180 wd_ops}x;
5181 if ($line !~ /\bconst\b/ &&
5182 $line =~ /\bstruct\s+($struct_ops)\b/) {
5183 WARN("CONST_STRUCT",
5184 "struct $1 should normally be const\n" .
5185 $herecurr);
5188 # use of NR_CPUS is usually wrong
5189 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5190 if ($line =~ /\bNR_CPUS\b/ &&
5191 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5192 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5193 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5194 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5195 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5197 WARN("NR_CPUS",
5198 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5201 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5202 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5203 ERROR("DEFINE_ARCH_HAS",
5204 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5207 # whine mightly about in_atomic
5208 if ($line =~ /\bin_atomic\s*\(/) {
5209 if ($realfile =~ m@^drivers/@) {
5210 ERROR("IN_ATOMIC",
5211 "do not use in_atomic in drivers\n" . $herecurr);
5212 } elsif ($realfile !~ m@^kernel/@) {
5213 WARN("IN_ATOMIC",
5214 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5218 # check for lockdep_set_novalidate_class
5219 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5220 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5221 if ($realfile !~ m@^kernel/lockdep@ &&
5222 $realfile !~ m@^include/linux/lockdep@ &&
5223 $realfile !~ m@^drivers/base/core@) {
5224 ERROR("LOCKDEP",
5225 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5229 if ($line =~ /debugfs_create_file.*S_IWUGO/ ||
5230 $line =~ /DEVICE_ATTR.*S_IWUGO/ ) {
5231 WARN("EXPORTED_WORLD_WRITABLE",
5232 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5235 # Mode permission misuses where it seems decimal should be octal
5236 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5237 if ($^V && $^V ge 5.10.0 &&
5238 $line =~ /$mode_perms_search/) {
5239 foreach my $entry (@mode_permission_funcs) {
5240 my $func = $entry->[0];
5241 my $arg_pos = $entry->[1];
5243 my $skip_args = "";
5244 if ($arg_pos > 1) {
5245 $arg_pos--;
5246 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5248 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5249 if ($line =~ /$test/) {
5250 my $val = $1;
5251 $val = $6 if ($skip_args ne "");
5253 if ($val !~ /^0$/ &&
5254 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5255 length($val) ne 4)) {
5256 ERROR("NON_OCTAL_PERMISSIONS",
5257 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5264 # If we have no input at all, then there is nothing to report on
5265 # so just keep quiet.
5266 if ($#rawlines == -1) {
5267 exit(0);
5270 # In mailback mode only produce a report in the negative, for
5271 # things that appear to be patches.
5272 if ($mailback && ($clean == 1 || !$is_patch)) {
5273 exit(0);
5276 # This is not a patch, and we are are in 'no-patch' mode so
5277 # just keep quiet.
5278 if (!$chk_patch && !$is_patch) {
5279 exit(0);
5282 if (!$is_patch) {
5283 ERROR("NOT_UNIFIED_DIFF",
5284 "Does not appear to be a unified-diff format patch\n");
5286 if ($is_patch && $chk_signoff && $signoff == 0) {
5287 ERROR("MISSING_SIGN_OFF",
5288 "Missing Signed-off-by: line(s)\n");
5291 print report_dump();
5292 if ($summary && !($clean == 1 && $quiet == 1)) {
5293 print "$filename " if ($summary_file);
5294 print "total: $cnt_error errors, $cnt_warn warnings, " .
5295 (($check)? "$cnt_chk checks, " : "") .
5296 "$cnt_lines lines checked\n";
5297 print "\n" if ($quiet == 0);
5300 if ($quiet == 0) {
5302 if ($^V lt 5.10.0) {
5303 print("NOTE: perl $^V is not modern enough to detect all possible issues.\n");
5304 print("An upgrade to at least perl v5.10.0 is suggested.\n\n");
5307 # If there were whitespace errors which cleanpatch can fix
5308 # then suggest that.
5309 if ($rpt_cleaners) {
5310 print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
5311 print " scripts/cleanfile\n\n";
5312 $rpt_cleaners = 0;
5316 hash_show_words(\%use_type, "Used");
5317 hash_show_words(\%ignore_type, "Ignored");
5319 if ($clean == 0 && $fix &&
5320 ("@rawlines" ne "@fixed" ||
5321 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5322 my $newfile = $filename;
5323 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5324 my $linecount = 0;
5325 my $f;
5327 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5329 open($f, '>', $newfile)
5330 or die "$P: Can't open $newfile for write\n";
5331 foreach my $fixed_line (@fixed) {
5332 $linecount++;
5333 if ($file) {
5334 if ($linecount > 3) {
5335 $fixed_line =~ s/^\+//;
5336 print $f $fixed_line . "\n";
5338 } else {
5339 print $f $fixed_line . "\n";
5342 close($f);
5344 if (!$quiet) {
5345 print << "EOM";
5346 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5348 Do _NOT_ trust the results written to this file.
5349 Do _NOT_ submit these changes without inspecting them for correctness.
5351 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5352 No warranties, expressed or implied...
5358 if ($clean == 1 && $quiet == 0) {
5359 print "$vname has no obvious style problems and is ready for submission.\n"
5361 if ($clean == 0 && $quiet == 0) {
5362 print << "EOM";
5363 $vname has style problems, please review.
5365 If any of these errors are false positives, please report
5366 them to the maintainer, see CHECKPATCH in MAINTAINERS.
5370 return $clean;