Fork of the vendor (Boundary Devices) u-boot for Reform 2, with minor tweaks. The goal is to migrate to mainstream u-boot or barebox ASAP. The main impediment so far is the 4GB RAM config.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

6573 lines
191 KiB

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