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
12 use Term::ANSIColor qw(:constants);
15 my $D = dirname(abs_path($P));
19 use Getopt::Long qw(:config no_auto_abbrev);
24 my $ignore_changeid = 0;
47 my $configuration_file = ".checkpatch.conf";
48 my $max_line_length = 80;
49 my $ignore_perl_version = 0;
50 my $minimum_perl_version = 5.10.0;
51 my $min_conf_desc_length = 4;
52 my $spelling_file = "$D/spelling.txt";
54 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 Usage: $P [OPTION]... [FILE]...
66 --no-tree run without a kernel tree
67 --no-signoff do not check for 'Signed-off-by' line
68 --ignore-changeid ignore Gerrit Change-Id
69 --patch treat FILE as patchfile (default)
70 --emacs emacs compile window format
71 --terse one line per report
72 --showfile emit diffed file position, not input file position
73 -f, --file treat FILE as regular source file
74 --subjective, --strict enable more subjective tests
75 --types TYPE(,TYPE2...) show only these comma separated message types
76 --ignore TYPE(,TYPE2...) ignore various comma separated message types
77 --max-line-length=n set the maximum line length, if exceeded, warn
78 --min-conf-desc-length=n set the min description length, if shorter, warn
79 --show-types show the message "types" in the output
80 --root=PATH PATH to the kernel tree root
81 --no-summary suppress the per-file summary
82 --mailback only produce a report in case of warnings/errors
83 --summary-file include the filename in summary
84 --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of
85 'values', 'possible', 'type', and 'attr' (default
87 --test-only=WORD report only warnings/errors containing WORD
89 --fix EXPERIMENTAL - may create horrible results
90 If correctable single-line errors exist, create
91 "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
92 with potential errors corrected to the preferred
94 --fix-inplace EXPERIMENTAL - may create horrible results
95 Is the same as --fix, but overwrites the input
96 file. It's your fault if there's no backup or git
97 --ignore-perl-version override checking of perl version. expect
99 --codespell Use the codespell dictionary for spelling/typos
100 (default:/usr/share/codespell/dictionary.txt)
101 --codespellfile Use this codespell dictionary
102 --color Use colors when output is STDOUT (default: on)
103 -h, --help, --version display this help and exit
105 When FILE is - read standard input.
111 my $conf = which_conf($configuration_file);
114 open(my $conffile, '<', "$conf")
115 or warn "$P: Can't find a readable $configuration_file file $!\n";
117 while (<$conffile>) {
120 $line =~ s/\s*\n?$//g;
124 next if ($line =~ m/^\s*#/);
125 next if ($line =~ m/^\s*$/);
127 my @words = split(" ", $line);
128 foreach my $word (@words) {
129 last if ($word =~ m/^#/);
130 push (@conf_args, $word);
134 unshift(@ARGV, @conf_args) if @conf_args;
138 'q|quiet+' => \$quiet,
140 'signoff!' => \$chk_signoff,
141 'ignore-changeid!' => \$ignore_changeid,
142 'patch!' => \$chk_patch,
145 'showfile!' => \$showfile,
147 'subjective!' => \$check,
148 'strict!' => \$check,
149 'ignore=s' => \@ignore,
151 'show-types!' => \$show_types,
152 'max-line-length=i' => \$max_line_length,
153 'min-conf-desc-length=i' => \$min_conf_desc_length,
155 'summary!' => \$summary,
156 'mailback!' => \$mailback,
157 'summary-file!' => \$summary_file,
159 'fix-inplace!' => \$fix_inplace,
160 'ignore-perl-version!' => \$ignore_perl_version,
161 'debug=s' => \%debug,
162 'test-only=s' => \$tst_only,
163 'codespell!' => \$codespell,
164 'codespellfile=s' => \$codespellfile,
172 $fix = 1 if ($fix_inplace);
173 $check_orig = $check;
177 if ($^V && $^V lt $minimum_perl_version) {
178 printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
179 if (!$ignore_perl_version) {
185 print "$P: no input files\n";
189 sub hash_save_array_words {
190 my ($hashRef, $arrayRef) = @_;
192 my @array = split(/,/, join(',', @$arrayRef));
193 foreach my $word (@array) {
194 $word =~ s/\s*\n?$//g;
197 $word =~ tr/[a-z]/[A-Z]/;
199 next if ($word =~ m/^\s*#/);
200 next if ($word =~ m/^\s*$/);
206 sub hash_show_words {
207 my ($hashRef, $prefix) = @_;
209 if (keys %$hashRef) {
210 print "\nNOTE: $prefix message types:";
211 foreach my $word (sort keys %$hashRef) {
218 hash_save_array_words(\%ignore_type, \@ignore);
219 hash_save_array_words(\%use_type, \@use);
222 my $dbg_possible = 0;
225 for my $key (keys %debug) {
227 eval "\${dbg_$key} = '$debug{$key}';";
231 my $rpt_cleaners = 0;
240 if (!top_of_kernel_tree($root)) {
241 die "$P: $root: --root does not point at a valid tree\n";
244 if (top_of_kernel_tree('.')) {
246 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
247 top_of_kernel_tree($1)) {
252 if (!defined $root) {
253 print "Must be run from the top-level dir. of a kernel tree\n";
258 my $emitted_corrupt = 0;
261 [A-Za-z_][A-Za-z\d_]*
262 (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
264 our $Storage = qr{extern|static|asmlinkage};
277 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
278 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
279 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
280 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
281 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
283 # Notes to $Attribute:
284 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
305 ____cacheline_aligned|
306 ____cacheline_aligned_in_smp|
307 ____cacheline_internodealigned_in_smp|
311 our $Inline = qr{inline|__always_inline|noinline|__inline|__inline__};
312 our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]};
313 our $Lval = qr{$Ident(?:$Member)*};
315 our $Int_type = qr{(?i)llu|ull|ll|lu|ul|l|u};
316 our $Binary = qr{(?i)0b[01]+$Int_type?};
317 our $Hex = qr{(?i)0x[0-9a-f]+$Int_type?};
318 our $Int = qr{[0-9]+$Int_type?};
319 our $Octal = qr{0[0-7]+$Int_type?};
320 our $String = qr{"[X\t]*"};
321 our $Float_hex = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
322 our $Float_dec = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
323 our $Float_int = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
324 our $Float = qr{$Float_hex|$Float_dec|$Float_int};
325 our $Constant = qr{$Float|$Binary|$Octal|$Hex|$Int};
326 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
327 our $Compare = qr{<=|>=|==|!=|<|(?<!-)>};
328 our $Arithmetic = qr{\+|-|\*|\/|%};
332 &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
335 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
339 our $NonptrTypeMisordered;
340 our $NonptrTypeWithAttr;
344 our $DeclareMisordered;
346 our $NON_ASCII_UTF8 = qr{
347 [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
348 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
349 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
350 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
351 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
352 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
353 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
357 [\x09\x0A\x0D\x20-\x7E] # ASCII
361 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
362 our $typeOtherOSTypedefs = qr{(?x:
363 u_(?:char|short|int|long) | # bsd
364 u(?:nchar|short|int|long) # sysv
366 our $typeKernelTypedefs = qr{(?x:
367 (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
370 our $typeTypedefs = qr{(?x:
372 $typeOtherOSTypedefs\b|
373 $typeKernelTypedefs\b
376 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
378 our $logFunctions = qr{(?x:
379 printk(?:_ratelimited|_once|)|
380 (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
381 WARN(?:_RATELIMIT|_ONCE|)|
384 seq_vprintf|seq_printf|seq_puts
387 our $signature_tags = qr{(?xi:
398 our @typeListMisordered = (
399 qr{char\s+(?:un)?signed},
400 qr{int\s+(?:(?:un)?signed\s+)?short\s},
401 qr{int\s+short(?:\s+(?:un)?signed)},
402 qr{short\s+int(?:\s+(?:un)?signed)},
403 qr{(?:un)?signed\s+int\s+short},
404 qr{short\s+(?:un)?signed},
405 qr{long\s+int\s+(?:un)?signed},
406 qr{int\s+long\s+(?:un)?signed},
407 qr{long\s+(?:un)?signed\s+int},
408 qr{int\s+(?:un)?signed\s+long},
409 qr{int\s+(?:un)?signed},
410 qr{int\s+long\s+long\s+(?:un)?signed},
411 qr{long\s+long\s+int\s+(?:un)?signed},
412 qr{long\s+long\s+(?:un)?signed\s+int},
413 qr{long\s+long\s+(?:un)?signed},
414 qr{long\s+(?:un)?signed},
419 qr{(?:(?:un)?signed\s+)?char},
420 qr{(?:(?:un)?signed\s+)?short\s+int},
421 qr{(?:(?:un)?signed\s+)?short},
422 qr{(?:(?:un)?signed\s+)?int},
423 qr{(?:(?:un)?signed\s+)?long\s+int},
424 qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
425 qr{(?:(?:un)?signed\s+)?long\s+long},
426 qr{(?:(?:un)?signed\s+)?long},
435 qr{${Ident}_handler},
436 qr{${Ident}_handler_fn},
439 our @typeListFile = ();
440 our @typeListWithAttr = (
442 qr{struct\s+$InitAttribute\s+$Ident},
443 qr{union\s+$InitAttribute\s+$Ident},
446 our @modifierList = (
449 our @modifierListFile = ();
451 our @mode_permission_funcs = (
453 ["module_param_(?:array|named|string)", 4],
454 ["module_param_array_named", 5],
455 ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
456 ["proc_create(?:_data|)", 2],
457 ["(?:CLASS|DEVICE|SENSOR)_ATTR", 2],
460 #Create a search pattern for all these functions to speed up a loop below
461 our $mode_perms_search = "";
462 foreach my $entry (@mode_permission_funcs) {
463 $mode_perms_search .= '|' if ($mode_perms_search ne "");
464 $mode_perms_search .= $entry->[0];
467 our $mode_perms_world_writable = qr{
475 our $allowed_asm_includes = qr{(?x:
481 # memory.h: ARM has a custom one
483 # Load common spelling mistakes and build regular expression list.
487 if (open(my $spelling, '<', $spelling_file)) {
488 while (<$spelling>) {
491 $line =~ s/\s*\n?$//g;
494 next if ($line =~ m/^\s*#/);
495 next if ($line =~ m/^\s*$/);
497 my ($suspect, $fix) = split(/\|\|/, $line);
499 $spelling_fix{$suspect} = $fix;
503 warn "No typos will be found - file '$spelling_file': $!\n";
507 if (open(my $spelling, '<', $codespellfile)) {
508 while (<$spelling>) {
511 $line =~ s/\s*\n?$//g;
514 next if ($line =~ m/^\s*#/);
515 next if ($line =~ m/^\s*$/);
516 next if ($line =~ m/, disabled/i);
520 my ($suspect, $fix) = split(/->/, $line);
522 $spelling_fix{$suspect} = $fix;
526 warn "No codespell typos will be found - file '$codespellfile': $!\n";
530 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
533 my $mods = "(?x: \n" . join("|\n ", (@modifierList, @modifierListFile)) . "\n)";
534 my $all = "(?x: \n" . join("|\n ", (@typeList, @typeListFile)) . "\n)";
535 my $Misordered = "(?x: \n" . join("|\n ", @typeListMisordered) . "\n)";
536 my $allWithAttr = "(?x: \n" . join("|\n ", @typeListWithAttr) . "\n)";
537 $Modifier = qr{(?:$Attribute|$Sparse|$mods)};
543 (?:$Modifier\s+|const\s+)*
545 (?:typeof|__typeof__)\s*\([^\)]*\)|
549 (?:\s+$Modifier|\s+const)*
551 $NonptrTypeMisordered = qr{
552 (?:$Modifier\s+|const\s+)*
556 (?:\s+$Modifier|\s+const)*
558 $NonptrTypeWithAttr = qr{
559 (?:$Modifier\s+|const\s+)*
561 (?:typeof|__typeof__)\s*\([^\)]*\)|
565 (?:\s+$Modifier|\s+const)*
569 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
570 (?:\s+$Inline|\s+$Modifier)*
572 $TypeMisordered = qr{
573 $NonptrTypeMisordered
574 (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
575 (?:\s+$Inline|\s+$Modifier)*
577 $Declare = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
578 $DeclareMisordered = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
582 our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
584 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
585 # requires at least perl version v5.10.0
586 # Any use must be runtime checked with $^V
588 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
589 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
590 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
592 our $declaration_macros = qr{(?x:
593 (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
594 (?:$Storage\s+)?LIST_HEAD\s*\(|
595 (?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(
600 return "" if (!defined($string));
602 while ($string =~ /^\s*\(.*\)\s*$/) {
603 $string =~ s@^\s*\(\s*@@;
604 $string =~ s@\s*\)\s*$@@;
607 $string =~ s@\s+@ @g;
612 sub seed_camelcase_file {
615 return if (!(-f $file));
619 open(my $include_file, '<', "$file")
620 or warn "$P: Can't read '$file' $!\n";
621 my $text = <$include_file>;
622 close($include_file);
624 my @lines = split('\n', $text);
626 foreach my $line (@lines) {
627 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
628 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
630 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
632 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
638 my $camelcase_seeded = 0;
639 sub seed_camelcase_includes {
640 return if ($camelcase_seeded);
643 my $camelcase_cache = "";
644 my @include_files = ();
646 $camelcase_seeded = 1;
649 my $git_last_include_commit = `git log --no-merges --pretty=format:"%h%n" -1 -- include`;
650 chomp $git_last_include_commit;
651 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
653 my $last_mod_date = 0;
654 $files = `find $root/include -name "*.h"`;
655 @include_files = split('\n', $files);
656 foreach my $file (@include_files) {
657 my $date = POSIX::strftime("%Y%m%d%H%M",
658 localtime((stat $file)[9]));
659 $last_mod_date = $date if ($last_mod_date < $date);
661 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
664 if ($camelcase_cache ne "" && -f $camelcase_cache) {
665 open(my $camelcase_file, '<', "$camelcase_cache")
666 or warn "$P: Can't read '$camelcase_cache' $!\n";
667 while (<$camelcase_file>) {
671 close($camelcase_file);
677 $files = `git ls-files "include/*.h"`;
678 @include_files = split('\n', $files);
681 foreach my $file (@include_files) {
682 seed_camelcase_file($file);
685 if ($camelcase_cache ne "") {
686 unlink glob ".checkpatch-camelcase.*";
687 open(my $camelcase_file, '>', "$camelcase_cache")
688 or warn "$P: Can't write '$camelcase_cache' $!\n";
689 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
690 print $camelcase_file ("$_\n");
692 close($camelcase_file);
696 sub git_commit_info {
697 my ($commit, $id, $desc) = @_;
699 return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
701 my $output = `git log --no-color --format='%H %s' -1 $commit 2>&1`;
702 $output =~ s/^\s*//gm;
703 my @lines = split("\n", $output);
705 return ($id, $desc) if ($#lines < 0);
707 if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous\./) {
708 # Maybe one day convert this block of bash into something that returns
709 # all matching commit ids, but it's very slow...
711 # echo "checking commits $1..."
712 # git rev-list --remotes | grep -i "^$1" |
713 # while read line ; do
714 # git log --format='%H %s' -1 $line |
715 # echo "commit $(cut -c 1-12,41-)"
717 } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
719 $id = substr($lines[0], 0, 12);
720 $desc = substr($lines[0], 41);
726 $chk_signoff = 0 if ($file);
731 my @fixed_inserted = ();
732 my @fixed_deleted = ();
736 for my $filename (@ARGV) {
739 open($FILE, '-|', "diff -u /dev/null $filename") ||
740 die "$P: $filename: diff failed - $!\n";
741 } elsif ($filename eq '-') {
742 open($FILE, '<&STDIN');
744 open($FILE, '<', "$filename") ||
745 die "$P: $filename: open failed - $!\n";
747 if ($filename eq '-') {
748 $vname = 'Your patch';
758 if ($#ARGV > 0 && $quiet == 0) {
759 print '-' x length($vname) . "\n";
761 print '-' x length($vname) . "\n";
764 if (!process($filename)) {
770 @fixed_inserted = ();
773 @modifierListFile = ();
779 hash_show_words(\%use_type, "Used");
780 hash_show_words(\%ignore_type, "Ignored");
785 NOTE: perl $^V is not modern enough to detect all possible issues.
786 An upgrade to at least perl v5.10.0 is suggested.
792 NOTE: If any of the errors are false positives, please report
793 them to the maintainer, see CHECKPATCH in MAINTAINERS.
800 sub top_of_kernel_tree {
804 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
805 "README", "Documentation", "arch", "include", "drivers",
806 "fs", "init", "ipc", "kernel", "lib", "scripts",
809 foreach my $check (@tree_check) {
810 if (! -e $root . '/' . $check) {
818 my ($formatted_email) = @_;
824 if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
827 $comment = $3 if defined $3;
828 } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
830 $comment = $2 if defined $2;
831 } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
833 $comment = $2 if defined $2;
834 $formatted_email =~ s/$address.*$//;
835 $name = $formatted_email;
837 $name =~ s/^\"|\"$//g;
838 # If there's a name left after stripping spaces and
839 # leading quotes, and the address doesn't have both
840 # leading and trailing angle brackets, the address
842 # "joe smith joe@smith.com" bad
843 # "joe smith <joe@smith.com" bad
844 if ($name ne "" && $address !~ /^<[^>]+>$/) {
852 $name =~ s/^\"|\"$//g;
853 $address = trim($address);
854 $address =~ s/^\<|\>$//g;
856 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
857 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
861 return ($name, $address, $comment);
865 my ($name, $address) = @_;
870 $name =~ s/^\"|\"$//g;
871 $address = trim($address);
873 if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
874 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
879 $formatted_email = "$address";
881 $formatted_email = "$name <$address>";
884 return $formatted_email;
890 foreach my $path (split(/:/, $ENV{PATH})) {
891 if (-e "$path/$bin") {
902 foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
903 if (-e "$path/$conf") {
904 return "$path/$conf";
916 for my $c (split(//, $str)) {
920 for (; ($n % 8) != 0; $n++) {
932 (my $res = shift) =~ tr/\t/ /c;
939 # Drop the diff line leader and expand tabs
941 $line = expand_tabs($line);
943 # Pick the indent from the front of the line.
944 my ($white) = ($line =~ /^(\s*)/);
946 return (length($line), length($white));
949 my $sanitise_quote = '';
951 sub sanitise_line_reset {
952 my ($in_comment) = @_;
955 $sanitise_quote = '*/';
957 $sanitise_quote = '';
970 # Always copy over the diff marker.
971 $res = substr($line, 0, 1);
973 for ($off = 1; $off < length($line); $off++) {
974 $c = substr($line, $off, 1);
976 # Comments we are wacking completly including the begin
977 # and end, all to $;.
978 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
979 $sanitise_quote = '*/';
981 substr($res, $off, 2, "$;$;");
985 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
986 $sanitise_quote = '';
987 substr($res, $off, 2, "$;$;");
991 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
992 $sanitise_quote = '//';
994 substr($res, $off, 2, $sanitise_quote);
999 # A \ in a string means ignore the next character.
1000 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1002 substr($res, $off, 2, 'XX');
1007 if ($c eq "'" || $c eq '"') {
1008 if ($sanitise_quote eq '') {
1009 $sanitise_quote = $c;
1011 substr($res, $off, 1, $c);
1013 } elsif ($sanitise_quote eq $c) {
1014 $sanitise_quote = '';
1018 #print "c<$c> SQ<$sanitise_quote>\n";
1019 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1020 substr($res, $off, 1, $;);
1021 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1022 substr($res, $off, 1, $;);
1023 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1024 substr($res, $off, 1, 'X');
1026 substr($res, $off, 1, $c);
1030 if ($sanitise_quote eq '//') {
1031 $sanitise_quote = '';
1034 # The pathname on a #include may be surrounded by '<' and '>'.
1035 if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1036 my $clean = 'X' x length($1);
1037 $res =~ s@\<.*\>@<$clean>@;
1039 # The whole of a #error is a string.
1040 } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1041 my $clean = 'X' x length($1);
1042 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1048 sub get_quoted_string {
1049 my ($line, $rawline) = @_;
1051 return "" if ($line !~ m/($String)/g);
1052 return substr($rawline, $-[0], $+[0] - $-[0]);
1055 sub ctx_statement_block {
1056 my ($linenr, $remain, $off) = @_;
1057 my $line = $linenr - 1;
1060 my $coff = $off - 1;
1074 @stack = (['', 0]) if ($#stack == -1);
1076 #warn "CSB: blk<$blk> remain<$remain>\n";
1077 # If we are about to drop off the end, pull in more
1080 for (; $remain > 0; $line++) {
1081 last if (!defined $lines[$line]);
1082 next if ($lines[$line] =~ /^-/);
1085 $blk .= $lines[$line] . "\n";
1086 $len = length($blk);
1090 # Bail if there is no further context.
1091 #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1095 if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1101 $c = substr($blk, $off, 1);
1102 $remainder = substr($blk, $off);
1104 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1106 # Handle nested #if/#else.
1107 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1108 push(@stack, [ $type, $level ]);
1109 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1110 ($type, $level) = @{$stack[$#stack - 1]};
1111 } elsif ($remainder =~ /^#\s*endif\b/) {
1112 ($type, $level) = @{pop(@stack)};
1115 # Statement ends at the ';' or a close '}' at the
1117 if ($level == 0 && $c eq ';') {
1121 # An else is really a conditional as long as its not else if
1122 if ($level == 0 && $coff_set == 0 &&
1123 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1124 $remainder =~ /^(else)(?:\s|{)/ &&
1125 $remainder !~ /^else\s+if\b/) {
1126 $coff = $off + length($1) - 1;
1128 #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1129 #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1132 if (($type eq '' || $type eq '(') && $c eq '(') {
1136 if ($type eq '(' && $c eq ')') {
1138 $type = ($level != 0)? '(' : '';
1140 if ($level == 0 && $coff < $soff) {
1143 #warn "CSB: mark coff<$coff>\n";
1146 if (($type eq '' || $type eq '{') && $c eq '{') {
1150 if ($type eq '{' && $c eq '}') {
1152 $type = ($level != 0)? '{' : '';
1155 if (substr($blk, $off + 1, 1) eq ';') {
1161 # Preprocessor commands end at the newline unless escaped.
1162 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1170 # We are truly at the end, so shuffle to the next line.
1177 my $statement = substr($blk, $soff, $off - $soff + 1);
1178 my $condition = substr($blk, $soff, $coff - $soff + 1);
1180 #warn "STATEMENT<$statement>\n";
1181 #warn "CONDITION<$condition>\n";
1183 #print "coff<$coff> soff<$off> loff<$loff>\n";
1185 return ($statement, $condition,
1186 $line, $remain + 1, $off - $loff + 1, $level);
1189 sub statement_lines {
1192 # Strip the diff line prefixes and rip blank lines at start and end.
1193 $stmt =~ s/(^|\n)./$1/g;
1197 my @stmt_lines = ($stmt =~ /\n/g);
1199 return $#stmt_lines + 2;
1202 sub statement_rawlines {
1205 my @stmt_lines = ($stmt =~ /\n/g);
1207 return $#stmt_lines + 2;
1210 sub statement_block_size {
1213 $stmt =~ s/(^|\n)./$1/g;
1219 my @stmt_lines = ($stmt =~ /\n/g);
1220 my @stmt_statements = ($stmt =~ /;/g);
1222 my $stmt_lines = $#stmt_lines + 2;
1223 my $stmt_statements = $#stmt_statements + 1;
1225 if ($stmt_lines > $stmt_statements) {
1228 return $stmt_statements;
1232 sub ctx_statement_full {
1233 my ($linenr, $remain, $off) = @_;
1234 my ($statement, $condition, $level);
1238 # Grab the first conditional/block pair.
1239 ($statement, $condition, $linenr, $remain, $off, $level) =
1240 ctx_statement_block($linenr, $remain, $off);
1241 #print "F: c<$condition> s<$statement> remain<$remain>\n";
1242 push(@chunks, [ $condition, $statement ]);
1243 if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1244 return ($level, $linenr, @chunks);
1247 # Pull in the following conditional/block pairs and see if they
1248 # could continue the statement.
1250 ($statement, $condition, $linenr, $remain, $off, $level) =
1251 ctx_statement_block($linenr, $remain, $off);
1252 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1253 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1255 push(@chunks, [ $condition, $statement ]);
1258 return ($level, $linenr, @chunks);
1262 my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1264 my $start = $linenr - 1;
1271 my @stack = ($level);
1272 for ($line = $start; $remain > 0; $line++) {
1273 next if ($rawlines[$line] =~ /^-/);
1276 $blk .= $rawlines[$line];
1278 # Handle nested #if/#else.
1279 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1280 push(@stack, $level);
1281 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1282 $level = $stack[$#stack - 1];
1283 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1284 $level = pop(@stack);
1287 foreach my $c (split(//, $lines[$line])) {
1288 ##print "C<$c>L<$level><$open$close>O<$off>\n";
1294 if ($c eq $close && $level > 0) {
1296 last if ($level == 0);
1297 } elsif ($c eq $open) {
1302 if (!$outer || $level <= 1) {
1303 push(@res, $rawlines[$line]);
1306 last if ($level == 0);
1309 return ($level, @res);
1311 sub ctx_block_outer {
1312 my ($linenr, $remain) = @_;
1314 my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1318 my ($linenr, $remain) = @_;
1320 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1324 my ($linenr, $remain, $off) = @_;
1326 my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1329 sub ctx_block_level {
1330 my ($linenr, $remain) = @_;
1332 return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1334 sub ctx_statement_level {
1335 my ($linenr, $remain, $off) = @_;
1337 return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1340 sub ctx_locate_comment {
1341 my ($first_line, $end_line) = @_;
1343 # Catch a comment on the end of the line itself.
1344 my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1345 return $current_comment if (defined $current_comment);
1347 # Look through the context and try and figure out if there is a
1350 $current_comment = '';
1351 for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1352 my $line = $rawlines[$linenr - 1];
1354 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1357 if ($line =~ m@/\*@) {
1360 if (!$in_comment && $current_comment ne '') {
1361 $current_comment = '';
1363 $current_comment .= $line . "\n" if ($in_comment);
1364 if ($line =~ m@\*/@) {
1369 chomp($current_comment);
1370 return($current_comment);
1372 sub ctx_has_comment {
1373 my ($first_line, $end_line) = @_;
1374 my $cmt = ctx_locate_comment($first_line, $end_line);
1376 ##print "LINE: $rawlines[$end_line - 1 ]\n";
1377 ##print "CMMT: $cmt\n";
1379 return ($cmt ne '');
1383 my ($linenr, $cnt) = @_;
1385 my $offset = $linenr - 1;
1390 $line = $rawlines[$offset++];
1391 next if (defined($line) && $line =~ /^-/);
1403 while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1406 $coded = sprintf("^%c", unpack('C', $2) + 64);
1415 my $av_preprocessor = 0;
1420 sub annotate_reset {
1421 $av_preprocessor = 0;
1423 @av_paren_type = ('E');
1424 $av_pend_colon = 'O';
1427 sub annotate_values {
1428 my ($stream, $type) = @_;
1431 my $var = '_' x length($stream);
1434 print "$stream\n" if ($dbg_values > 1);
1436 while (length($cur)) {
1437 @av_paren_type = ('E') if ($#av_paren_type < 0);
1438 print " <" . join('', @av_paren_type) .
1439 "> <$type> <$av_pending>" if ($dbg_values > 1);
1440 if ($cur =~ /^(\s+)/o) {
1441 print "WS($1)\n" if ($dbg_values > 1);
1442 if ($1 =~ /\n/ && $av_preprocessor) {
1443 $type = pop(@av_paren_type);
1444 $av_preprocessor = 0;
1447 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1448 print "CAST($1)\n" if ($dbg_values > 1);
1449 push(@av_paren_type, $type);
1452 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1453 print "DECLARE($1)\n" if ($dbg_values > 1);
1456 } elsif ($cur =~ /^($Modifier)\s*/) {
1457 print "MODIFIER($1)\n" if ($dbg_values > 1);
1460 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1461 print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1462 $av_preprocessor = 1;
1463 push(@av_paren_type, $type);
1469 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1470 print "UNDEF($1)\n" if ($dbg_values > 1);
1471 $av_preprocessor = 1;
1472 push(@av_paren_type, $type);
1474 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1475 print "PRE_START($1)\n" if ($dbg_values > 1);
1476 $av_preprocessor = 1;
1478 push(@av_paren_type, $type);
1479 push(@av_paren_type, $type);
1482 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1483 print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1484 $av_preprocessor = 1;
1486 push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1490 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1491 print "PRE_END($1)\n" if ($dbg_values > 1);
1493 $av_preprocessor = 1;
1495 # Assume all arms of the conditional end as this
1496 # one does, and continue as if the #endif was not here.
1497 pop(@av_paren_type);
1498 push(@av_paren_type, $type);
1501 } elsif ($cur =~ /^(\\\n)/o) {
1502 print "PRECONT($1)\n" if ($dbg_values > 1);
1504 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1505 print "ATTR($1)\n" if ($dbg_values > 1);
1506 $av_pending = $type;
1509 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1510 print "SIZEOF($1)\n" if ($dbg_values > 1);
1516 } elsif ($cur =~ /^(if|while|for)\b/o) {
1517 print "COND($1)\n" if ($dbg_values > 1);
1521 } elsif ($cur =~/^(case)/o) {
1522 print "CASE($1)\n" if ($dbg_values > 1);
1523 $av_pend_colon = 'C';
1526 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1527 print "KEYWORD($1)\n" if ($dbg_values > 1);
1530 } elsif ($cur =~ /^(\()/o) {
1531 print "PAREN('$1')\n" if ($dbg_values > 1);
1532 push(@av_paren_type, $av_pending);
1536 } elsif ($cur =~ /^(\))/o) {
1537 my $new_type = pop(@av_paren_type);
1538 if ($new_type ne '_') {
1540 print "PAREN('$1') -> $type\n"
1541 if ($dbg_values > 1);
1543 print "PAREN('$1')\n" if ($dbg_values > 1);
1546 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1547 print "FUNC($1)\n" if ($dbg_values > 1);
1551 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1552 if (defined $2 && $type eq 'C' || $type eq 'T') {
1553 $av_pend_colon = 'B';
1554 } elsif ($type eq 'E') {
1555 $av_pend_colon = 'L';
1557 print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1560 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1561 print "IDENT($1)\n" if ($dbg_values > 1);
1564 } elsif ($cur =~ /^($Assignment)/o) {
1565 print "ASSIGN($1)\n" if ($dbg_values > 1);
1568 } elsif ($cur =~/^(;|{|})/) {
1569 print "END($1)\n" if ($dbg_values > 1);
1571 $av_pend_colon = 'O';
1573 } elsif ($cur =~/^(,)/) {
1574 print "COMMA($1)\n" if ($dbg_values > 1);
1577 } elsif ($cur =~ /^(\?)/o) {
1578 print "QUESTION($1)\n" if ($dbg_values > 1);
1581 } elsif ($cur =~ /^(:)/o) {
1582 print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1584 substr($var, length($res), 1, $av_pend_colon);
1585 if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1590 $av_pend_colon = 'O';
1592 } elsif ($cur =~ /^(\[)/o) {
1593 print "CLOSE($1)\n" if ($dbg_values > 1);
1596 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1599 print "OPV($1)\n" if ($dbg_values > 1);
1606 substr($var, length($res), 1, $variant);
1609 } elsif ($cur =~ /^($Operators)/o) {
1610 print "OP($1)\n" if ($dbg_values > 1);
1611 if ($1 ne '++' && $1 ne '--') {
1615 } elsif ($cur =~ /(^.)/o) {
1616 print "C($1)\n" if ($dbg_values > 1);
1619 $cur = substr($cur, length($1));
1620 $res .= $type x length($1);
1624 return ($res, $var);
1628 my ($possible, $line) = @_;
1629 my $notPermitted = qr{(?:
1646 ^(?:typedef|struct|enum)\b
1648 warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1649 if ($possible !~ $notPermitted) {
1650 # Check for modifiers.
1651 $possible =~ s/\s*$Storage\s*//g;
1652 $possible =~ s/\s*$Sparse\s*//g;
1653 if ($possible =~ /^\s*$/) {
1655 } elsif ($possible =~ /\s/) {
1656 $possible =~ s/\s*$Type\s*//g;
1657 for my $modifier (split(' ', $possible)) {
1658 if ($modifier !~ $notPermitted) {
1659 warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1660 push(@modifierListFile, $modifier);
1665 warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1666 push(@typeListFile, $possible);
1670 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1679 return defined $use_type{$type} if (scalar keys %use_type > 0);
1681 return !defined $ignore_type{$type};
1685 my ($level, $type, $msg) = @_;
1687 if (!show_type($type) ||
1688 (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
1692 if (-t STDOUT && $color) {
1693 if ($level eq 'ERROR') {
1695 } elsif ($level eq 'WARNING') {
1701 $output .= $prefix . $level . ':';
1703 $output .= BLUE if (-t STDOUT && $color);
1704 $output .= "$type:";
1706 $output .= RESET if (-t STDOUT && $color);
1707 $output .= ' ' . $msg . "\n";
1710 my @lines = split("\n", $output, -1);
1711 splice(@lines, 1, 1);
1712 $output = join("\n", @lines);
1714 $output = (split('\n', $output))[0] . "\n" if ($terse);
1716 push(our @report, $output);
1725 sub fixup_current_range {
1726 my ($lineRef, $offset, $length) = @_;
1728 if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
1731 my $no = $o + $offset;
1732 my $nl = $l + $length;
1733 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
1737 sub fix_inserted_deleted_lines {
1738 my ($linesRef, $insertedRef, $deletedRef) = @_;
1740 my $range_last_linenr = 0;
1741 my $delta_offset = 0;
1746 my $next_insert = 0;
1747 my $next_delete = 0;
1751 my $inserted = @{$insertedRef}[$next_insert++];
1752 my $deleted = @{$deletedRef}[$next_delete++];
1754 foreach my $old_line (@{$linesRef}) {
1756 my $line = $old_line; #don't modify the array
1757 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) { #new filename
1759 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) { #new hunk
1760 $range_last_linenr = $new_linenr;
1761 fixup_current_range(\$line, $delta_offset, 0);
1764 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
1765 $deleted = @{$deletedRef}[$next_delete++];
1767 fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
1770 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
1771 push(@lines, ${$inserted}{'LINE'});
1772 $inserted = @{$insertedRef}[$next_insert++];
1774 fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
1778 push(@lines, $line);
1788 sub fix_insert_line {
1789 my ($linenr, $line) = @_;
1795 push(@fixed_inserted, $inserted);
1798 sub fix_delete_line {
1799 my ($linenr, $line) = @_;
1806 push(@fixed_deleted, $deleted);
1810 my ($type, $msg) = @_;
1812 if (report("ERROR", $type, $msg)) {
1820 my ($type, $msg) = @_;
1822 if (report("WARNING", $type, $msg)) {
1830 my ($type, $msg) = @_;
1832 if ($check && report("CHECK", $type, $msg)) {
1840 sub check_absolute_file {
1841 my ($absolute, $herecurr) = @_;
1842 my $file = $absolute;
1844 ##print "absolute<$absolute>\n";
1846 # See if any suffix of this path is a path within the tree.
1847 while ($file =~ s@^[^/]*/@@) {
1848 if (-f "$root/$file") {
1849 ##print "file<$file>\n";
1857 # It is, so see if the prefix is acceptable.
1858 my $prefix = $absolute;
1859 substr($prefix, -length($file)) = '';
1861 ##print "prefix<$prefix>\n";
1862 if ($prefix ne ".../") {
1863 WARN("USE_RELATIVE_PATH",
1864 "use relative pathname instead of absolute in changelog text\n" . $herecurr);
1871 $string =~ s/^\s+|\s+$//g;
1879 $string =~ s/^\s+//;
1887 $string =~ s/\s+$//;
1892 sub string_find_replace {
1893 my ($string, $find, $replace) = @_;
1895 $string =~ s/$find/$replace/g;
1903 my $source_indent = 8;
1904 my $max_spaces_before_tab = $source_indent - 1;
1905 my $spaces_to_tab = " " x $source_indent;
1907 #convert leading spaces to tabs
1908 1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
1909 #Remove spaces before a tab
1910 1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
1915 sub pos_last_openparen {
1920 my $opens = $line =~ tr/\(/\(/;
1921 my $closes = $line =~ tr/\)/\)/;
1923 my $last_openparen = 0;
1925 if (($opens == 0) || ($closes >= $opens)) {
1929 my $len = length($line);
1931 for ($pos = 0; $pos < $len; $pos++) {
1932 my $string = substr($line, $pos);
1933 if ($string =~ /^($FuncArg|$balanced_parens)/) {
1934 $pos += length($1) - 1;
1935 } elsif (substr($line, $pos, 1) eq '(') {
1936 $last_openparen = $pos;
1937 } elsif (index($string, '(') == -1) {
1942 return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
1946 my $filename = shift;
1952 my $stashrawline="";
1962 my $in_header_lines = $file ? 0 : 1;
1963 my $in_commit_log = 0; #Scanning lines before patch
1964 my $commit_log_possible_stack_dump = 0;
1965 my $commit_log_long_line = 0;
1966 my $commit_log_has_diff = 0;
1967 my $reported_maintainer_file = 0;
1968 my $non_utf8_charset = 0;
1970 my $last_blank_line = 0;
1971 my $last_coalesced_string_linenr = -1;
1979 # Trace the real file/line as we go.
1985 my $comment_edge = 0;
1989 my $prev_values = 'E';
1992 my %suppress_ifbraces;
1993 my %suppress_whiletrailers;
1994 my %suppress_export;
1995 my $suppress_statement = 0;
1997 my %signatures = ();
1999 # Pre-scan the patch sanitizing the lines.
2000 # Pre-scan the patch looking for any __setup documentation.
2002 my @setup_docs = ();
2005 my $camelcase_file_seeded = 0;
2007 sanitise_line_reset();
2009 foreach my $rawline (@rawlines) {
2013 push(@fixed, $rawline) if ($fix);
2015 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2017 if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
2022 if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2031 # Guestimate if this is a continuing comment. Run
2032 # the context looking for a comment "edge". If this
2033 # edge is a close comment then we must be in a comment
2037 for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2038 next if (defined $rawlines[$ln - 1] &&
2039 $rawlines[$ln - 1] =~ /^-/);
2041 #print "RAW<$rawlines[$ln - 1]>\n";
2042 last if (!defined $rawlines[$ln - 1]);
2043 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2044 $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2049 if (defined $edge && $edge eq '*/') {
2053 # Guestimate if this is a continuing comment. If this
2054 # is the start of a diff block and this line starts
2055 # ' *' then it is very likely a comment.
2056 if (!defined $edge &&
2057 $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2062 ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2063 sanitise_line_reset($in_comment);
2065 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2066 # Standardise the strings and chars within the input to
2067 # simplify matching -- only bother with positive lines.
2068 $line = sanitise_line($rawline);
2070 push(@lines, $line);
2073 $realcnt-- if ($line =~ /^(?:\+| |$)/);
2078 #print "==>$rawline\n";
2079 #print "-->$line\n";
2081 if ($setup_docs && $line =~ /^\+/) {
2082 push(@setup_docs, $line);
2091 foreach my $line (@lines) {
2094 my $sline = $line; #copy of $line
2095 $sline =~ s/$;/ /g; #with comments as spaces
2097 my $rawline = $rawlines[$linenr - 1];
2099 #extract the line range in the file after the patch is applied
2100 if (!$in_commit_log &&
2101 $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2103 $first_line = $linenr + 1;
2113 %suppress_ifbraces = ();
2114 %suppress_whiletrailers = ();
2115 %suppress_export = ();
2116 $suppress_statement = 0;
2119 # track the line number as we move through the hunk, note that
2120 # new versions of GNU diff omit the leading space on completely
2121 # blank context lines so we need to count that too.
2122 } elsif ($line =~ /^( |\+|$)/) {
2124 $realcnt-- if ($realcnt != 0);
2126 # Measure the line length and indent.
2127 ($length, $indent) = line_stats($rawline);
2129 # Track the previous line.
2130 ($prevline, $stashline) = ($stashline, $line);
2131 ($previndent, $stashindent) = ($stashindent, $indent);
2132 ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2134 #warn "line<$line>\n";
2136 } elsif ($realcnt == 1) {
2140 my $hunk_line = ($realcnt != 0);
2142 $here = "#$linenr: " if (!$file);
2143 $here = "#$realline: " if ($file);
2146 # extract the filename as it passes
2147 if ($line =~ /^diff --git.*?(\S+)$/) {
2149 $realfile =~ s@^([^/]*)/@@ if (!$file);
2152 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2154 $realfile =~ s@^([^/]*)/@@ if (!$file);
2158 if (!$file && $tree && $p1_prefix ne '' &&
2159 -e "$root/$p1_prefix") {
2160 WARN("PATCH_PREFIX",
2161 "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2164 if ($realfile =~ m@^include/asm/@) {
2165 ERROR("MODIFIED_INCLUDE_ASM",
2166 "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2171 #make up the handle for any error we report on this line
2173 $prefix = "$realfile:$realline: "
2176 $prefix = "$filename:$realline: ";
2178 $prefix = "$filename:$linenr: ";
2183 if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2186 $check = $check_orig;
2191 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2193 my $hereline = "$here\n$rawline\n";
2194 my $herecurr = "$here\n$rawline\n";
2195 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2197 $cnt_lines++ if ($realcnt != 0);
2199 # Check if the commit log has what seems like a diff which can confuse patch
2200 if ($in_commit_log && !$commit_log_has_diff &&
2201 (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2202 $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2203 $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2204 $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2205 ERROR("DIFF_IN_COMMIT_MSG",
2206 "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2207 $commit_log_has_diff = 1;
2210 # Check for incorrect file permissions
2211 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2212 my $permhere = $here . "FILE: $realfile\n";
2213 if ($realfile !~ m@scripts/@ &&
2214 $realfile !~ /\.(py|pl|awk|sh)$/) {
2215 ERROR("EXECUTE_PERMISSIONS",
2216 "do not set execute permissions for source files\n" . $permhere);
2220 # Check the patch for a signoff:
2221 if ($line =~ /^\s*signed-off-by:/i) {
2226 # Check if MAINTAINERS and/or NVIDIA-REVIEWERS is being updated. If so, there's probably no need to
2227 # emit the "does MAINTAINERS/NVIDIA-REVIEWERS need updating?" message on file add/move/delete
2228 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2229 $reported_maintainer_file = 1;
2232 if ($line =~ /^\s*NVIDIA-REVIEWERS\s*\|/) {
2233 $reported_maintainer_file = 1;
2236 # Check signature styles
2237 if (!$in_header_lines &&
2238 $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2239 my $space_before = $1;
2241 my $space_after = $3;
2243 my $ucfirst_sign_off = ucfirst(lc($sign_off));
2245 if ($sign_off !~ /$signature_tags/) {
2246 WARN("BAD_SIGN_OFF",
2247 "Non-standard signature: $sign_off\n" . $herecurr);
2249 if (defined $space_before && $space_before ne "") {
2250 if (WARN("BAD_SIGN_OFF",
2251 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2253 $fixed[$fixlinenr] =
2254 "$ucfirst_sign_off $email";
2257 if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2258 if (WARN("BAD_SIGN_OFF",
2259 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2261 $fixed[$fixlinenr] =
2262 "$ucfirst_sign_off $email";
2266 if (!defined $space_after || $space_after ne " ") {
2267 if (WARN("BAD_SIGN_OFF",
2268 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2270 $fixed[$fixlinenr] =
2271 "$ucfirst_sign_off $email";
2275 my ($email_name, $email_address, $comment) = parse_email($email);
2276 my $suggested_email = format_email(($email_name, $email_address));
2277 if ($suggested_email eq "") {
2278 ERROR("BAD_SIGN_OFF",
2279 "Unrecognized email address: '$email'\n" . $herecurr);
2281 my $dequoted = $suggested_email;
2282 $dequoted =~ s/^"//;
2283 $dequoted =~ s/" </ </;
2284 # Don't force email to have quotes
2285 # Allow just an angle bracketed address
2286 if ("$dequoted$comment" ne $email &&
2287 "<$email_address>$comment" ne $email &&
2288 "$suggested_email$comment" ne $email) {
2289 WARN("BAD_SIGN_OFF",
2290 "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2294 # Check for duplicate signatures
2295 my $sig_nospace = $line;
2296 $sig_nospace =~ s/\s//g;
2297 $sig_nospace = lc($sig_nospace);
2298 if (defined $signatures{$sig_nospace}) {
2299 WARN("BAD_SIGN_OFF",
2300 "Duplicate signature\n" . $herecurr);
2302 $signatures{$sig_nospace} = 1;
2306 # Check email subject for common tools that don't need to be mentioned
2307 if ($in_header_lines &&
2308 $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2309 WARN("EMAIL_SUBJECT",
2310 "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2313 # Check for old stable address
2314 if ($line =~ /^\s*cc:\s*.*<?\bstable\@kernel\.org\b>?.*$/i) {
2315 ERROR("STABLE_ADDRESS",
2316 "The 'stable' address should be 'stable\@vger.kernel.org'\n" . $herecurr);
2319 # Check for unwanted Gerrit info
2320 if ($in_commit_log && !$ignore_changeid && $line =~ /^\s*change-id:/i) {
2321 ERROR("GERRIT_CHANGE_ID",
2322 "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2325 # Check if the commit log is in a possible stack dump
2326 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2327 ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2328 $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2330 $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/)) {
2331 # stack dump address
2332 $commit_log_possible_stack_dump = 1;
2335 # Check for line lengths > 75 in commit log, warn once
2336 if ($in_commit_log && !$commit_log_long_line &&
2337 length($line) > 75 &&
2338 !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2339 # file delta changes
2340 $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2342 $line =~ /^\s*(?:Fixes:|Link:)/i ||
2343 # A Fixes: or Link: line
2344 $commit_log_possible_stack_dump)) {
2345 WARN("COMMIT_LOG_LONG_LINE",
2346 "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2347 $commit_log_long_line = 1;
2350 # Reset possible stack dump if a blank line is found
2351 if ($in_commit_log && $commit_log_possible_stack_dump &&
2353 $commit_log_possible_stack_dump = 0;
2356 # Check for git id commit length and improperly formed commit descriptions
2357 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2358 ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2359 ($line =~ /\b[0-9a-f]{12,40}\b/i &&
2360 $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2361 $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2362 my $init_char = "c";
2363 my $orig_commit = "";
2370 my $id = '0123456789ab';
2371 my $orig_desc = "commit description";
2372 my $description = "";
2374 if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2376 $orig_commit = lc($2);
2377 } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2378 $orig_commit = lc($1);
2381 $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2382 $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2383 $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2384 $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2385 if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2388 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2389 defined $rawlines[$linenr] &&
2390 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2393 } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2394 defined $rawlines[$linenr] &&
2395 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2396 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2398 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2399 $orig_desc .= " " . $1;
2403 ($id, $description) = git_commit_info($orig_commit,
2406 if ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens) {
2407 ERROR("GIT_COMMIT_ID",
2408 "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2412 # Check for added, moved or deleted files
2413 if (!$reported_maintainer_file && !$in_commit_log &&
2414 ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2415 $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2416 ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2417 (defined($1) || defined($2))))) {
2418 $reported_maintainer_file = 1;
2419 WARN("FILE_PATH_CHANGES",
2420 "added, moved or deleted file(s), does MAINTAINERS and/or NVIDIA-REVIEWERS need updating?\n" . $herecurr);
2423 # Check for wrappage within a valid hunk of the file
2424 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2425 ERROR("CORRUPTED_PATCH",
2426 "patch seems to be corrupt (line wrapped?)\n" .
2427 $herecurr) if (!$emitted_corrupt++);
2430 # Check for absolute kernel paths.
2432 while ($line =~ m{(?:^|\s)(/\S*)}g) {
2435 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2436 check_absolute_file($1, $herecurr)) {
2439 check_absolute_file($file, $herecurr);
2444 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2445 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2446 $rawline !~ m/^$UTF8*$/) {
2447 my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2449 my $blank = copy_spacing($rawline);
2450 my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2451 my $hereptr = "$hereline$ptr\n";
2454 "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2457 # Check if it's the start of a commit log
2458 # (not a header line and we haven't seen the patch filename)
2459 if ($in_header_lines && $realfile =~ /^$/ &&
2460 !($rawline =~ /^\s+\S/ ||
2461 $rawline =~ /^(commit\b|from\b|[\w-]+:).*$/i)) {
2462 $in_header_lines = 0;
2466 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2467 # declined it, i.e defined some charset where it is missing.
2468 if ($in_header_lines &&
2469 $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2471 $non_utf8_charset = 1;
2474 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2475 $rawline =~ /$NON_ASCII_UTF8/) {
2476 WARN("UTF8_BEFORE_PATCH",
2477 "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2480 # Check for various typo / spelling mistakes
2481 if (defined($misspellings) &&
2482 ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2483 while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2485 my $typo_fix = $spelling_fix{lc($typo)};
2486 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2487 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2488 my $msg_type = \&WARN;
2489 $msg_type = \&CHK if ($file);
2490 if (&{$msg_type}("TYPO_SPELLING",
2491 "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2493 $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2498 # ignore non-hunk lines and lines being removed
2499 next if (!$hunk_line || $line =~ /^-/);
2501 #trailing whitespace
2502 if ($line =~ /^\+.*\015/) {
2503 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2504 if (ERROR("DOS_LINE_ENDINGS",
2505 "DOS line endings\n" . $herevet) &&
2507 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
2509 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2510 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2511 if (ERROR("TRAILING_WHITESPACE",
2512 "trailing whitespace\n" . $herevet) &&
2514 $fixed[$fixlinenr] =~ s/\s+$//;
2520 # Check for FSF mailing addresses.
2521 if ($rawline =~ /\bwrite to the Free/i ||
2522 $rawline =~ /\b59\s+Temple\s+Pl/i ||
2523 $rawline =~ /\b51\s+Franklin\s+St/i) {
2524 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2525 my $msg_type = \&ERROR;
2526 $msg_type = \&CHK if ($file);
2527 &{$msg_type}("FSF_MAILING_ADDRESS",
2528 "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)
2531 # check for Kconfig help text having a real description
2532 # Only applies when adding the entry originally, after that we do not have
2533 # sufficient context to determine whether it is indeed long enough.
2534 if ($realfile =~ /Kconfig/ &&
2535 $line =~ /^\+\s*config\s+/) {
2538 my $ln = $linenr + 1;
2542 for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2543 $f = $lines[$ln - 1];
2544 $cnt-- if ($lines[$ln - 1] !~ /^-/);
2545 $is_end = $lines[$ln - 1] =~ /^\+/;
2547 next if ($f =~ /^-/);
2548 last if (!$file && $f =~ /^\@\@/);
2550 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate)\s*\"/) {
2552 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
2559 next if ($f =~ /^$/);
2560 if ($f =~ /^\s*config\s/) {
2566 if ($is_start && $is_end && $length < $min_conf_desc_length) {
2567 WARN("CONFIG_DESCRIPTION",
2568 "please write a paragraph that describes the config symbol fully\n" . $herecurr);
2570 #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
2573 # discourage the addition of CONFIG_EXPERIMENTAL in Kconfig.
2574 if ($realfile =~ /Kconfig/ &&
2575 $line =~ /.\s*depends on\s+.*\bEXPERIMENTAL\b/) {
2576 WARN("CONFIG_EXPERIMENTAL",
2577 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2580 # discourage the use of boolean for type definition attributes of Kconfig options
2581 if ($realfile =~ /Kconfig/ &&
2582 $line =~ /^\+\s*\bboolean\b/) {
2583 WARN("CONFIG_TYPE_BOOLEAN",
2584 "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
2587 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
2588 ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
2591 'EXTRA_AFLAGS' => 'asflags-y',
2592 'EXTRA_CFLAGS' => 'ccflags-y',
2593 'EXTRA_CPPFLAGS' => 'cppflags-y',
2594 'EXTRA_LDFLAGS' => 'ldflags-y',
2597 WARN("DEPRECATED_VARIABLE",
2598 "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
2601 # check for DT compatible documentation
2602 if (defined $root &&
2603 (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
2604 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
2606 my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
2608 my $dt_path = $root . "/Documentation/devicetree/bindings/";
2609 my $vp_file = $dt_path . "vendor-prefixes.txt";
2611 foreach my $compat (@compats) {
2612 my $compat2 = $compat;
2613 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
2614 my $compat3 = $compat;
2615 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
2616 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
2618 WARN("UNDOCUMENTED_DT_STRING",
2619 "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
2622 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
2624 `grep -Eq "^$vendor\\b" $vp_file`;
2626 WARN("UNDOCUMENTED_DT_STRING",
2627 "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
2632 # check we are in a valid source file if not then ignore this hunk
2633 next if ($realfile !~ /\.(h|c|s|S|pl|sh|dtsi|dts)$/);
2635 # line length limit (with some exclusions)
2637 # There are a few types of lines that may extend beyond $max_line_length:
2638 # logging functions like pr_info that end in a string
2639 # lines with a single string
2640 # #defines that are a single string
2642 # There are 3 different line length message types:
2643 # LONG_LINE_COMMENT a comment starts before but extends beyond $max_linelength
2644 # LONG_LINE_STRING a string starts before but extends beyond $max_line_length
2645 # LONG_LINE all other lines longer than $max_line_length
2647 # if LONG_LINE is ignored, the other 2 types are also ignored
2650 if ($line =~ /^\+/ && $length > $max_line_length) {
2651 my $msg_type = "LONG_LINE";
2653 # Check the allowed long line types first
2655 # logging functions that end in a string that starts
2656 # before $max_line_length
2657 if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
2658 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2661 # lines with only strings (w/ possible termination)
2662 # #defines with only strings
2663 } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
2664 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
2667 # Otherwise set the alternate message types
2669 # a comment starts before $max_line_length
2670 } elsif ($line =~ /($;[\s$;]*)$/ &&
2671 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2672 $msg_type = "LONG_LINE_COMMENT"
2674 # a quoted string starts before $max_line_length
2675 } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
2676 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
2677 $msg_type = "LONG_LINE_STRING"
2680 if ($msg_type ne "" &&
2681 (show_type("LONG_LINE") || show_type($msg_type))) {
2683 "line over $max_line_length characters\n" . $herecurr);
2687 # check for adding lines without a newline.
2688 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
2689 WARN("MISSING_EOF_NEWLINE",
2690 "adding a line without newline at end of file\n" . $herecurr);
2693 # Blackfin: use hi/lo macros
2694 if ($realfile =~ m@arch/blackfin/.*\.S$@) {
2695 if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
2696 my $herevet = "$here\n" . cat_vet($line) . "\n";
2698 "use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
2700 if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
2701 my $herevet = "$here\n" . cat_vet($line) . "\n";
2703 "use the HI() macro, not (... >> 16)\n" . $herevet);
2707 # check we are in a valid source file C or perl if not then ignore this hunk
2708 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
2710 # at the beginning of a line any tabs must come first and anything
2711 # more than 8 must use tabs.
2712 if ($rawline =~ /^\+\s* \t\s*\S/ ||
2713 $rawline =~ /^\+\s* \s*/) {
2714 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2716 if (ERROR("CODE_INDENT",
2717 "code indent should use tabs where possible\n" . $herevet) &&
2719 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2723 # check for space before tabs.
2724 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
2725 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2726 if (WARN("SPACE_BEFORE_TAB",
2727 "please, no space before tabs\n" . $herevet) &&
2729 while ($fixed[$fixlinenr] =~
2730 s/(^\+.*) {8,8}\t/$1\t\t/) {}
2731 while ($fixed[$fixlinenr] =~
2732 s/(^\+.*) +\t/$1\t/) {}
2736 # check for && or || at the start of a line
2737 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
2738 CHK("LOGICAL_CONTINUATIONS",
2739 "Logical continuations should be on the previous line\n" . $hereprev);
2742 # check multi-line statement indentation matches previous line
2743 if ($^V && $^V ge 5.10.0 &&
2744 $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
2745 $prevline =~ /^\+(\t*)(.*)$/;
2749 my $pos = pos_last_openparen($rest);
2751 $line =~ /^(\+| )([ \t]*)/;
2754 my $goodtabindent = $oldindent .
2757 my $goodspaceindent = $oldindent . " " x $pos;
2759 if ($newindent ne $goodtabindent &&
2760 $newindent ne $goodspaceindent) {
2762 if (CHK("PARENTHESIS_ALIGNMENT",
2763 "Alignment should match open parenthesis\n" . $hereprev) &&
2764 $fix && $line =~ /^\+/) {
2765 $fixed[$fixlinenr] =~
2766 s/^\+[ \t]*/\+$goodtabindent/;
2772 # check for space after cast like "(int) foo" or "(struct foo) bar"
2773 # avoid checking a few false positives:
2774 # "sizeof(<type>)" or "__alignof__(<type>)"
2775 # function pointer declarations like "(*foo)(int) = bar;"
2776 # structure definitions like "(struct foo) { 0 };"
2777 # multiline macros that define functions
2778 # known attributes or the __attribute__ keyword
2779 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
2780 (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
2782 "No space is necessary after a cast\n" . $herecurr) &&
2784 $fixed[$fixlinenr] =~
2785 s/(\(\s*$Type\s*\))[ \t]+/$1/;
2789 # Block comment styles
2790 # Networking with an initial /*
2791 if ($realfile =~ m@^(drivers/net/|net/)@ &&
2792 $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
2793 $rawline =~ /^\+[ \t]*\*/ &&
2795 WARN("NETWORKING_BLOCK_COMMENT_STYLE",
2796 "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
2799 # Block comments use * on subsequent lines
2800 if ($prevline =~ /$;[ \t]*$/ && #ends in comment
2801 $prevrawline =~ /^\+.*?\/\*/ && #starting /*
2802 $prevrawline !~ /\*\/[ \t]*$/ && #no trailing */
2803 $rawline =~ /^\+/ && #line is new
2804 $rawline !~ /^\+[ \t]*\*/) { #no leading *
2805 WARN("BLOCK_COMMENT_STYLE",
2806 "Block comments use * on subsequent lines\n" . $hereprev);
2809 # Block comments use */ on trailing lines
2810 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ && #trailing */
2811 $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ && #inline /*...*/
2812 $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ && #trailing **/
2813 $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) { #non blank */
2814 WARN("BLOCK_COMMENT_STYLE",
2815 "Block comments use a trailing */ on a separate line\n" . $herecurr);
2818 # check for missing blank lines after struct/union declarations
2819 # with exceptions for various attributes and macros
2820 if ($prevline =~ /^[\+ ]};?\s*$/ &&
2822 !($line =~ /^\+\s*$/ ||
2823 $line =~ /^\+\s*EXPORT_SYMBOL/ ||
2824 $line =~ /^\+\s*MODULE_/i ||
2825 $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
2826 $line =~ /^\+[a-z_]*init/ ||
2827 $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
2828 $line =~ /^\+\s*DECLARE/ ||
2829 $line =~ /^\+\s*__setup/)) {
2830 if (CHK("LINE_SPACING",
2831 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
2833 fix_insert_line($fixlinenr, "\+");
2837 # check for multiple consecutive blank lines
2838 if ($prevline =~ /^[\+ ]\s*$/ &&
2839 $line =~ /^\+\s*$/ &&
2840 $last_blank_line != ($linenr - 1)) {
2841 if (CHK("LINE_SPACING",
2842 "Please don't use multiple blank lines\n" . $hereprev) &&
2844 fix_delete_line($fixlinenr, $rawline);
2847 $last_blank_line = $linenr;
2850 # check for missing blank lines after declarations
2851 if ($sline =~ /^\+\s+\S/ && #Not at char 1
2852 # actual declarations
2853 ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2854 # function pointer declarations
2855 $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2856 # foo bar; where foo is some local typedef or #define
2857 $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2858 # known declaration macros
2859 $prevline =~ /^\+\s+$declaration_macros/) &&
2860 # for "else if" which can look like "$Ident $Ident"
2861 !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
2862 # other possible extensions of declaration lines
2863 $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
2864 # not starting a section or a macro "\" extended line
2865 $prevline =~ /(?:\{\s*|\\)$/) &&
2866 # looks like a declaration
2867 !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
2868 # function pointer declarations
2869 $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
2870 # foo bar; where foo is some local typedef or #define
2871 $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
2872 # known declaration macros
2873 $sline =~ /^\+\s+$declaration_macros/ ||
2874 # start of struct or union or enum
2875 $sline =~ /^\+\s+(?:union|struct|enum|typedef)\b/ ||
2876 # start or end of block or continuation of declaration
2877 $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
2878 # bitfield continuation
2879 $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
2880 # other possible extensions of declaration lines
2881 $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
2882 # indentation of previous and current line are the same
2883 (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
2884 if (WARN("LINE_SPACING",
2885 "Missing a blank line after declarations\n" . $hereprev) &&
2887 fix_insert_line($fixlinenr, "\+");
2891 # check for spaces at the beginning of a line.
2893 # 1) within comments
2894 # 2) indented preprocessor commands
2896 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) {
2897 my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2898 if (WARN("LEADING_SPACE",
2899 "please, no spaces at the start of a line\n" . $herevet) &&
2901 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
2905 # check we are in a valid C source file if not then ignore this hunk
2906 next if ($realfile !~ /\.(h|c)$/);
2908 # check indentation of any line with a bare else
2909 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
2910 # if the previous line is a break or return and is indented 1 tab more...
2911 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
2912 my $tabs = length($1) + 1;
2913 if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
2914 ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
2915 defined $lines[$linenr] &&
2916 $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
2917 WARN("UNNECESSARY_ELSE",
2918 "else is not generally useful after a break or return\n" . $hereprev);
2922 # check indentation of a line with a break;
2923 # if the previous line is a goto or return and is indented the same # of tabs
2924 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
2926 if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
2927 WARN("UNNECESSARY_BREAK",
2928 "break is not useful after a goto or return\n" . $hereprev);
2932 # discourage the addition of CONFIG_EXPERIMENTAL in #if(def).
2933 if ($line =~ /^\+\s*\#\s*if.*\bCONFIG_EXPERIMENTAL\b/) {
2934 WARN("CONFIG_EXPERIMENTAL",
2935 "Use of CONFIG_EXPERIMENTAL is deprecated. For alternatives, see https://lkml.org/lkml/2012/10/23/580\n");
2938 # check for RCS/CVS revision markers
2939 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
2941 "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
2944 # Blackfin: don't use __builtin_bfin_[cs]sync
2945 if ($line =~ /__builtin_bfin_csync/) {
2946 my $herevet = "$here\n" . cat_vet($line) . "\n";
2948 "use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
2950 if ($line =~ /__builtin_bfin_ssync/) {
2951 my $herevet = "$here\n" . cat_vet($line) . "\n";
2953 "use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
2956 # check for old HOTPLUG __dev<foo> section markings
2957 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
2958 WARN("HOTPLUG_SECTION",
2959 "Using $1 is unnecessary\n" . $herecurr);
2962 # Check for potential 'bare' types
2963 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
2965 #print "LINE<$line>\n";
2966 if ($linenr >= $suppress_statement &&
2967 $realcnt && $sline =~ /.\s*\S/) {
2968 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
2969 ctx_statement_block($linenr, $realcnt, 0);
2970 $stat =~ s/\n./\n /g;
2971 $cond =~ s/\n./\n /g;
2973 #print "linenr<$linenr> <$stat>\n";
2974 # If this statement has no statement boundaries within
2975 # it there is no point in retrying a statement scan
2976 # until we hit end of it.
2977 my $frag = $stat; $frag =~ s/;+\s*$//;
2978 if ($frag !~ /(?:{|;)/) {
2979 #print "skip<$line_nr_next>\n";
2980 $suppress_statement = $line_nr_next;
2983 # Find the real next line.
2984 $realline_next = $line_nr_next;
2985 if (defined $realline_next &&
2986 (!defined $lines[$realline_next - 1] ||
2987 substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
2994 # Ignore goto labels.
2995 if ($s =~ /$Ident:\*$/s) {
2997 # Ignore functions being called
2998 } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3000 } elsif ($s =~ /^.\s*else\b/s) {
3002 # declarations always start with types
3003 } 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) {
3006 possible($type, "A:" . $s);
3008 # definitions in global scope can only start with types
3009 } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3010 possible($1, "B:" . $s);
3013 # any (foo ... *) is a pointer cast, and foo is a type
3014 while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3015 possible($1, "C:" . $s);
3018 # Check for any sort of function declaration.
3019 # int foo(something bar, other baz);
3020 # void (*store_gdt)(x86_descr_ptr *);
3021 if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3022 my ($name_len) = length($1);
3025 substr($ctx, 0, $name_len + 1, '');
3026 $ctx =~ s/\)[^\)]*$//;
3028 for my $arg (split(/\s*,\s*/, $ctx)) {
3029 if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3031 possible($1, "D:" . $s);
3039 # Checks which may be anchored in the context.
3042 # Check for switch () and associated case and default
3043 # statements should be at the same indent.
3044 if ($line=~/\bswitch\s*\(.*\)/) {
3047 my @ctx = ctx_block_outer($linenr, $realcnt);
3049 for my $ctx (@ctx) {
3050 my ($clen, $cindent) = line_stats($ctx);
3051 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3052 $indent != $cindent) {
3053 $err .= "$sep$ctx\n";
3060 ERROR("SWITCH_CASE_INDENT_LEVEL",
3061 "switch and case should be at the same indent\n$hereline$err");
3065 # if/while/etc brace do not go on next line, unless defining a do while loop,
3066 # or if that brace on the next line is for something else
3067 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3068 my $pre_ctx = "$1$2";
3070 my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3072 if ($line =~ /^\+\t{6,}/) {
3073 WARN("DEEP_INDENTATION",
3074 "Too many leading tabs - consider code refactoring\n" . $herecurr);
3077 my $ctx_cnt = $realcnt - $#ctx - 1;
3078 my $ctx = join("\n", @ctx);
3080 my $ctx_ln = $linenr;
3081 my $ctx_skip = $realcnt;
3083 while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3084 defined $lines[$ctx_ln - 1] &&
3085 $lines[$ctx_ln - 1] =~ /^-/)) {
3086 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3087 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3091 #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3092 #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3094 if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3096 "that open brace { should be on the previous line\n" .
3097 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3099 if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3100 $ctx =~ /\)\s*\;\s*$/ &&
3101 defined $lines[$ctx_ln - 1])
3103 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3104 if ($nindent > $indent) {
3105 WARN("TRAILING_SEMICOLON",
3106 "trailing semicolon indicates no statements, indent implies otherwise\n" .
3107 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3112 # Check relative indent for conditionals and blocks.
3113 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3114 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3115 ctx_statement_block($linenr, $realcnt, 0)
3116 if (!defined $stat);
3117 my ($s, $c) = ($stat, $cond);
3119 substr($s, 0, length($c), '');
3121 # remove inline comments
3125 # Find out how long the conditional actually is.
3126 my @newlines = ($c =~ /\n/gs);
3127 my $cond_lines = 1 + $#newlines;
3129 # Make sure we remove the line prefixes as we have
3130 # none on the first line, and are going to readd them
3133 while ($s =~ /\n\s+\\\n/) {
3134 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3137 # We want to check the first line inside the block
3138 # starting at the end of the conditional, so remove:
3139 # 1) any blank line termination
3140 # 2) any opening brace { on end of the line
3142 my $continuation = 0;
3144 $s =~ s/^.*\bdo\b//;
3146 if ($s =~ s/^\s*\\//) {
3149 if ($s =~ s/^\s*?\n//) {
3154 # Also ignore a loop construct at the end of a
3155 # preprocessor statement.
3156 if (($prevline =~ /^.\s*#\s*define\s/ ||
3157 $prevline =~ /\\\s*$/) && $continuation == 0) {
3163 while ($cond_ptr != $cond_lines) {
3164 $cond_ptr = $cond_lines;
3166 # If we see an #else/#elif then the code
3168 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3173 # 1) blank lines, they should be at 0,
3174 # 2) preprocessor lines, and
3176 if ($continuation ||
3178 $s =~ /^\s*#\s*?/ ||
3179 $s =~ /^\s*$Ident\s*:/) {
3180 $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3181 if ($s =~ s/^.*?\n//) {
3187 my (undef, $sindent) = line_stats("+" . $s);
3188 my $stat_real = raw_line($linenr, $cond_lines);
3190 # Check if either of these lines are modified, else
3191 # this is not this patch's fault.
3192 if (!defined($stat_real) ||
3193 $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3196 if (defined($stat_real) && $cond_lines > 1) {
3197 $stat_real = "[...]\n$stat_real";
3200 #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";
3202 if ($check && $s ne '' &&
3203 (($sindent % 8) != 0 ||
3204 ($sindent < $indent) ||
3205 ($sindent > $indent + 8))) {
3206 WARN("SUSPECT_CODE_INDENT",
3207 "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3211 # Track the 'values' across context and added lines.
3212 my $opline = $line; $opline =~ s/^./ /;
3213 my ($curr_values, $curr_vars) =
3214 annotate_values($opline . "\n", $prev_values);
3215 $curr_values = $prev_values . $curr_values;
3217 my $outline = $opline; $outline =~ s/\t/ /g;
3218 print "$linenr > .$outline\n";
3219 print "$linenr > $curr_values\n";
3220 print "$linenr > $curr_vars\n";
3222 $prev_values = substr($curr_values, -1);
3224 #ignore lines not being added
3225 next if ($line =~ /^[^\+]/);
3227 # TEST: allow direct testing of the type matcher.
3229 if ($line =~ /^.\s*$Declare\s*$/) {
3231 "TEST: is type\n" . $herecurr);
3232 } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3233 ERROR("TEST_NOT_TYPE",
3234 "TEST: is not type ($1 is)\n". $herecurr);
3238 # TEST: allow direct testing of the attribute matcher.
3240 if ($line =~ /^.\s*$Modifier\s*$/) {
3242 "TEST: is attr\n" . $herecurr);
3243 } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3244 ERROR("TEST_NOT_ATTR",
3245 "TEST: is not attr ($1 is)\n". $herecurr);
3250 # check for initialisation to aggregates open brace on the next line
3251 if ($line =~ /^.\s*{/ &&
3252 $prevline =~ /(?:^|[^=])=\s*$/) {
3253 if (ERROR("OPEN_BRACE",
3254 "that open brace { should be on the previous line\n" . $hereprev) &&
3255 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3256 fix_delete_line($fixlinenr - 1, $prevrawline);
3257 fix_delete_line($fixlinenr, $rawline);
3258 my $fixedline = $prevrawline;
3259 $fixedline =~ s/\s*=\s*$/ = {/;
3260 fix_insert_line($fixlinenr, $fixedline);
3262 $fixedline =~ s/^(.\s*){\s*/$1/;
3263 fix_insert_line($fixlinenr, $fixedline);
3268 # Checks which are anchored on the added line.
3271 # check for malformed paths in #include statements (uses RAW line)
3272 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3274 if ($path =~ m{//}) {
3275 ERROR("MALFORMED_INCLUDE",
3276 "malformed #include filename\n" . $herecurr);
3278 if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3279 ERROR("UAPI_INCLUDE",
3280 "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3284 # no C99 // comments
3285 if ($line =~ m{//}) {
3286 if (ERROR("C99_COMMENTS",
3287 "do not use C99 // comments\n" . $herecurr) &&
3289 my $line = $fixed[$fixlinenr];
3290 if ($line =~ /\/\/(.*)$/) {
3291 my $comment = trim($1);
3292 $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3296 # Remove C99 comments.
3298 $opline =~ s@//.*@@;
3300 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3301 # the whole statement.
3302 #print "APW <$lines[$realline_next - 1]>\n";
3303 if (defined $realline_next &&
3304 exists $lines[$realline_next - 1] &&
3305 !defined $suppress_export{$realline_next} &&
3306 ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3307 $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3308 # Handle definitions which produce identifiers with
3311 # EXPORT_SYMBOL(something_foo);
3313 if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3314 $name =~ /^${Ident}_$2/) {
3315 #print "FOO C name<$name>\n";
3316 $suppress_export{$realline_next} = 1;
3318 } elsif ($stat !~ /(?:
3320 ^.DEFINE_$Ident\(\Q$name\E\)|
3321 ^.DECLARE_$Ident\(\Q$name\E\)|
3322 ^.LIST_HEAD\(\Q$name\E\)|
3323 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3324 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3326 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3327 $suppress_export{$realline_next} = 2;
3329 $suppress_export{$realline_next} = 1;
3332 if (!defined $suppress_export{$linenr} &&
3333 $prevline =~ /^.\s*$/ &&
3334 ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3335 $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3336 #print "FOO B <$lines[$linenr - 1]>\n";
3337 $suppress_export{$linenr} = 2;
3339 if (defined $suppress_export{$linenr} &&
3340 $suppress_export{$linenr} == 2) {
3341 WARN("EXPORT_SYMBOL",
3342 "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3345 # check for global initialisers.
3346 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3347 if (ERROR("GLOBAL_INITIALISERS",
3348 "do not initialise globals to $1\n" . $herecurr) &&
3350 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3353 # check for static initialisers.
3354 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3355 if (ERROR("INITIALISED_STATIC",
3356 "do not initialise statics to $1\n" .
3359 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3363 # check for misordered declarations of char/short/int/long with signed/unsigned
3364 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3366 WARN("MISORDERED_TYPE",
3367 "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3370 # check for static const char * arrays.
3371 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3372 WARN("STATIC_CONST_CHAR_ARRAY",
3373 "static const char * array should probably be static const char * const\n" .
3377 # check for static char foo[] = "bar" declarations.
3378 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
3379 WARN("STATIC_CONST_CHAR_ARRAY",
3380 "static char array declaration should probably be static const char\n" .
3384 # check for const <foo> const where <foo> is not a pointer or array type
3385 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
3387 if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
3389 "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
3390 } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
3392 "'const $found const' should probably be 'const $found'\n" . $herecurr);
3396 # check for non-global char *foo[] = {"bar", ...} declarations.
3397 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
3398 WARN("STATIC_CONST_CHAR_ARRAY",
3399 "char * array declaration might be better as static const\n" .
3403 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
3404 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
3406 if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
3408 if (WARN("ARRAY_SIZE",
3409 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
3411 $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
3416 # check for function declarations without arguments like "int foo()"
3417 if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
3418 if (ERROR("FUNCTION_WITHOUT_ARGS",
3419 "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
3421 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
3425 # check for uses of DEFINE_PCI_DEVICE_TABLE
3426 if ($line =~ /\bDEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=/) {
3427 if (WARN("DEFINE_PCI_DEVICE_TABLE",
3428 "Prefer struct pci_device_id over deprecated DEFINE_PCI_DEVICE_TABLE\n" . $herecurr) &&
3430 $fixed[$fixlinenr] =~ s/\b(?:static\s+|)DEFINE_PCI_DEVICE_TABLE\s*\(\s*(\w+)\s*\)\s*=\s*/static const struct pci_device_id $1\[\] = /;
3434 # check for new typedefs, only function parameters and sparse annotations
3436 if ($line =~ /\btypedef\s/ &&
3437 $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
3438 $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
3439 $line !~ /\b$typeTypedefs\b/ &&
3440 $line !~ /\b__bitwise(?:__|)\b/) {
3441 WARN("NEW_TYPEDEFS",
3442 "do not add new typedefs\n" . $herecurr);
3445 # * goes on variable not on type
3447 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
3449 my ($ident, $from, $to) = ($1, $2, $2);
3451 # Should start with a space.
3452 $to =~ s/^(\S)/ $1/;
3453 # Should not end with a space.
3455 # '*'s should not have spaces between.
3456 while ($to =~ s/\*\s+\*/\*\*/) {
3459 ## print "1: from<$from> to<$to> ident<$ident>\n";
3461 if (ERROR("POINTER_LOCATION",
3462 "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) &&
3464 my $sub_from = $ident;
3465 my $sub_to = $ident;
3466 $sub_to =~ s/\Q$from\E/$to/;
3467 $fixed[$fixlinenr] =~
3468 s@\Q$sub_from\E@$sub_to@;
3472 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
3474 my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
3476 # Should start with a space.
3477 $to =~ s/^(\S)/ $1/;
3478 # Should not end with a space.
3480 # '*'s should not have spaces between.
3481 while ($to =~ s/\*\s+\*/\*\*/) {
3483 # Modifiers should have spaces.
3484 $to =~ s/(\b$Modifier$)/$1 /;
3486 ## print "2: from<$from> to<$to> ident<$ident>\n";
3487 if ($from ne $to && $ident !~ /^$Modifier$/) {
3488 if (ERROR("POINTER_LOCATION",
3489 "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) &&
3492 my $sub_from = $match;
3493 my $sub_to = $match;
3494 $sub_to =~ s/\Q$from\E/$to/;
3495 $fixed[$fixlinenr] =~
3496 s@\Q$sub_from\E@$sub_to@;
3501 # avoid BUG() or BUG_ON()
3502 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
3503 my $msg_type = \&WARN;
3504 $msg_type = \&CHK if ($file);
3505 &{$msg_type}("AVOID_BUG",
3506 "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
3509 # avoid LINUX_VERSION_CODE
3510 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
3511 WARN("LINUX_VERSION_CODE",
3512 "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
3515 # check for uses of printk_ratelimit
3516 if ($line =~ /\bprintk_ratelimit\s*\(/) {
3517 WARN("PRINTK_RATELIMITED",
3518 "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
3521 # printk should use KERN_* levels. Note that follow on printk's on the
3522 # same line do not need a level, so we use the current block context
3523 # to try and find and validate the current printk. In summary the current
3524 # printk includes all preceding printk's which have no newline on the end.
3525 # we assume the first bad printk is the one to report.
3526 if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
3528 for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
3529 #print "CHECK<$lines[$ln - 1]\n";
3530 # we have a preceding printk if it ends
3531 # with "\n" ignore it, else it is to blame
3532 if ($lines[$ln - 1] =~ m{\bprintk\(}) {
3533 if ($rawlines[$ln - 1] !~ m{\\n"}) {
3540 WARN("PRINTK_WITHOUT_KERN_LEVEL",
3541 "printk() should include KERN_ facility level\n" . $herecurr);
3545 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
3547 my $level = lc($orig);
3548 $level = "warn" if ($level eq "warning");
3549 my $level2 = $level;
3550 $level2 = "dbg" if ($level eq "debug");
3551 WARN("PREFER_PR_LEVEL",
3552 "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(... to printk(KERN_$orig ...\n" . $herecurr);
3555 if ($line =~ /\bpr_warning\s*\(/) {
3556 if (WARN("PREFER_PR_LEVEL",
3557 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
3559 $fixed[$fixlinenr] =~
3560 s/\bpr_warning\b/pr_warn/;
3564 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
3566 my $level = lc($orig);
3567 $level = "warn" if ($level eq "warning");
3568 $level = "dbg" if ($level eq "debug");
3569 WARN("PREFER_DEV_LEVEL",
3570 "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
3573 # ENOSYS means "bad syscall nr" and nothing else. This will have a small
3574 # number of false positives, but assembly files are not checked, so at
3575 # least the arch entry code will not trigger this warning.
3576 if ($line =~ /\bENOSYS\b/) {
3578 "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
3581 # function brace can't be on same line, except for #defines of do while,
3582 # or if closed on same line
3583 if (($line=~/$Type\s*$Ident\(.*\).*\s*{/) and
3584 !($line=~/\#\s*define.*do\s\{/) and !($line=~/}/)) {
3585 if (ERROR("OPEN_BRACE",
3586 "open brace '{' following function declarations go on the next line\n" . $herecurr) &&
3588 fix_delete_line($fixlinenr, $rawline);
3589 my $fixed_line = $rawline;
3590 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
3593 fix_insert_line($fixlinenr, ltrim($line1));
3594 fix_insert_line($fixlinenr, "\+{");
3595 if ($line2 !~ /^\s*$/) {
3596 fix_insert_line($fixlinenr, "\+\t" . trim($line2));
3601 # open braces for enum, union and struct go on the same line.
3602 if ($line =~ /^.\s*{/ &&
3603 $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
3604 if (ERROR("OPEN_BRACE",
3605 "open brace '{' following $1 go on the same line\n" . $hereprev) &&
3606 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3607 fix_delete_line($fixlinenr - 1, $prevrawline);
3608 fix_delete_line($fixlinenr, $rawline);
3609 my $fixedline = rtrim($prevrawline) . " {";
3610 fix_insert_line($fixlinenr, $fixedline);
3611 $fixedline = $rawline;
3612 $fixedline =~ s/^(.\s*){\s*/$1\t/;
3613 if ($fixedline !~ /^\+\s*$/) {
3614 fix_insert_line($fixlinenr, $fixedline);
3619 # missing space after union, struct or enum definition
3620 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
3622 "missing space after $1 definition\n" . $herecurr) &&
3624 $fixed[$fixlinenr] =~
3625 s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
3629 # Function pointer declarations
3630 # check spacing between type, funcptr, and args
3631 # canonical declaration is "type (*funcptr)(args...)"
3632 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
3634 my $pre_pointer_space = $2;
3635 my $post_pointer_space = $3;
3637 my $post_funcname_space = $5;
3638 my $pre_args_space = $6;
3640 # the $Declare variable will capture all spaces after the type
3641 # so check it for a missing trailing missing space but pointer return types
3642 # don't need a space so don't warn for those.
3643 my $post_declare_space = "";
3644 if ($declare =~ /(\s+)$/) {
3645 $post_declare_space = $1;
3646 $declare = rtrim($declare);
3648 if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
3650 "missing space after return type\n" . $herecurr);
3651 $post_declare_space = " ";
3654 # unnecessary space "type (*funcptr)(args...)"
3655 # This test is not currently implemented because these declarations are
3657 # int foo(int bar, ...)
3658 # and this is form shouldn't/doesn't generate a checkpatch warning.
3660 # elsif ($declare =~ /\s{2,}$/) {
3662 # "Multiple spaces after return type\n" . $herecurr);
3665 # unnecessary space "type ( *funcptr)(args...)"
3666 if (defined $pre_pointer_space &&
3667 $pre_pointer_space =~ /^\s/) {
3669 "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
3672 # unnecessary space "type (* funcptr)(args...)"
3673 if (defined $post_pointer_space &&
3674 $post_pointer_space =~ /^\s/) {
3676 "Unnecessary space before function pointer name\n" . $herecurr);
3679 # unnecessary space "type (*funcptr )(args...)"
3680 if (defined $post_funcname_space &&
3681 $post_funcname_space =~ /^\s/) {
3683 "Unnecessary space after function pointer name\n" . $herecurr);
3686 # unnecessary space "type (*funcptr) (args...)"
3687 if (defined $pre_args_space &&
3688 $pre_args_space =~ /^\s/) {
3690 "Unnecessary space before function pointer arguments\n" . $herecurr);
3693 if (show_type("SPACING") && $fix) {
3694 $fixed[$fixlinenr] =~
3695 s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
3699 # check for spacing round square brackets; allowed:
3700 # 1. with a type on the left -- int [] a;
3701 # 2. at the beginning of a line for slice initialisers -- [0...10] = 5,
3702 # 3. inside a curly brace -- = { [0...10] = 5 }
3703 while ($line =~ /(.*?\s)\[/g) {
3704 my ($where, $prefix) = ($-[1], $1);
3705 if ($prefix !~ /$Type\s+$/ &&
3706 ($where != 0 || $prefix !~ /^.\s+$/) &&
3707 $prefix !~ /[{,]\s+$/) {
3708 if (ERROR("BRACKET_SPACE",
3709 "space prohibited before open square bracket '['\n" . $herecurr) &&
3711 $fixed[$fixlinenr] =~
3712 s/^(\+.*?)\s+\[/$1\[/;
3717 # check for spaces between functions and their parentheses.
3718 while ($line =~ /($Ident)\s+\(/g) {
3720 my $ctx_before = substr($line, 0, $-[1]);
3721 my $ctx = "$ctx_before$name";
3723 # Ignore those directives where spaces _are_ permitted.
3725 if|for|while|switch|return|case|
3726 volatile|__volatile__|
3727 __attribute__|format|__extension__|
3730 # cpp #define statements have non-optional spaces, ie
3731 # if there is a space between the name and the open
3732 # parenthesis it is simply not a parameter group.
3733 } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
3735 # cpp #elif statement condition may start with a (
3736 } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
3738 # If this whole things ends with a type its most
3739 # likely a typedef for a function.
3740 } elsif ($ctx =~ /$Type$/) {
3744 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
3746 $fixed[$fixlinenr] =~
3747 s/\b$name\s+\(/$name\(/;
3752 # Check operator spacing.
3753 if (!($line=~/\#\s*include/)) {
3754 my $fixed_line = "";
3758 <<=|>>=|<=|>=|==|!=|
3759 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
3760 =>|->|<<|>>|<|>|=|!|~|
3761 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
3764 my @elements = split(/($ops|;)/, $opline);
3766 ## print("element count: <" . $#elements . ">\n");
3767 ## foreach my $el (@elements) {
3768 ## print("el: <$el>\n");
3771 my @fix_elements = ();
3774 foreach my $el (@elements) {
3775 push(@fix_elements, substr($rawline, $off, length($el)));
3776 $off += length($el);
3781 my $blank = copy_spacing($opline);
3782 my $last_after = -1;
3784 for (my $n = 0; $n < $#elements; $n += 2) {
3786 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
3788 ## print("n: <$n> good: <$good>\n");
3790 $off += length($elements[$n]);
3792 # Pick up the preceding and succeeding characters.
3793 my $ca = substr($opline, 0, $off);
3795 if (length($opline) >= ($off + length($elements[$n + 1]))) {
3796 $cc = substr($opline, $off + length($elements[$n + 1]));
3798 my $cb = "$ca$;$cc";
3801 $a = 'V' if ($elements[$n] ne '');
3802 $a = 'W' if ($elements[$n] =~ /\s$/);
3803 $a = 'C' if ($elements[$n] =~ /$;$/);
3804 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
3805 $a = 'O' if ($elements[$n] eq '');
3806 $a = 'E' if ($ca =~ /^\s*$/);
3808 my $op = $elements[$n + 1];
3811 if (defined $elements[$n + 2]) {
3812 $c = 'V' if ($elements[$n + 2] ne '');
3813 $c = 'W' if ($elements[$n + 2] =~ /^\s/);
3814 $c = 'C' if ($elements[$n + 2] =~ /^$;/);
3815 $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
3816 $c = 'O' if ($elements[$n + 2] eq '');
3817 $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
3822 my $ctx = "${a}x${c}";
3824 my $at = "(ctx:$ctx)";
3826 my $ptr = substr($blank, 0, $off) . "^";
3827 my $hereptr = "$hereline$ptr\n";
3829 # Pull out the value of this operator.
3830 my $op_type = substr($curr_values, $off + 1, 1);
3832 # Get the full operator variant.
3833 my $opv = $op . substr($curr_vars, $off, 1);
3835 # Ignore operators passed as parameters.
3836 if ($op_type ne 'V' &&
3837 $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
3840 # } elsif ($op =~ /^$;+$/) {
3842 # ; should have either the end of line or a space or \ after it
3843 } elsif ($op eq ';') {
3844 if ($ctx !~ /.x[WEBC]/ &&
3845 $cc !~ /^\\/ && $cc !~ /^;/) {
3846 if (ERROR("SPACING",
3847 "space required after that '$op' $at\n" . $hereptr)) {
3848 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3854 } elsif ($op eq '//') {
3856 # : when part of a bitfield
3857 } elsif ($opv eq ':B') {
3858 # skip the bitfield test for now
3862 } elsif ($op eq '->') {
3863 if ($ctx =~ /Wx.|.xW/) {
3864 if (ERROR("SPACING",
3865 "spaces prohibited around that '$op' $at\n" . $hereptr)) {
3866 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3867 if (defined $fix_elements[$n + 2]) {
3868 $fix_elements[$n + 2] =~ s/^\s+//;
3874 # , must not have a space before and must have a space on the right.
3875 } elsif ($op eq ',') {
3876 my $rtrim_before = 0;
3877 my $space_after = 0;
3878 if ($ctx =~ /Wx./) {
3879 if (ERROR("SPACING",
3880 "space prohibited before that '$op' $at\n" . $hereptr)) {
3885 if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
3886 if (ERROR("SPACING",
3887 "space required after that '$op' $at\n" . $hereptr)) {
3893 if ($rtrim_before || $space_after) {
3894 if ($rtrim_before) {
3895 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3897 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3904 # '*' as part of a type definition -- reported already.
3905 } elsif ($opv eq '*_') {
3906 #warn "'*' is part of type\n";
3908 # unary operators should have a space before and
3909 # none after. May be left adjacent to another
3910 # unary operator, or a cast
3911 } elsif ($op eq '!' || $op eq '~' ||
3912 $opv eq '*U' || $opv eq '-U' ||
3913 $opv eq '&U' || $opv eq '&&U') {
3914 if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
3915 if (ERROR("SPACING",
3916 "space required before that '$op' $at\n" . $hereptr)) {
3917 if ($n != $last_after + 2) {
3918 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
3923 if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
3924 # A unary '*' may be const
3926 } elsif ($ctx =~ /.xW/) {
3927 if (ERROR("SPACING",
3928 "space prohibited after that '$op' $at\n" . $hereptr)) {
3929 $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
3930 if (defined $fix_elements[$n + 2]) {
3931 $fix_elements[$n + 2] =~ s/^\s+//;
3937 # unary ++ and unary -- are allowed no space on one side.
3938 } elsif ($op eq '++' or $op eq '--') {
3939 if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
3940 if (ERROR("SPACING",
3941 "space required one side of that '$op' $at\n" . $hereptr)) {
3942 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
3946 if ($ctx =~ /Wx[BE]/ ||
3947 ($ctx =~ /Wx./ && $cc =~ /^;/)) {
3948 if (ERROR("SPACING",
3949 "space prohibited before that '$op' $at\n" . $hereptr)) {
3950 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
3954 if ($ctx =~ /ExW/) {
3955 if (ERROR("SPACING",
3956 "space prohibited after that '$op' $at\n" . $hereptr)) {
3957 $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
3958 if (defined $fix_elements[$n + 2]) {
3959 $fix_elements[$n + 2] =~ s/^\s+//;
3965 # << and >> may either have or not have spaces both sides
3966 } elsif ($op eq '<<' or $op eq '>>' or
3967 $op eq '&' or $op eq '^' or $op eq '|' or
3968 $op eq '+' or $op eq '-' or
3969 $op eq '*' or $op eq '/' or
3973 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
3975 "spaces preferred around that '$op' $at\n" . $hereptr)) {
3976 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3977 $fix_elements[$n + 2] =~ s/^\s+//;
3980 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
3982 "space preferred before that '$op' $at\n" . $hereptr)) {
3983 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
3987 } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
3988 if (ERROR("SPACING",
3989 "need consistent spacing around '$op' $at\n" . $hereptr)) {
3990 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
3991 if (defined $fix_elements[$n + 2]) {
3992 $fix_elements[$n + 2] =~ s/^\s+//;
3998 # A colon needs no spaces before when it is
3999 # terminating a case value or a label.
4000 } elsif ($opv eq ':C' || $opv eq ':L') {
4001 if ($ctx =~ /Wx./) {
4002 if (ERROR("SPACING",
4003 "space prohibited before that '$op' $at\n" . $hereptr)) {
4004 $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4009 # All the others need spaces both sides.
4010 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4013 # Ignore email addresses <foo@bar>
4015 $cc =~ /^\S+\@\S+>/) ||
4017 $ca =~ /<\S+\@\S+$/))
4022 # for asm volatile statements
4023 # ignore a colon with another
4024 # colon immediately before or after
4026 ($ca =~ /:$/ || $cc =~ /^:/)) {
4030 # messages are ERROR, but ?: are CHK
4032 my $msg_type = \&ERROR;
4033 $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4035 if (&{$msg_type}("SPACING",
4036 "spaces required around that '$op' $at\n" . $hereptr)) {
4037 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4038 if (defined $fix_elements[$n + 2]) {
4039 $fix_elements[$n + 2] =~ s/^\s+//;
4045 $off += length($elements[$n + 1]);
4047 ## print("n: <$n> GOOD: <$good>\n");
4049 $fixed_line = $fixed_line . $good;
4052 if (($#elements % 2) == 0) {
4053 $fixed_line = $fixed_line . $fix_elements[$#elements];
4056 if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4057 $fixed[$fixlinenr] = $fixed_line;
4063 # check for whitespace before a non-naked semicolon
4064 if ($line =~ /^\+.*\S\s+;\s*$/) {
4066 "space prohibited before semicolon\n" . $herecurr) &&
4068 1 while $fixed[$fixlinenr] =~
4069 s/^(\+.*\S)\s+;/$1;/;
4073 # check for multiple assignments
4074 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4075 CHK("MULTIPLE_ASSIGNMENTS",
4076 "multiple assignments should be avoided\n" . $herecurr);
4079 ## # check for multiple declarations, allowing for a function declaration
4081 ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4082 ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4084 ## # Remove any bracketed sections to ensure we do not
4085 ## # falsly report the parameters of functions.
4087 ## while ($ln =~ s/\([^\(\)]*\)//g) {
4089 ## if ($ln =~ /,/) {
4090 ## WARN("MULTIPLE_DECLARATION",
4091 ## "declaring multiple variables together should be avoided\n" . $herecurr);
4095 #need space before brace following if, while, etc
4096 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\){/) ||
4098 if (ERROR("SPACING",
4099 "space required before the open brace '{'\n" . $herecurr) &&
4101 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|\))){/$1 {/;
4105 ## # check for blank lines before declarations
4106 ## if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4107 ## $prevrawline =~ /^.\s*$/) {
4109 ## "No blank lines before declarations\n" . $hereprev);
4113 # closing brace should have a space following it when it has anything
4115 if ($line =~ /}(?!(?:,|;|\)))\S/) {
4116 if (ERROR("SPACING",
4117 "space required after that close brace '}'\n" . $herecurr) &&
4119 $fixed[$fixlinenr] =~
4120 s/}((?!(?:,|;|\)))\S)/} $1/;
4124 # check spacing on square brackets
4125 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4126 if (ERROR("SPACING",
4127 "space prohibited after that open square bracket '['\n" . $herecurr) &&
4129 $fixed[$fixlinenr] =~
4133 if ($line =~ /\s\]/) {
4134 if (ERROR("SPACING",
4135 "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4137 $fixed[$fixlinenr] =~
4142 # check spacing on parentheses
4143 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4144 $line !~ /for\s*\(\s+;/) {
4145 if (ERROR("SPACING",
4146 "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4148 $fixed[$fixlinenr] =~
4152 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4153 $line !~ /for\s*\(.*;\s+\)/ &&
4154 $line !~ /:\s+\)/) {
4155 if (ERROR("SPACING",
4156 "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4158 $fixed[$fixlinenr] =~
4163 # check unnecessary parentheses around addressof/dereference single $Lvals
4164 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4166 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4168 if (CHK("UNNECESSARY_PARENTHESES",
4169 "Unnecessary parentheses around $var\n" . $herecurr) &&
4171 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4175 # check for unnecessary parentheses around function pointer uses
4176 # ie: (foo->bar)(); should be foo->bar();
4177 # but not "if (foo->bar) (" to avoid some false positives
4178 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4180 if (CHK("UNNECESSARY_PARENTHESES",
4181 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4183 my $var2 = deparenthesize($var);
4185 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4189 #goto labels aren't indented, allow a single space however
4190 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4191 !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4192 if (WARN("INDENTED_LABEL",
4193 "labels should not be indented\n" . $herecurr) &&
4195 $fixed[$fixlinenr] =~
4200 # return is not a function
4201 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4203 if ($^V && $^V ge 5.10.0 &&
4204 $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4206 $value = deparenthesize($value);
4207 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4208 ERROR("RETURN_PARENTHESES",
4209 "return is not a function, parentheses are not required\n" . $herecurr);
4211 } elsif ($spacing !~ /\s+/) {
4213 "space required before the open parenthesis '('\n" . $herecurr);
4217 # unnecessary return in a void function
4218 # at end-of-function, with the previous line a single leading tab, then return;
4219 # and the line before that not a goto label target like "out:"
4220 if ($sline =~ /^[ \+]}\s*$/ &&
4221 $prevline =~ /^\+\treturn\s*;\s*$/ &&
4223 $lines[$linenr - 3] =~ /^[ +]/ &&
4224 $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4226 "void function return statements are not generally useful\n" . $hereprev);
4229 # if statements using unnecessary parentheses - ie: if ((foo == bar))
4230 if ($^V && $^V ge 5.10.0 &&
4231 $line =~ /\bif\s*((?:\(\s*){2,})/) {
4232 my $openparens = $1;
4233 my $count = $openparens =~ tr@\(@\(@;
4235 if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4236 my $comp = $4; #Not $1 because of $LvalOrFunc
4237 $msg = " - maybe == should be = ?" if ($comp eq "==");
4238 WARN("UNNECESSARY_PARENTHESES",
4239 "Unnecessary parentheses$msg\n" . $herecurr);
4243 # comparisons with a constant or upper case identifier on the left
4244 # avoid cases like "foo + BAR < baz"
4245 # only fix matches surrounded by parentheses to avoid incorrect
4246 # conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4247 if ($^V && $^V ge 5.10.0 &&
4248 $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4253 my $newcomp = $comp;
4254 if ($lead !~ /$Operators\s*$/ &&
4255 $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4256 WARN("CONSTANT_COMPARISON",
4257 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4261 } elsif ($comp eq "<=") {
4263 } elsif ($comp eq ">") {
4265 } elsif ($comp eq ">=") {
4268 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4272 # Return of what appears to be an errno should normally be negative
4273 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4275 if ($name ne 'EOF' && $name ne 'ERROR') {
4276 WARN("USE_NEGATIVE_ERRNO",
4277 "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4281 # Need a space before open parenthesis after if, while etc
4282 if ($line =~ /\b(if|while|for|switch)\(/) {
4283 if (ERROR("SPACING",
4284 "space required before the open parenthesis '('\n" . $herecurr) &&
4286 $fixed[$fixlinenr] =~
4287 s/\b(if|while|for|switch)\(/$1 \(/;
4291 # Check for illegal assignment in if conditional -- and check for trailing
4292 # statements after the conditional.
4293 if ($line =~ /do\s*(?!{)/) {
4294 ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4295 ctx_statement_block($linenr, $realcnt, 0)
4296 if (!defined $stat);
4297 my ($stat_next) = ctx_statement_block($line_nr_next,
4298 $remain_next, $off_next);
4299 $stat_next =~ s/\n./\n /g;
4300 ##print "stat<$stat> stat_next<$stat_next>\n";
4302 if ($stat_next =~ /^\s*while\b/) {
4303 # If the statement carries leading newlines,
4304 # then count those as offsets.
4306 ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4308 statement_rawlines($whitespace) - 1;
4310 $suppress_whiletrailers{$line_nr_next +
4314 if (!defined $suppress_whiletrailers{$linenr} &&
4315 defined($stat) && defined($cond) &&
4316 $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4317 my ($s, $c) = ($stat, $cond);
4319 if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4320 ERROR("ASSIGN_IN_IF",
4321 "do not use assignment in if condition\n" . $herecurr);
4324 # Find out what is on the end of the line after the
4326 substr($s, 0, length($c), '');
4328 $s =~ s/$;//g; # Remove any comments
4329 if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4330 $c !~ /}\s*while\s*/)
4332 # Find out how long the conditional actually is.
4333 my @newlines = ($c =~ /\n/gs);
4334 my $cond_lines = 1 + $#newlines;
4337 $stat_real = raw_line($linenr, $cond_lines)
4338 . "\n" if ($cond_lines);
4339 if (defined($stat_real) && $cond_lines > 1) {
4340 $stat_real = "[...]\n$stat_real";
4343 ERROR("TRAILING_STATEMENTS",
4344 "trailing statements should be on next line\n" . $herecurr . $stat_real);
4348 # Check for bitwise tests written as boolean
4360 WARN("HEXADECIMAL_BOOLEAN_TEST",
4361 "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4364 # if and else should not have general statements after it
4365 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4367 $s =~ s/$;//g; # Remove any comments
4368 if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4369 ERROR("TRAILING_STATEMENTS",
4370 "trailing statements should be on next line\n" . $herecurr);
4373 # if should not continue a brace
4374 if ($line =~ /}\s*if\b/) {
4375 ERROR("TRAILING_STATEMENTS",
4376 "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4379 # case and default should not have general statements after them
4380 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4382 (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4386 ERROR("TRAILING_STATEMENTS",
4387 "trailing statements should be on next line\n" . $herecurr);
4390 # Check for }<nl>else {, these must be at the same
4391 # indent level to be relevant to each other.
4392 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4393 $previndent == $indent) {
4394 if (ERROR("ELSE_AFTER_BRACE",
4395 "else should follow close brace '}'\n" . $hereprev) &&
4396 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4397 fix_delete_line($fixlinenr - 1, $prevrawline);
4398 fix_delete_line($fixlinenr, $rawline);
4399 my $fixedline = $prevrawline;
4400 $fixedline =~ s/}\s*$//;
4401 if ($fixedline !~ /^\+\s*$/) {
4402 fix_insert_line($fixlinenr, $fixedline);
4404 $fixedline = $rawline;
4405 $fixedline =~ s/^(.\s*)else/$1} else/;
4406 fix_insert_line($fixlinenr, $fixedline);
4410 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
4411 $previndent == $indent) {
4412 my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
4414 # Find out what is on the end of the line after the
4416 substr($s, 0, length($c), '');
4419 if ($s =~ /^\s*;/) {
4420 if (ERROR("WHILE_AFTER_BRACE",
4421 "while should follow close brace '}'\n" . $hereprev) &&
4422 $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4423 fix_delete_line($fixlinenr - 1, $prevrawline);
4424 fix_delete_line($fixlinenr, $rawline);
4425 my $fixedline = $prevrawline;
4426 my $trailing = $rawline;
4427 $trailing =~ s/^\+//;
4428 $trailing = trim($trailing);
4429 $fixedline =~ s/}\s*$/} $trailing/;
4430 fix_insert_line($fixlinenr, $fixedline);
4435 #Specific variable tests
4436 while ($line =~ m{($Constant|$Lval)}g) {
4439 #gcc binary extension
4440 if ($var =~ /^$Binary$/) {
4441 if (WARN("GCC_BINARY_CONSTANT",
4442 "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) &&
4444 my $hexval = sprintf("0x%x", oct($var));
4445 $fixed[$fixlinenr] =~
4446 s/\b$var\b/$hexval/;
4451 if ($var !~ /^$Constant$/ &&
4452 $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
4453 #Ignore Page<foo> variants
4454 $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
4455 #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
4456 $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
4457 #Ignore some three character SI units explicitly, like MiB and KHz
4458 $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
4459 while ($var =~ m{($Ident)}g) {
4461 next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
4463 seed_camelcase_includes();
4464 if (!$file && !$camelcase_file_seeded) {
4465 seed_camelcase_file($realfile);
4466 $camelcase_file_seeded = 1;
4469 if (!defined $camelcase{$word}) {
4470 $camelcase{$word} = 1;
4472 "Avoid CamelCase: <$word>\n" . $herecurr);
4478 #no spaces allowed after \ in define
4479 if ($line =~ /\#\s*define.*\\\s+$/) {
4480 if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
4481 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
4483 $fixed[$fixlinenr] =~ s/\s+$//;
4487 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
4488 # itself <asm/foo.h> (uses RAW line)
4489 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
4491 my $checkfile = "include/linux/$file";
4492 if (-f "$root/$checkfile" &&
4493 $realfile ne $checkfile &&
4494 $1 !~ /$allowed_asm_includes/)
4496 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
4497 if ($asminclude > 0) {
4498 if ($realfile =~ m{^arch/}) {
4499 CHK("ARCH_INCLUDE_LINUX",
4500 "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4502 WARN("INCLUDE_LINUX",
4503 "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
4509 # multi-statement macros should be enclosed in a do while loop, grab the
4510 # first statement and ensure its the whole macro if its not enclosed
4511 # in a known good container
4512 if ($realfile !~ m@/vmlinux.lds.h$@ &&
4513 $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
4516 my ($off, $dstat, $dcond, $rest);
4518 my $has_flow_statement = 0;
4519 my $has_arg_concat = 0;
4520 ($dstat, $dcond, $ln, $cnt, $off) =
4521 ctx_statement_block($linenr, $realcnt, 0);
4523 #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
4524 #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
4526 $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
4527 $has_arg_concat = 1 if ($ctx =~ /\#\#/);
4529 $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//;
4531 $dstat =~ s/\\\n.//g;
4532 $dstat =~ s/^\s*//s;
4533 $dstat =~ s/\s*$//s;
4535 # Flatten any parentheses and braces
4536 while ($dstat =~ s/\([^\(\)]*\)/1/ ||
4537 $dstat =~ s/\{[^\{\}]*\}/1/ ||
4538 $dstat =~ s/\[[^\[\]]*\]/1/)
4542 # Flatten any obvious string concatentation.
4543 while ($dstat =~ s/($String)\s*$Ident/$1/ ||
4544 $dstat =~ s/$Ident\s*($String)/$1/)
4548 my $exceptions = qr{
4560 #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
4562 $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(),
4563 $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo();
4564 $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
4565 $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ && # character constants
4566 $dstat !~ /$exceptions/ &&
4567 $dstat !~ /^\.$Ident\s*=/ && # .foo =
4568 $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo
4569 $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...)
4570 $dstat !~ /^for\s*$Constant$/ && # for (...)
4571 $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar()
4572 $dstat !~ /^do\s*{/ && # do {...
4573 $dstat !~ /^\(\{/ && # ({...
4574 $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
4577 my $herectx = $here . "\n";
4578 my $cnt = statement_rawlines($ctx);
4580 for (my $n = 0; $n < $cnt; $n++) {
4581 $herectx .= raw_line($linenr, $n) . "\n";
4584 if ($dstat =~ /;/) {
4585 ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
4586 "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
4588 ERROR("COMPLEX_MACRO",
4589 "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
4593 # check for macros with flow control, but without ## concatenation
4594 # ## concatenation is commonly a macro that defines a function so ignore those
4595 if ($has_flow_statement && !$has_arg_concat) {
4596 my $herectx = $here . "\n";
4597 my $cnt = statement_rawlines($ctx);
4599 for (my $n = 0; $n < $cnt; $n++) {
4600 $herectx .= raw_line($linenr, $n) . "\n";
4602 WARN("MACRO_WITH_FLOW_CONTROL",
4603 "Macros with flow control statements should be avoided\n" . "$herectx");
4606 # check for line continuations outside of #defines, preprocessor #, and asm
4609 if ($prevline !~ /^..*\\$/ &&
4610 $line !~ /^\+\s*\#.*\\$/ && # preprocessor
4611 $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm
4612 $line =~ /^\+.*\\$/) {
4613 WARN("LINE_CONTINUATIONS",
4614 "Avoid unnecessary line continuations\n" . $herecurr);
4618 # do {} while (0) macro tests:
4619 # single-statement macros do not need to be enclosed in do while (0) loop,
4620 # macro should not end with a semicolon
4621 if ($^V && $^V ge 5.10.0 &&
4622 $realfile !~ m@/vmlinux.lds.h$@ &&
4623 $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
4626 my ($off, $dstat, $dcond, $rest);
4628 ($dstat, $dcond, $ln, $cnt, $off) =
4629 ctx_statement_block($linenr, $realcnt, 0);
4632 $dstat =~ s/\\\n.//g;
4635 if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
4640 my $cnt = statement_rawlines($ctx);
4641 my $herectx = $here . "\n";
4643 for (my $n = 0; $n < $cnt; $n++) {
4644 $herectx .= raw_line($linenr, $n) . "\n";
4647 if (($stmts =~ tr/;/;/) == 1 &&
4648 $stmts !~ /^\s*(if|while|for|switch)\b/) {
4649 WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
4650 "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
4652 if (defined $semis && $semis ne "") {
4653 WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
4654 "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
4656 } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
4658 my $cnt = statement_rawlines($ctx);
4659 my $herectx = $here . "\n";
4661 for (my $n = 0; $n < $cnt; $n++) {
4662 $herectx .= raw_line($linenr, $n) . "\n";
4665 WARN("TRAILING_SEMICOLON",
4666 "macros should not use a trailing semicolon\n" . "$herectx");
4670 # make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
4671 # all assignments may have only one of the following with an assignment:
4674 # VMLINUX_SYMBOL(...)
4675 if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
4676 WARN("MISSING_VMLINUX_SYMBOL",
4677 "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
4680 # check for redundant bracing round if etc
4681 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
4682 my ($level, $endln, @chunks) =
4683 ctx_statement_full($linenr, $realcnt, 1);
4684 #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
4685 #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
4686 if ($#chunks > 0 && $level == 0) {
4690 my $herectx = $here . "\n";
4691 my $ln = $linenr - 1;
4692 for my $chunk (@chunks) {
4693 my ($cond, $block) = @{$chunk};
4695 # If the condition carries leading newlines, then count those as offsets.
4696 my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
4697 my $offset = statement_rawlines($whitespace) - 1;
4699 $allowed[$allow] = 0;
4700 #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
4702 # We have looked at and allowed this specific line.
4703 $suppress_ifbraces{$ln + $offset} = 1;
4705 $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
4706 $ln += statement_rawlines($block) - 1;
4708 substr($block, 0, length($cond), '');
4710 $seen++ if ($block =~ /^\s*{/);
4712 #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
4713 if (statement_lines($cond) > 1) {
4714 #print "APW: ALLOWED: cond<$cond>\n";
4715 $allowed[$allow] = 1;
4717 if ($block =~/\b(?:if|for|while)\b/) {
4718 #print "APW: ALLOWED: block<$block>\n";
4719 $allowed[$allow] = 1;
4721 if (statement_block_size($block) > 1) {
4722 #print "APW: ALLOWED: lines block<$block>\n";
4723 $allowed[$allow] = 1;
4728 my $sum_allowed = 0;
4729 foreach (@allowed) {
4732 if ($sum_allowed == 0) {
4734 "braces {} are not necessary for any arm of this statement\n" . $herectx);
4735 } elsif ($sum_allowed != $allow &&
4738 "braces {} should be used on all arms of this statement\n" . $herectx);
4743 if (!defined $suppress_ifbraces{$linenr - 1} &&
4744 $line =~ /\b(if|while|for|else)\b/) {
4747 # Check the pre-context.
4748 if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
4749 #print "APW: ALLOWED: pre<$1>\n";
4753 my ($level, $endln, @chunks) =
4754 ctx_statement_full($linenr, $realcnt, $-[0]);
4756 # Check the condition.
4757 my ($cond, $block) = @{$chunks[0]};
4758 #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
4759 if (defined $cond) {
4760 substr($block, 0, length($cond), '');
4762 if (statement_lines($cond) > 1) {
4763 #print "APW: ALLOWED: cond<$cond>\n";
4766 if ($block =~/\b(?:if|for|while)\b/) {
4767 #print "APW: ALLOWED: block<$block>\n";
4770 if (statement_block_size($block) > 1) {
4771 #print "APW: ALLOWED: lines block<$block>\n";
4774 # Check the post-context.
4775 if (defined $chunks[1]) {
4776 my ($cond, $block) = @{$chunks[1]};
4777 if (defined $cond) {
4778 substr($block, 0, length($cond), '');
4780 if ($block =~ /^\s*\{/) {
4781 #print "APW: ALLOWED: chunk-1 block<$block>\n";
4785 if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
4786 my $herectx = $here . "\n";
4787 my $cnt = statement_rawlines($block);
4789 for (my $n = 0; $n < $cnt; $n++) {
4790 $herectx .= raw_line($linenr, $n) . "\n";
4794 "braces {} are not necessary for single statement blocks\n" . $herectx);
4798 # check for unnecessary blank lines around braces
4799 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
4801 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
4802 $fix && $prevrawline =~ /^\+/) {
4803 fix_delete_line($fixlinenr - 1, $prevrawline);
4806 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
4808 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
4810 fix_delete_line($fixlinenr, $rawline);
4814 # no volatiles please
4815 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
4816 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
4818 "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
4821 # Check for user-visible strings broken across lines, which breaks the ability
4822 # to grep for the string. Make exceptions when the previous string ends in a
4823 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
4824 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
4825 if ($line =~ /^\+\s*$String/ &&
4826 $prevline =~ /"\s*$/ &&
4827 $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
4828 if (WARN("SPLIT_STRING",
4829 "quoted string split across lines\n" . $hereprev) &&
4831 $prevrawline =~ /^\+.*"\s*$/ &&
4832 $last_coalesced_string_linenr != $linenr - 1) {
4833 my $extracted_string = get_quoted_string($line, $rawline);
4834 my $comma_close = "";
4835 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
4839 fix_delete_line($fixlinenr - 1, $prevrawline);
4840 fix_delete_line($fixlinenr, $rawline);
4841 my $fixedline = $prevrawline;
4842 $fixedline =~ s/"\s*$//;
4843 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
4844 fix_insert_line($fixlinenr - 1, $fixedline);
4845 $fixedline = $rawline;
4846 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
4847 if ($fixedline !~ /\+\s*$/) {
4848 fix_insert_line($fixlinenr, $fixedline);
4850 $last_coalesced_string_linenr = $linenr;
4854 # check for missing a space in a string concatenation
4855 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
4856 WARN('MISSING_SPACE',
4857 "break quoted strings at a space character\n" . $hereprev);
4860 # check for spaces before a quoted newline
4861 if ($rawline =~ /^.*\".*\s\\n/) {
4862 if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
4863 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
4865 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
4870 # concatenated string without spaces between elements
4871 if ($line =~ /$String[A-Z_]/ || $line =~ /[A-Za-z0-9_]$String/) {
4872 CHK("CONCATENATED_STRING",
4873 "Concatenated strings should use spaces between elements\n" . $herecurr);
4876 # uncoalesced string fragments
4877 if ($line =~ /$String\s*"/) {
4878 WARN("STRING_FRAGMENTS",
4879 "Consecutive strings are generally better as a single string\n" . $herecurr);
4882 # check for %L{u,d,i} and 0x%[udi] in strings
4884 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
4885 $string = substr($rawline, $-[1], $+[1] - $-[1]);
4886 $string =~ s/%%/__/g;
4887 if ($string =~ /(?<!%)%[\*\d\.\$]*L[udi]/) {
4889 "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
4892 if ($string =~ /0x%[\*\d\.\$\Llzth]*[udi]/) {
4893 ERROR("PRINTF_0xDECIMAL",
4894 "Prefixing 0x with decimal output is defective\n" . $herecurr);
4898 # check for line continuations in quoted strings with odd counts of "
4899 if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) {
4900 WARN("LINE_CONTINUATIONS",
4901 "Avoid line continuations in quoted strings\n" . $herecurr);
4905 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
4906 CHK("REDUNDANT_CODE",
4907 "if this code is redundant consider removing it\n" .
4911 # check for needless "if (<foo>) fn(<foo>)" uses
4912 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
4913 my $tested = quotemeta($1);
4914 my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
4915 if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
4917 if (WARN('NEEDLESS_IF',
4918 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
4921 my $leading_tabs = "";
4922 my $new_leading_tabs = "";
4923 if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
4928 if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
4929 $new_leading_tabs = $1;
4930 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
4937 fix_delete_line($fixlinenr - 1, $prevrawline);
4938 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
4944 # check for unnecessary "Out of Memory" messages
4945 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
4946 $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
4947 (defined $1 || defined $3) &&
4950 my $testline = $lines[$linenr - 3];
4952 my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
4953 # print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
4955 if ($c =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*(?:devm_)?(?:[kv][czm]alloc(?:_node|_array)?\b|kstrdup|(?:dev_)?alloc_skb)/) {
4957 "Possible unnecessary 'out of memory' message\n" . $hereprev);
4961 # check for logging functions with KERN_<LEVEL>
4962 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
4963 $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
4965 if (WARN("UNNECESSARY_KERN_LEVEL",
4966 "Possible unnecessary $level\n" . $herecurr) &&
4968 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
4972 # check for mask then right shift without a parentheses
4973 if ($^V && $^V ge 5.10.0 &&
4974 $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
4975 $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
4976 WARN("MASK_THEN_SHIFT",
4977 "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
4980 # check for pointer comparisons to NULL
4981 if ($^V && $^V ge 5.10.0) {
4982 while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
4985 $equal = "" if ($4 eq "!=");
4986 if (CHK("COMPARISON_TO_NULL",
4987 "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
4989 $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
4994 # check for bad placement of section $InitAttribute (e.g.: __initdata)
4995 if ($line =~ /(\b$InitAttribute\b)/) {
4997 if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5000 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5001 ERROR("MISPLACED_INIT",
5002 "$attr should be placed after $var\n" . $herecurr)) ||
5003 ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5004 WARN("MISPLACED_INIT",
5005 "$attr should be placed after $var\n" . $herecurr))) &&
5007 $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;
5012 # check for $InitAttributeData (ie: __initdata) with const
5013 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5015 $attr =~ /($InitAttributePrefix)(.*)/;
5016 my $attr_prefix = $1;
5018 if (ERROR("INIT_ATTRIBUTE",
5019 "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5021 $fixed[$fixlinenr] =~
5022 s/$InitAttributeData/${attr_prefix}initconst/;
5026 # check for $InitAttributeConst (ie: __initconst) without const
5027 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5029 if (ERROR("INIT_ATTRIBUTE",
5030 "Use of $attr requires a separate use of const\n" . $herecurr) &&
5032 my $lead = $fixed[$fixlinenr] =~
5033 /(^\+\s*(?:static\s+))/;
5035 $lead = "$lead " if ($lead !~ /^\+$/);
5036 $lead = "${lead}const ";
5037 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5041 # check for __read_mostly with const non-pointer (should just be const)
5042 if ($line =~ /\b__read_mostly\b/ &&
5043 $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5044 if (ERROR("CONST_READ_MOSTLY",
5045 "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5047 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5051 # don't use __constant_<foo> functions outside of include/uapi/
5052 if ($realfile !~ m@^include/uapi/@ &&
5053 $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5054 my $constant_func = $1;
5055 my $func = $constant_func;
5056 $func =~ s/^__constant_//;
5057 if (WARN("CONSTANT_CONVERSION",
5058 "$constant_func should be $func\n" . $herecurr) &&
5060 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5064 # prefer usleep_range over udelay
5065 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5067 # ignore udelay's < 10, however
5068 if (! ($delay < 10) ) {
5070 "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5072 if ($delay > 2000) {
5074 "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5078 # warn about unexpectedly long msleep's
5079 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5082 "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $herecurr);
5086 # check for comparisons of jiffies
5087 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5088 WARN("JIFFIES_COMPARISON",
5089 "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5092 # check for comparisons of get_jiffies_64()
5093 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5094 WARN("JIFFIES_COMPARISON",
5095 "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5098 # warn about #ifdefs in C files
5099 # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5100 # print "#ifdef in C files should be avoided\n";
5101 # print "$herecurr";
5105 # warn about spacing in #ifdefs
5106 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5107 if (ERROR("SPACING",
5108 "exactly one space required after that #$1\n" . $herecurr) &&
5110 $fixed[$fixlinenr] =~
5111 s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5116 # check for spinlock_t definitions without a comment.
5117 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5118 $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5120 if (!ctx_has_comment($first_line, $linenr)) {
5121 CHK("UNCOMMENTED_DEFINITION",
5122 "$1 definition without comment\n" . $herecurr);
5125 # check for memory barriers without a comment.
5126 if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
5127 if (!ctx_has_comment($first_line, $linenr)) {
5128 WARN("MEMORY_BARRIER",
5129 "memory barrier without comment\n" . $herecurr);
5133 # check for waitqueue_active without a comment.
5134 if ($line =~ /\bwaitqueue_active\s*\(/) {
5135 if (!ctx_has_comment($first_line, $linenr)) {
5136 WARN("WAITQUEUE_ACTIVE",
5137 "waitqueue_active without comment\n" . $herecurr);
5141 # Check for expedited grace periods that interrupt non-idle non-nohz
5142 # online CPUs. These expedited can therefore degrade real-time response
5143 # if used carelessly, and should be avoided where not absolutely
5144 # needed. It is always OK to use synchronize_rcu_expedited() and
5145 # synchronize_sched_expedited() at boot time (before real-time applications
5146 # start) and in error situations where real-time response is compromised in
5147 # any case. Note that synchronize_srcu_expedited() does -not- interrupt
5148 # other CPUs, so don't warn on uses of synchronize_srcu_expedited().
5149 # Of course, nothing comes for free, and srcu_read_lock() and
5150 # srcu_read_unlock() do contain full memory barriers in payment for
5151 # synchronize_srcu_expedited() non-interruption properties.
5152 if ($line =~ /\b(synchronize_rcu_expedited|synchronize_sched_expedited)\(/) {
5153 WARN("EXPEDITED_RCU_GRACE_PERIOD",
5154 "expedited RCU grace periods should be avoided where they can degrade real-time response\n" . $herecurr);
5158 # check of hardware specific defines
5159 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5161 "architecture specific defines should be avoided\n" . $herecurr);
5164 # Check that the storage class is at the beginning of a declaration
5165 if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
5166 WARN("STORAGE_CLASS",
5167 "storage class should be at the beginning of the declaration\n" . $herecurr)
5170 # check the location of the inline attribute, that it is between
5171 # storage class and type.
5172 if ($line =~ /\b$Type\s+$Inline\b/ ||
5173 $line =~ /\b$Inline\s+$Storage\b/) {
5174 ERROR("INLINE_LOCATION",
5175 "inline keyword should sit between storage class and type\n" . $herecurr);
5178 # Check for __inline__ and __inline, prefer inline
5179 if ($realfile !~ m@\binclude/uapi/@ &&
5180 $line =~ /\b(__inline__|__inline)\b/) {
5182 "plain inline is preferred over $1\n" . $herecurr) &&
5184 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5189 # Check for __attribute__ packed, prefer __packed
5190 if ($realfile !~ m@\binclude/uapi/@ &&
5191 $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5192 WARN("PREFER_PACKED",
5193 "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5196 # Check for __attribute__ aligned, prefer __aligned
5197 if ($realfile !~ m@\binclude/uapi/@ &&
5198 $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5199 WARN("PREFER_ALIGNED",
5200 "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5203 # Check for __attribute__ format(printf, prefer __printf
5204 if ($realfile !~ m@\binclude/uapi/@ &&
5205 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5206 if (WARN("PREFER_PRINTF",
5207 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5209 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5214 # Check for __attribute__ format(scanf, prefer __scanf
5215 if ($realfile !~ m@\binclude/uapi/@ &&
5216 $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5217 if (WARN("PREFER_SCANF",
5218 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5220 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5224 # Check for __attribute__ weak, or __weak declarations (may have link issues)
5225 if ($^V && $^V ge 5.10.0 &&
5226 $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5227 ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5228 $line =~ /\b__weak\b/)) {
5229 ERROR("WEAK_DECLARATION",
5230 "Using weak declarations can have unintended link defects\n" . $herecurr);
5233 # check for c99 types like uint8_t used outside of uapi/
5234 if ($realfile !~ m@\binclude/uapi/@ &&
5235 $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5237 if ($type =~ /\b($typeC99Typedefs)\b/) {
5239 my $kernel_type = 'u';
5240 $kernel_type = 's' if ($type =~ /^_*[si]/);
5243 if (CHK("PREFER_KERNEL_TYPES",
5244 "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5246 $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5251 # check for sizeof(&)
5252 if ($line =~ /\bsizeof\s*\(\s*\&/) {
5253 WARN("SIZEOF_ADDRESS",
5254 "sizeof(& should be avoided\n" . $herecurr);
5257 # check for sizeof without parenthesis
5258 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5259 if (WARN("SIZEOF_PARENTHESIS",
5260 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5262 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5266 # check for struct spinlock declarations
5267 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
5268 WARN("USE_SPINLOCK_T",
5269 "struct spinlock should be spinlock_t\n" . $herecurr);
5272 # check for seq_printf uses that could be seq_puts
5273 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
5274 my $fmt = get_quoted_string($line, $rawline);
5277 if (WARN("PREFER_SEQ_PUTS",
5278 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
5280 $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
5285 # Check for misused memsets
5286 if ($^V && $^V ge 5.10.0 &&
5288 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
5294 if ($ms_size =~ /^(0x|)0$/i) {
5296 "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
5297 } elsif ($ms_size =~ /^(0x|)1$/i) {
5299 "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
5303 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
5304 if ($^V && $^V ge 5.10.0 &&
5306 $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5307 if (WARN("PREFER_ETHER_ADDR_COPY",
5308 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
5310 $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
5314 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
5315 if ($^V && $^V ge 5.10.0 &&
5317 $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5318 WARN("PREFER_ETHER_ADDR_EQUAL",
5319 "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
5322 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
5323 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
5324 if ($^V && $^V ge 5.10.0 &&
5326 $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
5330 if ($ms_val =~ /^(?:0x|)0+$/i) {
5331 if (WARN("PREFER_ETH_ZERO_ADDR",
5332 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
5334 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
5336 } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
5337 if (WARN("PREFER_ETH_BROADCAST_ADDR",
5338 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
5340 $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
5345 # typecasts on min/max could be min_t/max_t
5346 if ($^V && $^V ge 5.10.0 &&
5348 $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
5349 if (defined $2 || defined $7) {
5351 my $cast1 = deparenthesize($2);
5353 my $cast2 = deparenthesize($7);
5357 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
5358 $cast = "$cast1 or $cast2";
5359 } elsif ($cast1 ne "") {
5365 "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
5369 # check usleep_range arguments
5370 if ($^V && $^V ge 5.10.0 &&
5372 $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
5376 WARN("USLEEP_RANGE",
5377 "usleep_range should not use min == max args; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5378 } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
5380 WARN("USLEEP_RANGE",
5381 "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.txt\n" . "$here\n$stat\n");
5385 # check for naked sscanf
5386 if ($^V && $^V ge 5.10.0 &&
5388 $line =~ /\bsscanf\b/ &&
5389 ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
5390 $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
5391 $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
5392 my $lc = $stat =~ tr@\n@@;
5393 $lc = $lc + $linenr;
5394 my $stat_real = raw_line($linenr, 0);
5395 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5396 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5398 WARN("NAKED_SSCANF",
5399 "unchecked sscanf return value\n" . "$here\n$stat_real\n");
5402 # check for simple sscanf that should be kstrto<foo>
5403 if ($^V && $^V ge 5.10.0 &&
5405 $line =~ /\bsscanf\b/) {
5406 my $lc = $stat =~ tr@\n@@;
5407 $lc = $lc + $linenr;
5408 my $stat_real = raw_line($linenr, 0);
5409 for (my $count = $linenr + 1; $count <= $lc; $count++) {
5410 $stat_real = $stat_real . "\n" . raw_line($count, 0);
5412 if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
5414 my $count = $format =~ tr@%@%@;
5416 $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
5417 WARN("SSCANF_TO_KSTRTO",
5418 "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
5423 # check for new externs in .h files.
5424 if ($realfile =~ /\.h$/ &&
5425 $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
5426 if (CHK("AVOID_EXTERNS",
5427 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
5429 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
5433 # check for new externs in .c files.
5434 if ($realfile =~ /\.c$/ && defined $stat &&
5435 $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
5437 my $function_name = $1;
5438 my $paren_space = $2;
5441 if (defined $cond) {
5442 substr($s, 0, length($cond), '');
5444 if ($s =~ /^\s*;/ &&
5445 $function_name ne 'uninitialized_var')
5447 WARN("AVOID_EXTERNS",
5448 "externs should be avoided in .c files\n" . $herecurr);
5451 if ($paren_space =~ /\n/) {
5452 WARN("FUNCTION_ARGUMENTS",
5453 "arguments for function declarations should follow identifier\n" . $herecurr);
5456 } elsif ($realfile =~ /\.c$/ && defined $stat &&
5457 $stat =~ /^.\s*extern\s+/)
5459 WARN("AVOID_EXTERNS",
5460 "externs should be avoided in .c files\n" . $herecurr);
5463 # checks for new __setup's
5464 if ($rawline =~ /\b__setup\("([^"]*)"/) {
5467 if (!grep(/$name/, @setup_docs)) {
5468 CHK("UNDOCUMENTED_SETUP",
5469 "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
5473 # check for pointless casting of kmalloc return
5474 if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) {
5475 WARN("UNNECESSARY_CASTS",
5476 "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
5480 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
5481 if ($^V && $^V ge 5.10.0 &&
5482 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
5483 CHK("ALLOC_SIZEOF_STRUCT",
5484 "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
5487 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
5488 if ($^V && $^V ge 5.10.0 &&
5489 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
5493 my $newfunc = "kmalloc_array";
5494 $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
5497 if ($a1 =~ /^sizeof\s*\S/) {
5501 if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
5502 !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
5503 if (WARN("ALLOC_WITH_MULTIPLY",
5504 "Prefer $newfunc over $oldfunc with multiply\n" . $herecurr) &&
5506 $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;
5512 # check for krealloc arg reuse
5513 if ($^V && $^V ge 5.10.0 &&
5514 $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {
5515 WARN("KREALLOC_ARG_REUSE",
5516 "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
5519 # check for alloc argument mismatch
5520 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
5521 WARN("ALLOC_ARRAY_ARGS",
5522 "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
5525 # check for multiple semicolons
5526 if ($line =~ /;\s*;\s*$/) {
5527 if (WARN("ONE_SEMICOLON",
5528 "Statements terminations use 1 semicolon\n" . $herecurr) &&
5530 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
5534 # check for #defines like: 1 << <digit> that could be BIT(digit)
5535 if ($line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
5537 $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
5538 if (CHK("BIT_MACRO",
5539 "Prefer using the BIT$ull macro\n" . $herecurr) &&
5541 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
5545 # check for case / default statements not preceded by break/fallthrough/switch
5546 if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
5548 my $has_statement = 0;
5550 my $prevline = $linenr;
5551 while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
5553 my $rline = $rawlines[$prevline - 1];
5554 my $fline = $lines[$prevline - 1];
5555 last if ($fline =~ /^\@\@/);
5556 next if ($fline =~ /^\-/);
5557 next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
5558 $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
5559 next if ($fline =~ /^.[\s$;]*$/);
5562 $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/);
5564 if (!$has_break && $has_statement) {
5565 WARN("MISSING_BREAK",
5566 "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr);
5570 # check for switch/default statements without a break;
5571 if ($^V && $^V ge 5.10.0 &&
5573 $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
5575 my $herectx = $here . "\n";
5576 my $cnt = statement_rawlines($stat);
5577 for (my $n = 0; $n < $cnt; $n++) {
5578 $herectx .= raw_line($linenr, $n) . "\n";
5580 WARN("DEFAULT_NO_BREAK",
5581 "switch default: should use break\n" . $herectx);
5584 # check for gcc specific __FUNCTION__
5585 if ($line =~ /\b__FUNCTION__\b/) {
5586 if (WARN("USE_FUNC",
5587 "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr) &&
5589 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
5593 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
5594 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
5596 "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
5599 # check for use of yield()
5600 if ($line =~ /\byield\s*\(\s*\)/) {
5602 "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n" . $herecurr);
5605 # check for comparisons against true and false
5606 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
5614 ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
5616 my $type = lc($otype);
5617 if ($type =~ /^(?:true|false)$/) {
5618 if (("$test" eq "==" && "$type" eq "true") ||
5619 ("$test" eq "!=" && "$type" eq "false")) {
5623 CHK("BOOL_COMPARISON",
5624 "Using comparison to $otype is error prone\n" . $herecurr);
5626 ## maybe suggesting a correct construct would better
5627 ## "Using comparison to $otype is error prone. Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
5632 # check for semaphores initialized locked
5633 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
5634 WARN("CONSIDER_COMPLETION",
5635 "consider using a completion\n" . $herecurr);
5638 # recommend kstrto* over simple_strto* and strict_strto*
5639 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
5640 WARN("CONSIDER_KSTRTO",
5641 "$1 is obsolete, use k$3 instead\n" . $herecurr);
5644 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
5645 if ($line =~ /^.\s*__initcall\s*\(/) {
5646 WARN("USE_DEVICE_INITCALL",
5647 "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
5650 # check for various structs that are normally const (ops, kgdb, device_tree)
5651 my $const_structs = qr{
5653 address_space_operations|
5655 block_device_operations|
5660 file_lock_operations|
5670 lock_manager_operations|
5677 pipe_buf_operations|
5678 platform_hibernation_ops|
5679 platform_suspend_ops|
5684 soc_pcmcia_socket_ops|
5691 if ($line !~ /\bconst\b/ &&
5692 $line =~ /\bstruct\s+($const_structs)\b/) {
5693 WARN("CONST_STRUCT",
5694 "struct $1 should normally be const\n" .
5698 # use of NR_CPUS is usually wrong
5699 # ignore definitions of NR_CPUS and usage to define arrays as likely right
5700 if ($line =~ /\bNR_CPUS\b/ &&
5701 $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
5702 $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
5703 $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
5704 $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
5705 $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
5708 "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
5711 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
5712 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
5713 ERROR("DEFINE_ARCH_HAS",
5714 "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
5717 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
5718 if ($^V && $^V ge 5.10.0 &&
5719 $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
5720 WARN("LIKELY_MISUSE",
5721 "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
5724 # whine mightly about in_atomic
5725 if ($line =~ /\bin_atomic\s*\(/) {
5726 if ($realfile =~ m@^drivers/@) {
5728 "do not use in_atomic in drivers\n" . $herecurr);
5729 } elsif ($realfile !~ m@^kernel/@) {
5731 "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
5735 # check for lockdep_set_novalidate_class
5736 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
5737 $line =~ /__lockdep_no_validate__\s*\)/ ) {
5738 if ($realfile !~ m@^kernel/lockdep@ &&
5739 $realfile !~ m@^include/linux/lockdep@ &&
5740 $realfile !~ m@^drivers/base/core@) {
5742 "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
5746 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
5747 $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
5748 WARN("EXPORTED_WORLD_WRITABLE",
5749 "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5752 # Mode permission misuses where it seems decimal should be octal
5753 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
5754 if ($^V && $^V ge 5.10.0 &&
5755 $line =~ /$mode_perms_search/) {
5756 foreach my $entry (@mode_permission_funcs) {
5757 my $func = $entry->[0];
5758 my $arg_pos = $entry->[1];
5763 $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
5765 my $test = "\\b$func\\s*\\(${skip_args}([\\d]+)\\s*[,\\)]";
5766 if ($line =~ /$test/) {
5768 $val = $6 if ($skip_args ne "");
5770 if ($val !~ /^0$/ &&
5771 (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
5772 length($val) ne 4)) {
5773 ERROR("NON_OCTAL_PERMISSIONS",
5774 "Use 4 digit octal (0777) not decimal permissions\n" . $herecurr);
5775 } elsif ($val =~ /^$Octal$/ && (oct($val) & 02)) {
5776 ERROR("EXPORTED_WORLD_WRITABLE",
5777 "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
5783 # validate content of MODULE_LICENSE against list from include/linux/module.h
5784 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
5785 my $extracted_string = get_quoted_string($line, $rawline);
5786 my $valid_licenses = qr{
5789 GPL\ and\ additional\ rights|
5795 if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
5796 WARN("MODULE_LICENSE",
5797 "unknown module license " . $extracted_string . "\n" . $herecurr);
5802 # If we have no input at all, then there is nothing to report on
5803 # so just keep quiet.
5804 if ($#rawlines == -1) {
5808 # In mailback mode only produce a report in the negative, for
5809 # things that appear to be patches.
5810 if ($mailback && ($clean == 1 || !$is_patch)) {
5814 # This is not a patch, and we are are in 'no-patch' mode so
5816 if (!$chk_patch && !$is_patch) {
5820 if (!$is_patch && $file !~ /cover-letter\.patch$/) {
5821 ERROR("NOT_UNIFIED_DIFF",
5822 "Does not appear to be a unified-diff format patch\n");
5824 if ($is_patch && $filename ne '-' && $chk_signoff && $signoff == 0) {
5825 ERROR("MISSING_SIGN_OFF",
5826 "Missing Signed-off-by: line(s)\n");
5829 print report_dump();
5830 if ($summary && !($clean == 1 && $quiet == 1)) {
5831 print "$filename " if ($summary_file);
5832 print "total: $cnt_error errors, $cnt_warn warnings, " .
5833 (($check)? "$cnt_chk checks, " : "") .
5834 "$cnt_lines lines checked\n";
5838 # If there were whitespace errors which cleanpatch can fix
5839 # then suggest that.
5840 if ($rpt_cleaners) {
5844 NOTE: Whitespace errors detected.
5845 You may wish to use scripts/cleanpatch or scripts/cleanfile
5850 if ($clean == 0 && $fix &&
5851 ("@rawlines" ne "@fixed" ||
5852 $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
5853 my $newfile = $filename;
5854 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
5858 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
5860 open($f, '>', $newfile)
5861 or die "$P: Can't open $newfile for write\n";
5862 foreach my $fixed_line (@fixed) {
5865 if ($linecount > 3) {
5866 $fixed_line =~ s/^\+//;
5867 print $f $fixed_line . "\n";
5870 print $f $fixed_line . "\n";
5878 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
5880 Do _NOT_ trust the results written to this file.
5881 Do _NOT_ submit these changes without inspecting them for correctness.
5883 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
5884 No warranties, expressed or implied...
5892 print "$vname has no obvious style problems and is ready for submission.\n";
5894 print "$vname has style problems, please review.\n";