1 #!/usr/bin/perl -w
   2 #
   3 # CDDL HEADER START
   4 #
   5 # The contents of this file are subject to the terms of the
   6 # Common Development and Distribution License (the "License").
   7 # You may not use this file except in compliance with the License.
   8 #
   9 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
  10 # or http://www.opensolaris.org/os/licensing.
  11 # See the License for the specific language governing permissions
  12 # and limitations under the License.
  13 #
  14 # When distributing Covered Code, include this CDDL HEADER in each
  15 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  16 # If applicable, add the following below this CDDL HEADER, with the
  17 # fields enclosed by brackets "[]" replaced with your own identifying
  18 # information: Portions Copyright [yyyy] [name of copyright owner]
  19 #
  20 # CDDL HEADER END
  21 #
  22 #
  23 # Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
  24 # Use is subject to license terms.
  25 #
  26 # cstyle - check for some common stylistic errors.
  27 #
  28 #       cstyle is a sort of "lint" for C coding style.
  29 #       It attempts to check for the style used in the
  30 #       kernel, sometimes known as "Bill Joy Normal Form".
  31 #
  32 #       There's a lot this can't check for, like proper indentation
  33 #       of code blocks.  There's also a lot more this could check for.
  34 #
  35 #       A note to the non perl literate:
  36 #
  37 #               perl regular expressions are pretty much like egrep
  38 #               regular expressions, with the following special symbols
  39 #
  40 #               \s      any space character
  41 #               \S      any non-space character
  42 #               \w      any "word" character [a-zA-Z0-9_]
  43 #               \W      any non-word character
  44 #               \d      a digit [0-9]
  45 #               \D      a non-digit
  46 #               \b      word boundary (between \w and \W)
  47 #               \B      non-word boundary
  48 #
  49 
  50 require 5.0;
  51 use IO::File;
  52 use Getopt::Std;
  53 use strict;
  54 
  55 my $usage =
  56 "usage: cstyle [-chpvCP] [-o constructs] file ...
  57         -c      check continuation indentation inside functions
  58         -h      perform heuristic checks that are sometimes wrong
  59         -p      perform some of the more picky checks
  60         -v      verbose
  61         -C      don't check anything in header block comments
  62         -P      check for use of non-POSIX types
  63         -o constructs
  64                 allow a comma-seperated list of optional constructs:
  65                     doxygen     allow doxygen-style block comments (/** /*!)
  66                     splint      allow splint-style lint comments (/*@ ... @*/)
  67 ";
  68 
  69 my %opts;
  70 
  71 if (!getopts("cho:pvCP", \%opts)) {
  72         print $usage;
  73         exit 2;
  74 }
  75 
  76 my $check_continuation = $opts{'c'};
  77 my $heuristic = $opts{'h'};
  78 my $picky = $opts{'p'};
  79 my $verbose = $opts{'v'};
  80 my $ignore_hdr_comment = $opts{'C'};
  81 my $check_posix_types = $opts{'P'};
  82 
  83 my $doxygen_comments = 0;
  84 my $splint_comments = 0;
  85 
  86 if (defined($opts{'o'})) {
  87         for my $x (split /,/, $opts{'o'}) {
  88                 if ($x eq "doxygen") {
  89                         $doxygen_comments = 1;
  90                 } elsif ($x eq "splint") {
  91                         $splint_comments = 1;
  92                 } else {
  93                         print "cstyle: unrecognized construct \"$x\"\n";
  94                         print $usage;
  95                         exit 2;
  96                 }
  97         }
  98 }
  99 
 100 my ($filename, $line, $prev);           # shared globals
 101 
 102 my $fmt;
 103 my $hdr_comment_start;
 104 
 105 if ($verbose) {
 106         $fmt = "%s: %d: %s\n%s\n";
 107 } else {
 108         $fmt = "%s: %d: %s\n";
 109 }
 110 
 111 if ($doxygen_comments) {
 112         # doxygen comments look like "/*!" or "/**"; allow them.
 113         $hdr_comment_start = qr/^\s*\/\*[\!\*]?$/;
 114 } else {
 115         $hdr_comment_start = qr/^\s*\/\*$/;
 116 }
 117 
 118 # Note, following must be in single quotes so that \s and \w work right.
 119 my $typename = '(int|char|short|long|unsigned|float|double' .
 120     '|\w+_t|struct\s+\w+|union\s+\w+|FILE)';
 121 
 122 # mapping of old types to POSIX compatible types
 123 my %old2posix = (
 124         'unchar' => 'uchar_t',
 125         'ushort' => 'ushort_t',
 126         'uint' => 'uint_t',
 127         'ulong' => 'ulong_t',
 128         'u_int' => 'uint_t',
 129         'u_short' => 'ushort_t',
 130         'u_long' => 'ulong_t',
 131         'u_char' => 'uchar_t',
 132         'quad' => 'quad_t'
 133 );
 134 
 135 my $lint_re = qr/\/\*(?:
 136         ARGSUSED[0-9]*|NOTREACHED|LINTLIBRARY|VARARGS[0-9]*|
 137         CONSTCOND|CONSTANTCOND|CONSTANTCONDITION|EMPTY|
 138         FALLTHRU|FALLTHROUGH|LINTED.*?|PRINTFLIKE[0-9]*|
 139         PROTOLIB[0-9]*|SCANFLIKE[0-9]*|CSTYLED.*?
 140     )\*\//x;
 141 
 142 my $splint_re = qr/\/\*@.*?@\*\//x;
 143 
 144 my $warlock_re = qr/\/\*\s*(?:
 145         VARIABLES\ PROTECTED\ BY|
 146         MEMBERS\ PROTECTED\ BY|
 147         ALL\ MEMBERS\ PROTECTED\ BY|
 148         READ-ONLY\ VARIABLES:|
 149         READ-ONLY\ MEMBERS:|
 150         VARIABLES\ READABLE\ WITHOUT\ LOCK:|
 151         MEMBERS\ READABLE\ WITHOUT\ LOCK:|
 152         LOCKS\ COVERED\ BY|
 153         LOCK\ UNNEEDED\ BECAUSE|
 154         LOCK\ NEEDED:|
 155         LOCK\ HELD\ ON\ ENTRY:|
 156         READ\ LOCK\ HELD\ ON\ ENTRY:|
 157         WRITE\ LOCK\ HELD\ ON\ ENTRY:|
 158         LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
 159         READ\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
 160         WRITE\ LOCK\ ACQUIRED\ AS\ SIDE\ EFFECT:|
 161         LOCK\ RELEASED\ AS\ SIDE\ EFFECT:|
 162         LOCK\ UPGRADED\ AS\ SIDE\ EFFECT:|
 163         LOCK\ DOWNGRADED\ AS\ SIDE\ EFFECT:|
 164         FUNCTIONS\ CALLED\ THROUGH\ POINTER|
 165         FUNCTIONS\ CALLED\ THROUGH\ MEMBER|
 166         LOCK\ ORDER:
 167     )/x;
 168 
 169 my $err_stat = 0;               # exit status
 170 
 171 if ($#ARGV >= 0) {
 172         foreach my $arg (@ARGV) {
 173                 my $fh = new IO::File $arg, "r";
 174                 if (!defined($fh)) {
 175                         printf "%s: can not open\n", $arg;
 176                 } else {
 177                         &cstyle($arg, $fh);
 178                         close $fh;
 179                 }
 180         }
 181 } else {
 182         &cstyle("<stdin>", *STDIN);
 183 }
 184 exit $err_stat;
 185 
 186 my $no_errs = 0;                # set for CSTYLED-protected lines
 187 
 188 sub err($) {
 189         my ($error) = @_;
 190         unless ($no_errs) {
 191                 printf $fmt, $filename, $., $error, $line;
 192                 $err_stat = 1;
 193         }
 194 }
 195 
 196 sub err_prefix($$) {
 197         my ($prevline, $error) = @_;
 198         my $out = $prevline."\n".$line;
 199         unless ($no_errs) {
 200                 printf $fmt, $filename, $., $error, $out;
 201                 $err_stat = 1;
 202         }
 203 }
 204 
 205 sub err_prev($) {
 206         my ($error) = @_;
 207         unless ($no_errs) {
 208                 printf $fmt, $filename, $. - 1, $error, $prev;
 209                 $err_stat = 1;
 210         }
 211 }
 212 
 213 sub cstyle($$) {
 214 
 215 my ($fn, $filehandle) = @_;
 216 $filename = $fn;                        # share it globally
 217 
 218 my $in_cpp = 0;
 219 my $next_in_cpp = 0;
 220 
 221 my $in_comment = 0;
 222 my $in_header_comment = 0;
 223 my $comment_done = 0;
 224 my $in_warlock_comment = 0;
 225 my $in_function = 0;
 226 my $in_function_header = 0;
 227 my $in_declaration = 0;
 228 my $note_level = 0;
 229 my $nextok = 0;
 230 my $nocheck = 0;
 231 
 232 my $in_string = 0;
 233 
 234 my ($okmsg, $comment_prefix);
 235 
 236 $line = '';
 237 $prev = '';
 238 reset_indent();
 239 
 240 line: while (<$filehandle>) {
 241         s/\r?\n$//;     # strip return and newline
 242 
 243         # save the original line, then remove all text from within
 244         # double or single quotes, we do not want to check such text.
 245 
 246         $line = $_;
 247 
 248         #
 249         # C allows strings to be continued with a backslash at the end of
 250         # the line.  We translate that into a quoted string on the previous
 251         # line followed by an initial quote on the next line.
 252         #
 253         # (we assume that no-one will use backslash-continuation with character
 254         # constants)
 255         #
 256         $_ = '"' . $_           if ($in_string && !$nocheck && !$in_comment);
 257 
 258         #
 259         # normal strings and characters
 260         #
 261         s/'([^\\']|\\[^xX0]|\\0[0-9]*|\\[xX][0-9a-fA-F]*)'/''/g;
 262         s/"([^\\"]|\\.)*"/\"\"/g;
 263 
 264         #
 265         # detect string continuation
 266         #
 267         if ($nocheck || $in_comment) {
 268                 $in_string = 0;
 269         } else {
 270                 #
 271                 # Now that all full strings are replaced with "", we check
 272                 # for unfinished strings continuing onto the next line.
 273                 #
 274                 $in_string =
 275                     (s/([^"](?:"")*)"([^\\"]|\\.)*\\$/$1""/ ||
 276                     s/^("")*"([^\\"]|\\.)*\\$/""/);
 277         }
 278 
 279         #
 280         # figure out if we are in a cpp directive
 281         #
 282         $in_cpp = $next_in_cpp || /^\s*#/;      # continued or started
 283         $next_in_cpp = $in_cpp && /\\$/;        # only if continued
 284 
 285         # strip off trailing backslashes, which appear in long macros
 286         s/\s*\\$//;
 287 
 288         # an /* END CSTYLED */ comment ends a no-check block.
 289         if ($nocheck) {
 290                 if (/\/\* *END *CSTYLED *\*\//) {
 291                         $nocheck = 0;
 292                 } else {
 293                         reset_indent();
 294                         next line;
 295                 }
 296         }
 297 
 298         # a /*CSTYLED*/ comment indicates that the next line is ok.
 299         if ($nextok) {
 300                 if ($okmsg) {
 301                         err($okmsg);
 302                 }
 303                 $nextok = 0;
 304                 $okmsg = 0;
 305                 if (/\/\* *CSTYLED.*\*\//) {
 306                         /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
 307                         $okmsg = $1;
 308                         $nextok = 1;
 309                 }
 310                 $no_errs = 1;
 311         } elsif ($no_errs) {
 312                 $no_errs = 0;
 313         }
 314 
 315         # check length of line.
 316         # first, a quick check to see if there is any chance of being too long.
 317         if (($line =~ tr/\t/\t/) * 7 + length($line) > 80) {
 318                 # yes, there is a chance.
 319                 # replace tabs with spaces and check again.
 320                 my $eline = $line;
 321                 1 while $eline =~
 322                     s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
 323                 if (length($eline) > 80) {
 324                         err("line > 80 characters");
 325                 }
 326         }
 327 
 328         # ignore NOTE(...) annotations (assumes NOTE is on lines by itself).
 329         if ($note_level || /\b_?NOTE\s*\(/) { # if in NOTE or this is NOTE
 330                 s/[^()]//g;                       # eliminate all non-parens
 331                 $note_level += s/\(//g - length;  # update paren nest level
 332                 next;
 333         }
 334 
 335         # a /* BEGIN CSTYLED */ comment starts a no-check block.
 336         if (/\/\* *BEGIN *CSTYLED *\*\//) {
 337                 $nocheck = 1;
 338         }
 339 
 340         # a /*CSTYLED*/ comment indicates that the next line is ok.
 341         if (/\/\* *CSTYLED.*\*\//) {
 342                 /^.*\/\* *CSTYLED *(.*) *\*\/.*$/;
 343                 $okmsg = $1;
 344                 $nextok = 1;
 345         }
 346         if (/\/\/ *CSTYLED/) {
 347                 /^.*\/\/ *CSTYLED *(.*)$/;
 348                 $okmsg = $1;
 349                 $nextok = 1;
 350         }
 351 
 352         # universal checks; apply to everything
 353         if (/\t +\t/) {
 354                 err("spaces between tabs");
 355         }
 356         if (/ \t+ /) {
 357                 err("tabs between spaces");
 358         }
 359         if (/\s$/) {
 360                 err("space or tab at end of line");
 361         }
 362         if (/[^ \t(]\/\*/ && !/\w\(\/\*.*\*\/\);/) {
 363                 err("comment preceded by non-blank");
 364         }
 365 
 366         # is this the beginning or ending of a function?
 367         # (not if "struct foo\n{\n")
 368         if (/^{$/ && $prev =~ /\)\s*(const\s*)?(\/\*.*\*\/\s*)?\\?$/) {
 369                 $in_function = 1;
 370                 $in_declaration = 1;
 371                 $in_function_header = 0;
 372                 $prev = $line;
 373                 next line;
 374         }
 375         if (/^}\s*(\/\*.*\*\/\s*)*$/) {
 376                 if ($prev =~ /^\s*return\s*;/) {
 377                         err_prev("unneeded return at end of function");
 378                 }
 379                 $in_function = 0;
 380                 reset_indent();         # we don't check between functions
 381                 $prev = $line;
 382                 next line;
 383         }
 384         if (/^\w*\($/) {
 385                 $in_function_header = 1;
 386         }
 387 
 388         if ($in_warlock_comment && /\*\//) {
 389                 $in_warlock_comment = 0;
 390                 $prev = $line;
 391                 next line;
 392         }
 393 
 394         # a blank line terminates the declarations within a function.
 395         # XXX - but still a problem in sub-blocks.
 396         if ($in_declaration && /^$/) {
 397                 $in_declaration = 0;
 398         }
 399 
 400         if ($comment_done) {
 401                 $in_comment = 0;
 402                 $in_header_comment = 0;
 403                 $comment_done = 0;
 404         }
 405         # does this looks like the start of a block comment?
 406         if (/$hdr_comment_start/) {
 407                 if (!/^\t*\/\*/) {
 408                         err("block comment not indented by tabs");
 409                 }
 410                 $in_comment = 1;
 411                 /^(\s*)\//;
 412                 $comment_prefix = $1;
 413                 if ($comment_prefix eq "") {
 414                         $in_header_comment = 1;
 415                 }
 416                 $prev = $line;
 417                 next line;
 418         }
 419         # are we still in the block comment?
 420         if ($in_comment) {
 421                 if (/^$comment_prefix \*\/$/) {
 422                         $comment_done = 1;
 423                 } elsif (/\*\//) {
 424                         $comment_done = 1;
 425                         err("improper block comment close")
 426                             unless ($ignore_hdr_comment && $in_header_comment);
 427                 } elsif (!/^$comment_prefix \*[ \t]/ &&
 428                     !/^$comment_prefix \*$/) {
 429                         err("improper block comment")
 430                             unless ($ignore_hdr_comment && $in_header_comment);
 431                 }
 432         }
 433 
 434         if ($in_header_comment && $ignore_hdr_comment) {
 435                 $prev = $line;
 436                 next line;
 437         }
 438 
 439         # check for errors that might occur in comments and in code.
 440 
 441         # allow spaces to be used to draw pictures in header comments.
 442         if (/[^ ]     / && !/".*     .*"/ && !$in_header_comment) {
 443                 err("spaces instead of tabs");
 444         }
 445         if (/^ / && !/^ \*[ \t\/]/ && !/^ \*$/ &&
 446             (!/^    \w/ || $in_function != 0)) {
 447                 err("indent by spaces instead of tabs");
 448         }
 449         if (/^\t+ [^ \t\*]/ || /^\t+  \S/ || /^\t+   \S/) {
 450                 err("continuation line not indented by 4 spaces");
 451         }
 452         if (/$warlock_re/ && !/\*\//) {
 453                 $in_warlock_comment = 1;
 454                 $prev = $line;
 455                 next line;
 456         }
 457         if (/^\s*\/\*./ && !/^\s*\/\*.*\*\// && !/$hdr_comment_start/) {
 458                 err("improper first line of block comment");
 459         }
 460 
 461         if ($in_comment) {      # still in comment, don't do further checks
 462                 $prev = $line;
 463                 next line;
 464         }
 465 
 466         if ((/[^(]\/\*\S/ || /^\/\*\S/) &&
 467             !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
 468                 err("missing blank after open comment");
 469         }
 470         if (/\S\*\/[^)]|\S\*\/$/ &&
 471             !(/$lint_re/ || ($splint_comments && /$splint_re/))) {
 472                 err("missing blank before close comment");
 473         }
 474         if (/\/\/\S/) {         # C++ comments
 475                 err("missing blank after start comment");
 476         }
 477         # check for unterminated single line comments, but allow them when
 478         # they are used to comment out the argument list of a function
 479         # declaration.
 480         if (/\S.*\/\*/ && !/\S.*\/\*.*\*\// && !/\(\/\*/) {
 481                 err("unterminated single line comment");
 482         }
 483 
 484         if (/^(#else|#endif|#include)(.*)$/) {
 485                 $prev = $line;
 486                 if ($picky) {
 487                         my $directive = $1;
 488                         my $clause = $2;
 489                         # Enforce ANSI rules for #else and #endif: no noncomment
 490                         # identifiers are allowed after #endif or #else.  Allow
 491                         # C++ comments since they seem to be a fact of life.
 492                         if ((($1 eq "#endif") || ($1 eq "#else")) &&
 493                             ($clause ne "") &&
 494                             (!($clause =~ /^\s+\/\*.*\*\/$/)) &&
 495                             (!($clause =~ /^\s+\/\/.*$/))) {
 496                                 err("non-comment text following " .
 497                                     "$directive (or malformed $directive " .
 498                                     "directive)");
 499                         }
 500                 }
 501                 next line;
 502         }
 503 
 504         #
 505         # delete any comments and check everything else.  Note that
 506         # ".*?" is a non-greedy match, so that we don't get confused by
 507         # multiple comments on the same line.
 508         #
 509         s/\/\*.*?\*\///g;
 510         s/\/\/.*$//;           # C++ comments
 511 
 512         # delete any trailing whitespace; we have already checked for that.
 513         s/\s*$//;
 514 
 515         # following checks do not apply to text in comments.
 516 
 517         if (/[^<>\s][!<>=]=/ || /[^<>][!<>=]=[^\s,]/ ||
 518             (/[^->]>[^,=>\s]/ && !/[^->]>$/) ||
 519             (/[^<]<[^,=<\s]/ && !/[^<]<$/) ||
 520             /[^<\s]<[^<]/ || /[^->\s]>[^>]/) {
 521                 err("missing space around relational operator");
 522         }
 523         if (/\S>>=/ || /\S<<=/ || />>=\S/ || /<<=\S/ || /\S[-+*\/&|^%]=/ ||
 524             (/[^-+*\/&|^%!<>=\s]=[^=]/ && !/[^-+*\/&|^%!<>=\s]=$/) ||
 525             (/[^!<>=]=[^=\s]/ && !/[^!<>=]=$/)) {
 526                 # XXX - should only check this for C++ code
 527                 # XXX - there are probably other forms that should be allowed
 528                 if (!/\soperator=/) {
 529                         err("missing space around assignment operator");
 530                 }
 531         }
 532         if (/[,;]\S/ && !/\bfor \(;;\)/) {
 533                 err("comma or semicolon followed by non-blank");
 534         }
 535         # allow "for" statements to have empty "while" clauses
 536         if (/\s[,;]/ && !/^[\t]+;$/ && !/^\s*for \([^;]*; ;[^;]*\)/) {
 537                 err("comma or semicolon preceded by blank");
 538         }
 539         if (/^\s*(&&|\|\|)/) {
 540                 err("improper boolean continuation");
 541         }
 542         if (/\S   *(&&|\|\|)/ || /(&&|\|\|)   *\S/) {
 543                 err("more than one space around boolean operator");
 544         }
 545         if (/\b(for|if|while|switch|sizeof|return|case)\(/) {
 546                 err("missing space between keyword and paren");
 547         }
 548         if (/(\b(for|if|while|switch|return)\b.*){2,}/ && !/^#define/) {
 549                 # multiple "case" and "sizeof" allowed
 550                 err("more than one keyword on line");
 551         }
 552         if (/\b(for|if|while|switch|sizeof|return|case)\s\s+\(/ &&
 553             !/^#if\s+\(/) {
 554                 err("extra space between keyword and paren");
 555         }
 556         # try to detect "func (x)" but not "if (x)" or
 557         # "#define foo (x)" or "int (*func)();"
 558         if (/\w\s\(/) {
 559                 my $s = $_;
 560                 # strip off all keywords on the line
 561                 s/\b(for|if|while|switch|return|case|sizeof)\s\(/XXX(/g;
 562                 s/#elif\s\(/XXX(/g;
 563                 s/^#define\s+\w+\s+\(/XXX(/;
 564                 # do not match things like "void (*f)();"
 565                 # or "typedef void (func_t)();"
 566                 s/\w\s\(+\*/XXX(*/g;
 567                 s/\b($typename|void)\s+\(+/XXX(/og;
 568                 if (/\w\s\(/) {
 569                         err("extra space between function name and left paren");
 570                 }
 571                 $_ = $s;
 572         }
 573         # try to detect "int foo(x)", but not "extern int foo(x);"
 574         # XXX - this still trips over too many legitimate things,
 575         # like "int foo(x,\n\ty);"
 576 #               if (/^(\w+(\s|\*)+)+\w+\(/ && !/\)[;,](\s|)*$/ &&
 577 #                   !/^(extern|static)\b/) {
 578 #                       err("return type of function not on separate line");
 579 #               }
 580         # this is a close approximation
 581         if (/^(\w+(\s|\*)+)+\w+\(.*\)(\s|)*$/ &&
 582             !/^(extern|static)\b/) {
 583                 err("return type of function not on separate line");
 584         }
 585         if (/^#define /) {
 586                 err("#define followed by space instead of tab");
 587         }
 588         if (/^\s*return\W[^;]*;/ && !/^\s*return\s*\(.*\);/) {
 589                 err("unparenthesized return expression");
 590         }
 591         if (/\bsizeof\b/ && !/\bsizeof\s*\(.*\)/) {
 592                 err("unparenthesized sizeof expression");
 593         }
 594         if (/\(\s/) {
 595                 err("whitespace after left paren");
 596         }
 597         # allow "for" statements to have empty "continue" clauses
 598         if (/\s\)/ && !/^\s*for \([^;]*;[^;]*; \)/) {
 599                 err("whitespace before right paren");
 600         }
 601         if (/^\s*\(void\)[^ ]/) {
 602                 err("missing space after (void) cast");
 603         }
 604         if (/\S{/ && !/{{/) {
 605                 err("missing space before left brace");
 606         }
 607         if ($in_function && /^\s+{/ &&
 608             ($prev =~ /\)\s*$/ || $prev =~ /\bstruct\s+\w+$/)) {
 609                 err("left brace starting a line");
 610         }
 611         if (/}(else|while)/) {
 612                 err("missing space after right brace");
 613         }
 614         if (/}\s\s+(else|while)/) {
 615                 err("extra space after right brace");
 616         }
 617         if (/\b_VOID\b|\bVOID\b|\bSTATIC\b/) {
 618                 err("obsolete use of VOID or STATIC");
 619         }
 620         if (/\b$typename\*/o) {
 621                 err("missing space between type name and *");
 622         }
 623         if (/^\s+#/) {
 624                 err("preprocessor statement not in column 1");
 625         }
 626         if (/^#\s/) {
 627                 err("blank after preprocessor #");
 628         }
 629         if (/!\s*(strcmp|strncmp|bcmp)\s*\(/) {
 630                 err("don't use boolean ! with comparison functions");
 631         }
 632         if (/\batomic_add_(8|16|32|64|char|short|int|long)\([^,]*,\s*1\)/) {
 633                 err("use atomic_inc_*(...) instead of atomic_add_*(..., 1)");
 634         }
 635         if (/\batomic_add_(8|16|32|64|char|short|int|long)\([^,]*,\s*-1\)/) {
 636                 err("use atomic_dec_*(...) instead of atomic_add_*(..., -1)");
 637         }
 638 
 639         #
 640         # We completely ignore, for purposes of indentation:
 641         #  * lines outside of functions
 642         #  * preprocessor lines
 643         #
 644         if ($check_continuation && $in_function && !$in_cpp) {
 645                 process_indent($_);
 646         }
 647         if ($picky) {
 648                 # try to detect spaces after casts, but allow (e.g.)
 649                 # "sizeof (int) + 1", "void (*funcptr)(int) = foo;", and
 650                 # "int foo(int) __NORETURN;"
 651                 if ((/^\($typename( \*+)?\)\s/o ||
 652                     /\W\($typename( \*+)?\)\s/o) &&
 653                     !/sizeof\s*\($typename( \*)?\)\s/o &&
 654                     !/\($typename( \*+)?\)\s+=[^=]/o) {
 655                         err("space after cast");
 656                 }
 657                 if (/\b$typename\s*\*\s/o &&
 658                     !/\b$typename\s*\*\s+const\b/o) {
 659                         err("unary * followed by space");
 660                 }
 661         }
 662         if ($check_posix_types) {
 663                 # try to detect old non-POSIX types.
 664                 # POSIX requires all non-standard typedefs to end in _t,
 665                 # but historically these have been used.
 666                 if (/\b(unchar|ushort|uint|ulong|u_int|u_short|u_long|u_char|quad)\b/) {
 667                         err("non-POSIX typedef $1 used: use $old2posix{$1} instead");
 668                 }
 669         }
 670         if ($heuristic) {
 671                 # cannot check this everywhere due to "struct {\n...\n} foo;"
 672                 if ($in_function && !$in_declaration &&
 673                     /}./ && !/}\s+=/ && !/{.*}[;,]$/ && !/}(\s|)*$/ &&
 674                     !/} (else|while)/ && !/}}/) {
 675                         err("possible bad text following right brace");
 676                 }
 677                 # cannot check this because sub-blocks in
 678                 # the middle of code are ok
 679                 if ($in_function && /^\s+{/) {
 680                         err("possible left brace starting a line");
 681                 }
 682         }
 683         if (/^\s*else\W/) {
 684                 if ($prev =~ /^\s*}$/) {
 685                         err_prefix($prev,
 686                             "else and right brace should be on same line");
 687                 }
 688         }
 689         $prev = $line;
 690 }
 691 
 692 if ($prev eq "") {
 693         err("last line in file is blank");
 694 }
 695 
 696 }
 697 
 698 #
 699 # Continuation-line checking
 700 #
 701 # The rest of this file contains the code for the continuation checking
 702 # engine.  It's a pretty simple state machine which tracks the expression
 703 # depth (unmatched '('s and '['s).
 704 #
 705 # Keep in mind that the argument to process_indent() has already been heavily
 706 # processed; all comments have been replaced by control-A, and the contents of
 707 # strings and character constants have been elided.
 708 #
 709 
 710 my $cont_in;            # currently inside of a continuation
 711 my $cont_off;           # skipping an initializer or definition
 712 my $cont_noerr;         # suppress cascading errors
 713 my $cont_start;         # the line being continued
 714 my $cont_base;          # the base indentation
 715 my $cont_first;         # this is the first line of a statement
 716 my $cont_multiseg;      # this continuation has multiple segments
 717 
 718 my $cont_special;       # this is a C statement (if, for, etc.)
 719 my $cont_macro;         # this is a macro
 720 my $cont_case;          # this is a multi-line case
 721 
 722 my @cont_paren;         # the stack of unmatched ( and [s we've seen
 723 
 724 sub
 725 reset_indent()
 726 {
 727         $cont_in = 0;
 728         $cont_off = 0;
 729 }
 730 
 731 sub
 732 delabel($)
 733 {
 734         #
 735         # replace labels with tabs.  Note that there may be multiple
 736         # labels on a line.
 737         #
 738         local $_ = $_[0];
 739 
 740         while (/^(\t*)( *(?:(?:\w+\s*)|(?:case\b[^:]*)): *)(.*)$/) {
 741                 my ($pre_tabs, $label, $rest) = ($1, $2, $3);
 742                 $_ = $pre_tabs;
 743                 while ($label =~ s/^([^\t]*)(\t+)//) {
 744                         $_ .= "\t" x (length($2) + length($1) / 8);
 745                 }
 746                 $_ .= ("\t" x (length($label) / 8)).$rest;
 747         }
 748 
 749         return ($_);
 750 }
 751 
 752 sub
 753 process_indent($)
 754 {
 755         require strict;
 756         local $_ = $_[0];                       # preserve the global $_
 757 
 758         s///g; # No comments
 759         s/\s+$//;       # Strip trailing whitespace
 760 
 761         return                  if (/^$/);      # skip empty lines
 762 
 763         # regexps used below; keywords taking (), macros, and continued cases
 764         my $special = '(?:(?:\}\s*)?else\s+)?(?:if|for|while|switch)\b';
 765         my $macro = '[A-Z_][A-Z_0-9]*\(';
 766         my $case = 'case\b[^:]*$';
 767 
 768         # skip over enumerations, array definitions, initializers, etc.
 769         if ($cont_off <= 0 && !/^\s*$special/ &&
 770             (/(?:(?:\b(?:enum|struct|union)\s*[^\{]*)|(?:\s+=\s*)){/ ||
 771             (/^\s*{/ && $prev =~ /=\s*(?:\/\*.*\*\/\s*)*$/))) {
 772                 $cont_in = 0;
 773                 $cont_off = tr/{/{/ - tr/}/}/;
 774                 return;
 775         }
 776         if ($cont_off) {
 777                 $cont_off += tr/{/{/ - tr/}/}/;
 778                 return;
 779         }
 780 
 781         if (!$cont_in) {
 782                 $cont_start = $line;
 783 
 784                 if (/^\t* /) {
 785                         err("non-continuation indented 4 spaces");
 786                         $cont_noerr = 1;                # stop reporting
 787                 }
 788                 $_ = delabel($_);       # replace labels with tabs
 789 
 790                 # check if the statement is complete
 791                 return          if (/^\s*\}?$/);
 792                 return          if (/^\s*\}?\s*else\s*\{?$/);
 793                 return          if (/^\s*do\s*\{?$/);
 794                 return          if (/{$/);
 795                 return          if (/}[,;]?$/);
 796 
 797                 # Allow macros on their own lines
 798                 return          if (/^\s*[A-Z_][A-Z_0-9]*$/);
 799 
 800                 # cases we don't deal with, generally non-kosher
 801                 if (/{/) {
 802                         err("stuff after {");
 803                         return;
 804                 }
 805 
 806                 # Get the base line, and set up the state machine
 807                 /^(\t*)/;
 808                 $cont_base = $1;
 809                 $cont_in = 1;
 810                 @cont_paren = ();
 811                 $cont_first = 1;
 812                 $cont_multiseg = 0;
 813 
 814                 # certain things need special processing
 815                 $cont_special = /^\s*$special/? 1 : 0;
 816                 $cont_macro = /^\s*$macro/? 1 : 0;
 817                 $cont_case = /^\s*$case/? 1 : 0;
 818         } else {
 819                 $cont_first = 0;
 820 
 821                 # Strings may be pulled back to an earlier (half-)tabstop
 822                 unless ($cont_noerr || /^$cont_base    / ||
 823                     (/^\t*(?:    )?(?:gettext\()?\"/ && !/^$cont_base\t/)) {
 824                         err_prefix($cont_start,
 825                             "continuation should be indented 4 spaces");
 826                 }
 827         }
 828 
 829         my $rest = $_;                  # keeps the remainder of the line
 830 
 831         #
 832         # The split matches 0 characters, so that each 'special' character
 833         # is processed separately.  Parens and brackets are pushed and
 834         # popped off the @cont_paren stack.  For normal processing, we wait
 835         # until a ; or { terminates the statement.  "special" processing
 836         # (if/for/while/switch) is allowed to stop when the stack empties,
 837         # as is macro processing.  Case statements are terminated with a :
 838         # and an empty paren stack.
 839         #
 840         foreach $_ (split /[^\(\)\[\]\{\}\;\:]*/) {
 841                 next            if (length($_) == 0);
 842 
 843                 # rest contains the remainder of the line
 844                 my $rxp = "[^\Q$_\E]*\Q$_\E";
 845                 $rest =~ s/^$rxp//;
 846 
 847                 if (/\(/ || /\[/) {
 848                         push @cont_paren, $_;
 849                 } elsif (/\)/ || /\]/) {
 850                         my $cur = $_;
 851                         tr/\)\]/\(\[/;
 852 
 853                         my $old = (pop @cont_paren);
 854                         if (!defined($old)) {
 855                                 err("unexpected '$cur'");
 856                                 $cont_in = 0;
 857                                 last;
 858                         } elsif ($old ne $_) {
 859                                 err("'$cur' mismatched with '$old'");
 860                                 $cont_in = 0;
 861                                 last;
 862                         }
 863 
 864                         #
 865                         # If the stack is now empty, do special processing
 866                         # for if/for/while/switch and macro statements.
 867                         #
 868                         next            if (@cont_paren != 0);
 869                         if ($cont_special) {
 870                                 if ($rest =~ /^\s*{?$/) {
 871                                         $cont_in = 0;
 872                                         last;
 873                                 }
 874                                 if ($rest =~ /^\s*;$/) {
 875                                         err("empty if/for/while body ".
 876                                             "not on its own line");
 877                                         $cont_in = 0;
 878                                         last;
 879                                 }
 880                                 if (!$cont_first && $cont_multiseg == 1) {
 881                                         err_prefix($cont_start,
 882                                             "multiple statements continued ".
 883                                             "over multiple lines");
 884                                         $cont_multiseg = 2;
 885                                 } elsif ($cont_multiseg == 0) {
 886                                         $cont_multiseg = 1;
 887                                 }
 888                                 # We've finished this section, start
 889                                 # processing the next.
 890                                 goto section_ended;
 891                         }
 892                         if ($cont_macro) {
 893                                 if ($rest =~ /^$/) {
 894                                         $cont_in = 0;
 895                                         last;
 896                                 }
 897                         }
 898                 } elsif (/\;/) {
 899                         if ($cont_case) {
 900                                 err("unexpected ;");
 901                         } elsif (!$cont_special) {
 902                                 err("unexpected ;")     if (@cont_paren != 0);
 903                                 if (!$cont_first && $cont_multiseg == 1) {
 904                                         err_prefix($cont_start,
 905                                             "multiple statements continued ".
 906                                             "over multiple lines");
 907                                         $cont_multiseg = 2;
 908                                 } elsif ($cont_multiseg == 0) {
 909                                         $cont_multiseg = 1;
 910                                 }
 911                                 if ($rest =~ /^$/) {
 912                                         $cont_in = 0;
 913                                         last;
 914                                 }
 915                                 if ($rest =~ /^\s*special/) {
 916                                         err("if/for/while/switch not started ".
 917                                             "on its own line");
 918                                 }
 919                                 goto section_ended;
 920                         }
 921                 } elsif (/\{/) {
 922                         err("{ while in parens/brackets") if (@cont_paren != 0);
 923                         err("stuff after {")            if ($rest =~ /[^\s}]/);
 924                         $cont_in = 0;
 925                         last;
 926                 } elsif (/\}/) {
 927                         err("} while in parens/brackets") if (@cont_paren != 0);
 928                         if (!$cont_special && $rest !~ /^\s*(while|else)\b/) {
 929                                 if ($rest =~ /^$/) {
 930                                         err("unexpected }");
 931                                 } else {
 932                                         err("stuff after }");
 933                                 }
 934                                 $cont_in = 0;
 935                                 last;
 936                         }
 937                 } elsif (/\:/ && $cont_case && @cont_paren == 0) {
 938                         err("stuff after multi-line case") if ($rest !~ /$^/);
 939                         $cont_in = 0;
 940                         last;
 941                 }
 942                 next;
 943 section_ended:
 944                 # End of a statement or if/while/for loop.  Reset
 945                 # cont_special and cont_macro based on the rest of the
 946                 # line.
 947                 $cont_special = ($rest =~ /^\s*$special/)? 1 : 0;
 948                 $cont_macro = ($rest =~ /^\s*$macro/)? 1 : 0;
 949                 $cont_case = 0;
 950                 next;
 951         }
 952         $cont_noerr = 0                 if (!$cont_in);
 953 }