• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env perl
2#***************************************************************************
3#                                  _   _ ____  _
4#  Project                     ___| | | |  _ \| |
5#                             / __| | | | |_) | |
6#                            | (__| |_| |  _ <| |___
7#                             \___|\___/|_| \_\_____|
8#
9# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
10#
11# This software is licensed as described in the file COPYING, which
12# you should have received as part of this distribution. The terms
13# are also available at https://curl.se/docs/copyright.html.
14#
15# You may opt to use, copy, modify, merge, publish, distribute and/or sell
16# copies of the Software, and permit persons to whom the Software is
17# furnished to do so, under the terms of the COPYING file.
18#
19# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20# KIND, either express or implied.
21#
22# SPDX-License-Identifier: curl
23#
24###########################################################################
25
26use strict;
27use warnings;
28
29my $max_column = 79;
30my $indent = 2;
31
32my $warnings = 0;
33my $swarnings = 0;
34my $errors = 0;
35my $serrors = 0;
36my $suppressed; # skipped problems
37my $file;
38my $dir=".";
39my $wlist="";
40my @alist;
41my $windows_os = $^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys';
42my $verbose;
43my %skiplist;
44
45my %ignore;
46my %ignore_set;
47my %ignore_used;
48my @ignore_line;
49
50my %warnings_extended = (
51    'COPYRIGHTYEAR'    => 'copyright year incorrect',
52    'STRERROR',        => 'strerror() detected',
53    );
54
55my %warnings = (
56    'ASSIGNWITHINCONDITION' => 'assignment within conditional expression',
57    'ASTERISKNOSPACE'  => 'pointer declared without space before asterisk',
58    'ASTERISKSPACE'    => 'pointer declared with space after asterisk',
59    'BADCOMMAND'       => 'bad !checksrc! instruction',
60    'BANNEDFUNC'       => 'a banned function was used',
61    'BRACEELSE'        => '} else on the same line',
62    'BRACEPOS'         => 'wrong position for an open brace',
63    'BRACEWHILE'       => 'A single space between open brace and while',
64    'COMMANOSPACE'     => 'comma without following space',
65    'COMMENTNOSPACEEND' => 'no space before */',
66    'COMMENTNOSPACESTART' => 'no space following /*',
67    'COPYRIGHT'        => 'file missing a copyright statement',
68    'CPPCOMMENTS'      => '// comment detected',
69    'DOBRACE'          => 'A single space between do and open brace',
70    'EMPTYLINEBRACE'   => 'Empty line before the open brace',
71    'EQUALSNOSPACE'    => 'equals sign without following space',
72    'EQUALSNULL'       => 'if/while comparison with == NULL',
73    'EXCLAMATIONSPACE' => 'Whitespace after exclamation mark in expression',
74    'FOPENMODE'        => 'fopen needs a macro for the mode string',
75    'INCLUDEDUP',      => 'same file is included again',
76    'INDENTATION'      => 'wrong start column for code',
77    'LONGLINE'         => "Line longer than $max_column",
78    'MULTISPACE'       => 'multiple spaces used when not suitable',
79    'NOSPACEEQUALS'    => 'equals sign without preceding space',
80    'NOTEQUALSZERO',   => 'if/while comparison with != 0',
81    'ONELINECONDITION' => 'conditional block on the same line as the if()',
82    'OPENCOMMENT'      => 'file ended with a /* comment still "open"',
83    'PARENBRACE'       => '){ without sufficient space',
84    'RETURNNOSPACE'    => 'return without space',
85    'SEMINOSPACE'      => 'semicolon without following space',
86    'SIZEOFNOPAREN'    => 'use of sizeof without parentheses',
87    'SNPRINTF'         => 'use of snprintf',
88    'SPACEAFTERPAREN'  => 'space after open parenthesis',
89    'SPACEBEFORECLOSE' => 'space before a close parenthesis',
90    'SPACEBEFORECOMMA' => 'space before a comma',
91    'SPACEBEFOREPAREN' => 'space before an open parenthesis',
92    'SPACESEMICOLON'   => 'space before semicolon',
93    'TABS'             => 'TAB characters not allowed',
94    'TRAILINGSPACE'    => 'Trailing whitespace on the line',
95    'TYPEDEFSTRUCT'    => 'typedefed struct',
96    'UNUSEDIGNORE'     => 'a warning ignore was not used',
97    );
98
99sub readskiplist {
100    open(W, "<$dir/checksrc.skip") or return;
101    my @all=<W>;
102    for(@all) {
103        $windows_os ? $_ =~ s/\r?\n$// : chomp;
104        $skiplist{$_}=1;
105    }
106    close(W);
107}
108
109# Reads the .checksrc in $dir for any extended warnings to enable locally.
110# Currently there is no support for disabling warnings from the standard set,
111# and since that's already handled via !checksrc! commands there is probably
112# little use to add it.
113sub readlocalfile {
114    my $i = 0;
115
116    open(my $rcfile, "<", "$dir/.checksrc") or return;
117
118    while(<$rcfile>) {
119        $i++;
120
121        # Lines starting with '#' are considered comments
122        if (/^\s*(#.*)/) {
123            next;
124        }
125        elsif (/^\s*enable ([A-Z]+)$/) {
126            if(!defined($warnings_extended{$1})) {
127                print STDERR "invalid warning specified in .checksrc: \"$1\"\n";
128                next;
129            }
130            $warnings{$1} = $warnings_extended{$1};
131        }
132        elsif (/^\s*disable ([A-Z]+)$/) {
133            if(!defined($warnings{$1})) {
134                print STDERR "invalid warning specified in .checksrc: \"$1\"\n";
135                next;
136            }
137            # Accept-list
138            push @alist, $1;
139        }
140        else {
141            die "Invalid format in $dir/.checksrc on line $i\n";
142        }
143    }
144    close($rcfile);
145}
146
147sub checkwarn {
148    my ($name, $num, $col, $file, $line, $msg, $error) = @_;
149
150    my $w=$error?"error":"warning";
151    my $nowarn=0;
152
153    #if(!$warnings{$name}) {
154    #    print STDERR "Dev! there's no description for $name!\n";
155    #}
156
157    # checksrc.skip
158    if($skiplist{$line}) {
159        $nowarn = 1;
160    }
161    # !checksrc! controlled
162    elsif($ignore{$name}) {
163        $ignore{$name}--;
164        $ignore_used{$name}++;
165        $nowarn = 1;
166        if(!$ignore{$name}) {
167            # reached zero, enable again
168            enable_warn($name, $num, $file, $line);
169        }
170    }
171
172    if($nowarn) {
173        $suppressed++;
174        if($w) {
175            $swarnings++;
176        }
177        else {
178            $serrors++;
179        }
180        return;
181    }
182
183    if($w) {
184        $warnings++;
185    }
186    else {
187        $errors++;
188    }
189
190    $col++;
191    print "$file:$num:$col: $w: $msg ($name)\n";
192    print " $line\n";
193
194    if($col < 80) {
195        my $pref = (' ' x $col);
196        print "${pref}^\n";
197    }
198}
199
200$file = shift @ARGV;
201
202while(defined $file) {
203
204    if($file =~ /-D(.*)/) {
205        $dir = $1;
206        $file = shift @ARGV;
207        next;
208    }
209    elsif($file =~ /-W(.*)/) {
210        $wlist .= " $1 ";
211        $file = shift @ARGV;
212        next;
213    }
214    elsif($file =~ /-A(.+)/) {
215        push @alist, $1;
216        $file = shift @ARGV;
217        next;
218    }
219    elsif($file =~ /-i([1-9])/) {
220        $indent = $1 + 0;
221        $file = shift @ARGV;
222        next;
223    }
224    elsif($file =~ /-m([0-9]+)/) {
225        $max_column = $1 + 0;
226        $file = shift @ARGV;
227        next;
228    }
229    elsif($file =~ /^(-h|--help)/) {
230        undef $file;
231        last;
232    }
233
234    last;
235}
236
237if(!$file) {
238    print "checksrc.pl [option] <file1> [file2] ...\n";
239    print " Options:\n";
240    print "  -A[rule]  Accept this violation, can be used multiple times\n";
241    print "  -D[DIR]   Directory to prepend file names\n";
242    print "  -h        Show help output\n";
243    print "  -W[file]  Skip the given file - ignore all its flaws\n";
244    print "  -i<n>     Indent spaces. Default: 2\n";
245    print "  -m<n>     Maximum line length. Default: 79\n";
246    print "\nDetects and warns for these problems:\n";
247    my @allw = keys %warnings;
248    push @allw, keys %warnings_extended;
249    for my $w (sort @allw) {
250        if($warnings{$w}) {
251            printf (" %-18s: %s\n", $w, $warnings{$w});
252        }
253        else {
254            printf (" %-18s: %s[*]\n", $w, $warnings_extended{$w});
255        }
256    }
257    print " [*] = disabled by default\n";
258    exit;
259}
260
261readskiplist();
262readlocalfile();
263
264do {
265    if("$wlist" !~ / $file /) {
266        my $fullname = $file;
267        $fullname = "$dir/$file" if ($fullname !~ '^\.?\.?/');
268        scanfile($fullname);
269    }
270    $file = shift @ARGV;
271
272} while($file);
273
274sub accept_violations {
275    for my $r (@alist) {
276        if(!$warnings{$r}) {
277            print "'$r' is not a warning to accept!\n";
278            exit;
279        }
280        $ignore{$r}=999999;
281        $ignore_used{$r}=0;
282    }
283}
284
285sub checksrc_clear {
286    undef %ignore;
287    undef %ignore_set;
288    undef @ignore_line;
289}
290
291sub checksrc_endoffile {
292    my ($file) = @_;
293    for(keys %ignore_set) {
294        if($ignore_set{$_} && !$ignore_used{$_}) {
295            checkwarn("UNUSEDIGNORE", $ignore_set{$_},
296                      length($_)+11, $file,
297                      $ignore_line[$ignore_set{$_}],
298                      "Unused ignore: $_");
299        }
300    }
301}
302
303sub enable_warn {
304    my ($what, $line, $file, $l) = @_;
305
306    # switch it back on, but warn if not triggered!
307    if(!$ignore_used{$what}) {
308        checkwarn("UNUSEDIGNORE",
309                  $line, length($what) + 11, $file, $l,
310                  "No warning was inhibited!");
311    }
312    $ignore_set{$what}=0;
313    $ignore_used{$what}=0;
314    $ignore{$what}=0;
315}
316sub checksrc {
317    my ($cmd, $line, $file, $l) = @_;
318    if($cmd =~ / *([^ ]*) *(.*)/) {
319        my ($enable, $what) = ($1, $2);
320        $what =~ s: *\*/$::; # cut off end of C comment
321        # print "ENABLE $enable WHAT $what\n";
322        if($enable eq "disable") {
323            my ($warn, $scope)=($1, $2);
324            if($what =~ /([^ ]*) +(.*)/) {
325                ($warn, $scope)=($1, $2);
326            }
327            else {
328                $warn = $what;
329                $scope = 1;
330            }
331            # print "IGNORE $warn for SCOPE $scope\n";
332            if($scope eq "all") {
333                $scope=999999;
334            }
335
336            # Comparing for a literal zero rather than the scalar value zero
337            # covers the case where $scope contains the ending '*' from the
338            # comment. If we use a scalar comparison (==) we induce warnings
339            # on non-scalar contents.
340            if($scope eq "0") {
341                checkwarn("BADCOMMAND",
342                          $line, 0, $file, $l,
343                          "Disable zero not supported, did you mean to enable?");
344            }
345            elsif($ignore_set{$warn}) {
346                checkwarn("BADCOMMAND",
347                          $line, 0, $file, $l,
348                          "$warn already disabled from line $ignore_set{$warn}");
349            }
350            else {
351                $ignore{$warn}=$scope;
352                $ignore_set{$warn}=$line;
353                $ignore_line[$line]=$l;
354            }
355        }
356        elsif($enable eq "enable") {
357            enable_warn($what, $line, $file, $l);
358        }
359        else {
360            checkwarn("BADCOMMAND",
361                      $line, 0, $file, $l,
362                      "Illegal !checksrc! command");
363        }
364    }
365}
366
367sub nostrings {
368    my ($str) = @_;
369    $str =~ s/\".*\"//g;
370    return $str;
371}
372
373sub scanfile {
374    my ($file) = @_;
375
376    my $line = 1;
377    my $prevl="";
378    my $prevpl="";
379    my $l = "";
380    my $prep = 0;
381    my $prevp = 0;
382    open(R, "<$file") || die "failed to open $file";
383
384    my $incomment=0;
385    my @copyright=();
386    my %includes;
387    checksrc_clear(); # for file based ignores
388    accept_violations();
389
390    while(<R>) {
391        $windows_os ? $_ =~ s/\r?\n$// : chomp;
392        my $l = $_;
393        my $ol = $l; # keep the unmodified line for error reporting
394        my $column = 0;
395
396        # check for !checksrc! commands
397        if($l =~ /\!checksrc\! (.*)/) {
398            my $cmd = $1;
399            checksrc($cmd, $line, $file, $l)
400        }
401
402        # check for a copyright statement and save the years
403        if($l =~ /\* +copyright .* (\d\d\d\d|)/i) {
404            my $count = 0;
405            while($l =~ /([\d]{4})/g) {
406                push @copyright, {
407                  year => $1,
408                  line => $line,
409                  col => index($l, $1),
410                  code => $l
411                };
412                $count++;
413            }
414            if(!$count) {
415                # year-less
416                push @copyright, {
417                    year => -1,
418                    line => $line,
419                    col => index($l, $1),
420                    code => $l
421                };
422            }
423        }
424
425        # detect long lines
426        if(length($l) > $max_column) {
427            checkwarn("LONGLINE", $line, length($l), $file, $l,
428                      "Longer than $max_column columns");
429        }
430        # detect TAB characters
431        if($l =~ /^(.*)\t/) {
432            checkwarn("TABS",
433                      $line, length($1), $file, $l, "Contains TAB character", 1);
434        }
435        # detect trailing whitespace
436        if($l =~ /^(.*)[ \t]+\z/) {
437            checkwarn("TRAILINGSPACE",
438                      $line, length($1), $file, $l, "Trailing whitespace");
439        }
440
441        # no space after comment start
442        if($l =~ /^(.*)\/\*\w/) {
443            checkwarn("COMMENTNOSPACESTART",
444                      $line, length($1) + 2, $file, $l,
445                      "Missing space after comment start");
446        }
447        # no space at comment end
448        if($l =~ /^(.*)\w\*\//) {
449            checkwarn("COMMENTNOSPACEEND",
450                      $line, length($1) + 1, $file, $l,
451                      "Missing space end comment end");
452        }
453        # ------------------------------------------------------------
454        # Above this marker, the checks were done on lines *including*
455        # comments
456        # ------------------------------------------------------------
457
458        # strip off C89 comments
459
460      comment:
461        if(!$incomment) {
462            if($l =~ s/\/\*.*\*\// /g) {
463                # full /* comments */ were removed!
464            }
465            if($l =~ s/\/\*.*//) {
466                # start of /* comment was removed
467                $incomment = 1;
468            }
469        }
470        else {
471            if($l =~ s/.*\*\///) {
472                # end of comment */ was removed
473                $incomment = 0;
474                goto comment;
475            }
476            else {
477                # still within a comment
478                $l="";
479            }
480        }
481
482        # ------------------------------------------------------------
483        # Below this marker, the checks were done on lines *without*
484        # comments
485        # ------------------------------------------------------------
486
487        # prev line was a preprocessor **and** ended with a backslash
488        if($prep && ($prevpl =~ /\\ *\z/)) {
489            # this is still a preprocessor line
490            $prep = 1;
491            goto preproc;
492        }
493        $prep = 0;
494
495        # crude attempt to detect // comments without too many false
496        # positives
497        if($l =~ /^(([^"\*]*)[^:"]|)\/\//) {
498            checkwarn("CPPCOMMENTS",
499                      $line, length($1), $file, $l, "\/\/ comment");
500        }
501
502        if($l =~ /^(\#\s*include\s+)([\">].*[>}"])/) {
503            my ($pre, $path) = ($1, $2);
504            if($includes{$path}) {
505                checkwarn("INCLUDEDUP",
506                          $line, length($1), $file, $l, "duplicated include");
507            }
508            $includes{$path} = $l;
509        }
510
511        # detect and strip preprocessor directives
512        if($l =~ /^[ \t]*\#/) {
513            # preprocessor line
514            $prep = 1;
515            goto preproc;
516        }
517
518        my $nostr = nostrings($l);
519        # check spaces after for/if/while/function call
520        if($nostr =~ /^(.*)(for|if|while| ([a-zA-Z0-9_]+)) \((.)/) {
521            if($1 =~ / *\#/) {
522                # this is a #if, treat it differently
523            }
524            elsif(defined $3 && $3 eq "return") {
525                # return must have a space
526            }
527            elsif(defined $3 && $3 eq "case") {
528                # case must have a space
529            }
530            elsif($4 eq "*") {
531                # (* beginning makes the space OK!
532            }
533            elsif($1 =~ / *typedef/) {
534                # typedefs can use space-paren
535            }
536            else {
537                checkwarn("SPACEBEFOREPAREN", $line, length($1)+length($2), $file, $l,
538                          "$2 with space");
539            }
540        }
541        # check for '== NULL' in if/while conditions but not if the thing on
542        # the left of it is a function call
543        if($nostr =~ /^(.*)(if|while)(\(.*?)([!=]= NULL|NULL [!=]=)/) {
544            checkwarn("EQUALSNULL", $line,
545                      length($1) + length($2) + length($3),
546                      $file, $l, "we prefer !variable instead of \"== NULL\" comparisons");
547        }
548
549        # check for '!= 0' in if/while conditions but not if the thing on
550        # the left of it is a function call
551        if($nostr =~ /^(.*)(if|while)(\(.*[^)]) != 0[^x]/) {
552            checkwarn("NOTEQUALSZERO", $line,
553                      length($1) + length($2) + length($3),
554                      $file, $l, "we prefer if(rc) instead of \"rc != 0\" comparisons");
555        }
556
557        # check spaces in 'do {'
558        if($nostr =~ /^( *)do( *)\{/ && length($2) != 1) {
559            checkwarn("DOBRACE", $line, length($1) + 2, $file, $l, "one space after do before brace");
560        }
561        # check spaces in 'do {'
562        elsif($nostr =~ /^( *)\}( *)while/ && length($2) != 1) {
563            checkwarn("BRACEWHILE", $line, length($1) + 2, $file, $l, "one space between brace and while");
564        }
565        if($nostr =~ /^((.*\s)(if) *\()(.*)\)(.*)/) {
566            my $pos = length($1);
567            my $postparen = $5;
568            my $cond = $4;
569            if($cond =~ / = /) {
570                checkwarn("ASSIGNWITHINCONDITION",
571                          $line, $pos+1, $file, $l,
572                          "assignment within conditional expression");
573            }
574            my $temp = $cond;
575            $temp =~ s/\(//g; # remove open parens
576            my $openc = length($cond) - length($temp);
577
578            $temp = $cond;
579            $temp =~ s/\)//g; # remove close parens
580            my $closec = length($cond) - length($temp);
581            my $even = $openc == $closec;
582
583            if($l =~ / *\#/) {
584                # this is a #if, treat it differently
585            }
586            elsif($even && $postparen &&
587               ($postparen !~ /^ *$/) && ($postparen !~ /^ *[,{&|\\]+/)) {
588                checkwarn("ONELINECONDITION",
589                          $line, length($l)-length($postparen), $file, $l,
590                          "conditional block on the same line");
591            }
592        }
593        # check spaces after open parentheses
594        if($l =~ /^(.*[a-z])\( /i) {
595            checkwarn("SPACEAFTERPAREN",
596                      $line, length($1)+1, $file, $l,
597                      "space after open parenthesis");
598        }
599
600        # check spaces before close parentheses, unless it was a space or a
601        # close parenthesis!
602        if($l =~ /(.*[^\) ]) \)/) {
603            checkwarn("SPACEBEFORECLOSE",
604                      $line, length($1)+1, $file, $l,
605                      "space before close parenthesis");
606        }
607
608        # check spaces before comma!
609        if($l =~ /(.*[^ ]) ,/) {
610            checkwarn("SPACEBEFORECOMMA",
611                      $line, length($1)+1, $file, $l,
612                      "space before comma");
613        }
614
615        # check for "return(" without space
616        if($l =~ /^(.*)return\(/) {
617            if($1 =~ / *\#/) {
618                # this is a #if, treat it differently
619            }
620            else {
621                checkwarn("RETURNNOSPACE", $line, length($1)+6, $file, $l,
622                          "return without space before paren");
623            }
624        }
625
626        # check for "sizeof" without parenthesis
627        if(($l =~ /^(.*)sizeof *([ (])/) && ($2 ne "(")) {
628            if($1 =~ / *\#/) {
629                # this is a #if, treat it differently
630            }
631            else {
632                checkwarn("SIZEOFNOPAREN", $line, length($1)+6, $file, $l,
633                          "sizeof without parenthesis");
634            }
635        }
636
637        # check for comma without space
638        if($l =~ /^(.*),[^ \n]/) {
639            my $pref=$1;
640            my $ign=0;
641            if($pref =~ / *\#/) {
642                # this is a #if, treat it differently
643                $ign=1;
644            }
645            elsif($pref =~ /\/\*/) {
646                # this is a comment
647                $ign=1;
648            }
649            elsif($pref =~ /[\"\']/) {
650                $ign = 1;
651                # There is a quote here, figure out whether the comma is
652                # within a string or '' or not.
653                if($pref =~ /\"/) {
654                    # within a string
655                }
656                elsif($pref =~ /\'$/) {
657                    # a single letter
658                }
659                else {
660                    $ign = 0;
661                }
662            }
663            if(!$ign) {
664                checkwarn("COMMANOSPACE", $line, length($pref)+1, $file, $l,
665                          "comma without following space");
666            }
667        }
668
669        # check for "} else"
670        if($l =~ /^(.*)\} *else/) {
671            checkwarn("BRACEELSE",
672                      $line, length($1), $file, $l, "else after closing brace on same line");
673        }
674        # check for "){"
675        if($l =~ /^(.*)\)\{/) {
676            checkwarn("PARENBRACE",
677                      $line, length($1)+1, $file, $l, "missing space after close paren");
678        }
679        # check for "^{" with an empty line before it
680        if(($l =~ /^\{/) && ($prevl =~ /^[ \t]*\z/)) {
681            checkwarn("EMPTYLINEBRACE",
682                      $line, 0, $file, $l, "empty line before open brace");
683        }
684
685        # check for space before the semicolon last in a line
686        if($l =~ /^(.*[^ ].*) ;$/) {
687            checkwarn("SPACESEMICOLON",
688                      $line, length($1), $file, $ol, "no space before semicolon");
689        }
690
691        # scan for use of banned functions
692        if($l =~ /^(.*\W)
693                   (gmtime|localtime|
694                    gets|
695                    strtok|
696                    v?sprintf|
697                    (str|_mbs|_tcs|_wcs)n?cat|
698                    LoadLibrary(Ex)?(A|W)?)
699                   \s*\(
700                 /x) {
701            checkwarn("BANNEDFUNC",
702                      $line, length($1), $file, $ol,
703                      "use of $2 is banned");
704        }
705        if($warnings{"STRERROR"}) {
706            # scan for use of banned strerror. This is not a BANNEDFUNC to
707            # allow for individual enable/disable of this warning.
708            if($l =~ /^(.*\W)(strerror)\s*\(/x) {
709                if($1 !~ /^ *\#/) {
710                    # skip preprocessor lines
711                    checkwarn("STRERROR",
712                              $line, length($1), $file, $ol,
713                              "use of $2 is banned");
714                }
715            }
716        }
717        # scan for use of snprintf for curl-internals reasons
718        if($l =~ /^(.*\W)(v?snprintf)\s*\(/x) {
719            checkwarn("SNPRINTF",
720                      $line, length($1), $file, $ol,
721                      "use of $2 is banned");
722        }
723
724        # scan for use of non-binary fopen without the macro
725        if($l =~ /^(.*\W)fopen\s*\([^,]*, *\"([^"]*)/) {
726            my $mode = $2;
727            if($mode !~ /b/) {
728                checkwarn("FOPENMODE",
729                          $line, length($1), $file, $ol,
730                          "use of non-binary fopen without FOPEN_* macro: $mode");
731            }
732        }
733
734        # check for open brace first on line but not first column only alert
735        # if previous line ended with a close paren and it wasn't a cpp line
736        if(($prevl =~ /\)\z/) && ($l =~ /^( +)\{/) && !$prevp) {
737            checkwarn("BRACEPOS",
738                      $line, length($1), $file, $ol, "badly placed open brace");
739        }
740
741        # if the previous line starts with if/while/for AND ends with an open
742        # brace, or an else statement, check that this line is indented $indent
743        # more steps, if not a cpp line
744        if(!$prevp && ($prevl =~ /^( *)((if|while|for)\(.*\{|else)\z/)) {
745            my $first = length($1);
746            # this line has some character besides spaces
747            if($l =~ /^( *)[^ ]/) {
748                my $second = length($1);
749                my $expect = $first+$indent;
750                if($expect != $second) {
751                    my $diff = $second - $first;
752                    checkwarn("INDENTATION", $line, length($1), $file, $ol,
753                              "not indented $indent steps (uses $diff)");
754
755                }
756            }
757        }
758
759        # check for 'char * name'
760        if(($l =~ /(^.*(char|int|long|void|CURL|CURLM|CURLMsg|[cC]url_[A-Za-z_]+|struct [a-zA-Z_]+) *(\*+)) (\w+)/) && ($4 !~ /^(const|volatile)$/)) {
761            checkwarn("ASTERISKSPACE",
762                      $line, length($1), $file, $ol,
763                      "space after declarative asterisk");
764        }
765        # check for 'char*'
766        if(($l =~ /(^.*(char|int|long|void|curl_slist|CURL|CURLM|CURLMsg|curl_httppost|sockaddr_in|FILE)\*)/)) {
767            checkwarn("ASTERISKNOSPACE",
768                      $line, length($1)-1, $file, $ol,
769                      "no space before asterisk");
770        }
771
772        # check for 'void func() {', but avoid false positives by requiring
773        # both an open and closed parentheses before the open brace
774        if($l =~ /^((\w).*)\{\z/) {
775            my $k = $1;
776            $k =~ s/const *//;
777            $k =~ s/static *//;
778            if($k =~ /\(.*\)/) {
779                checkwarn("BRACEPOS",
780                          $line, length($l)-1, $file, $ol,
781                          "wrongly placed open brace");
782            }
783        }
784
785        # check for equals sign without spaces next to it
786        if($nostr =~ /(.*)\=[a-z0-9]/i) {
787            checkwarn("EQUALSNOSPACE",
788                      $line, length($1)+1, $file, $ol,
789                      "no space after equals sign");
790        }
791        # check for equals sign without spaces before it
792        elsif($nostr =~ /(.*)[a-z0-9]\=/i) {
793            checkwarn("NOSPACEEQUALS",
794                      $line, length($1)+1, $file, $ol,
795                      "no space before equals sign");
796        }
797
798        # check for plus signs without spaces next to it
799        if($nostr =~ /(.*)[^+]\+[a-z0-9]/i) {
800            checkwarn("PLUSNOSPACE",
801                      $line, length($1)+1, $file, $ol,
802                      "no space after plus sign");
803        }
804        # check for plus sign without spaces before it
805        elsif($nostr =~ /(.*)[a-z0-9]\+[^+]/i) {
806            checkwarn("NOSPACEPLUS",
807                      $line, length($1)+1, $file, $ol,
808                      "no space before plus sign");
809        }
810
811        # check for semicolons without space next to it
812        if($nostr =~ /(.*)\;[a-z0-9]/i) {
813            checkwarn("SEMINOSPACE",
814                      $line, length($1)+1, $file, $ol,
815                      "no space after semicolon");
816        }
817
818        # typedef struct ... {
819        if($nostr =~ /^(.*)typedef struct.*{/) {
820            checkwarn("TYPEDEFSTRUCT",
821                      $line, length($1)+1, $file, $ol,
822                      "typedef'ed struct");
823        }
824
825        if($nostr =~ /(.*)! +(\w|\()/) {
826            checkwarn("EXCLAMATIONSPACE",
827                      $line, length($1)+1, $file, $ol,
828                      "space after exclamation mark");
829        }
830
831        # check for more than one consecutive space before open brace or
832        # question mark. Skip lines containing strings since they make it hard
833        # due to artificially getting multiple spaces
834        if(($l eq $nostr) &&
835           $nostr =~ /^(.*(\S)) + [{?]/i) {
836            checkwarn("MULTISPACE",
837                      $line, length($1)+1, $file, $ol,
838                      "multiple spaces");
839        }
840      preproc:
841        $line++;
842        $prevp = $prep;
843        $prevl = $ol if(!$prep);
844        $prevpl = $ol if($prep);
845    }
846
847    if(!scalar(@copyright)) {
848        checkwarn("COPYRIGHT", 1, 0, $file, "", "Missing copyright statement", 1);
849    }
850
851    # COPYRIGHTYEAR is a extended warning so we must first see if it has been
852    # enabled in .checksrc
853    if(defined($warnings{"COPYRIGHTYEAR"})) {
854        # The check for updated copyrightyear is overly complicated in order to
855        # not punish current hacking for past sins. The copyright years are
856        # right now a bit behind, so enforcing copyright year checking on all
857        # files would cause hundreds of errors. Instead we only look at files
858        # which are tracked in the Git repo and edited in the workdir, or
859        # committed locally on the branch without being in upstream master.
860        #
861        # The simple and naive test is to simply check for the current year,
862        # but updating the year even without an edit is against project policy
863        # (and it would fail every file on January 1st).
864        #
865        # A rather more interesting, and correct, check would be to not test
866        # only locally committed files but inspect all files wrt the year of
867        # their last commit. Removing the `git rev-list origin/master..HEAD`
868        # condition below will enforce copyright year checks against the year
869        # the file was last committed (and thus edited to some degree).
870        my $commityear = undef;
871        @copyright = sort {$$b{year} cmp $$a{year}} @copyright;
872
873        # if the file is modified, assume commit year this year
874        if(`git status -s -- $file` =~ /^ [MARCU]/) {
875            $commityear = (localtime(time))[5] + 1900;
876        }
877        else {
878            # min-parents=1 to ignore wrong initial commit in truncated repos
879            my $grl = `git rev-list --max-count=1 --min-parents=1 --timestamp HEAD -- $file`;
880            if($grl) {
881                chomp $grl;
882                $commityear = (localtime((split(/ /, $grl))[0]))[5] + 1900;
883            }
884        }
885
886        if(defined($commityear) && scalar(@copyright) &&
887           $copyright[0]{year} != $commityear) {
888            checkwarn("COPYRIGHTYEAR", $copyright[0]{line}, $copyright[0]{col},
889                      $file, $copyright[0]{code},
890                      "Copyright year out of date, should be $commityear, " .
891                      "is $copyright[0]{year}", 1);
892        }
893    }
894
895    if($incomment) {
896        checkwarn("OPENCOMMENT", 1, 0, $file, "", "Missing closing comment", 1);
897    }
898
899    checksrc_endoffile($file);
900
901    close(R);
902
903}
904
905
906if($errors || $warnings || $verbose) {
907    printf "checksrc: %d errors and %d warnings\n", $errors, $warnings;
908    if($suppressed) {
909        printf "checksrc: %d errors and %d warnings suppressed\n",
910        $serrors,
911        $swarnings;
912    }
913    exit 5; # return failure
914}
915