libssh2

Форк
0
/
checksrc.pl 
981 строка · 33.2 Кб
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

26
use strict;
27
use warnings;
28

29
my $max_column = 79;
30
my $indent = 2;
31

32
my $warnings = 0;
33
my $swarnings = 0;
34
my $errors = 0;
35
my $serrors = 0;
36
my $suppressed; # skipped problems
37
my $file;
38
my $dir=".";
39
my $wlist="";
40
my @alist;
41
my $windows_os = $^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys';
42
my $verbose;
43
my %skiplist;
44

45
my %ignore;
46
my %ignore_set;
47
my %ignore_used;
48
my @ignore_line;
49

50
my %warnings_extended = (
51
    'COPYRIGHTYEAR'    => 'copyright year incorrect',
52
    'STRERROR',        => 'strerror() detected',
53
    'STDERR',          => 'stderr detected',
54
    );
55

56
my %warnings = (
57
    'ASSIGNWITHINCONDITION' => 'assignment within conditional expression',
58
    'ASTERISKNOSPACE'  => 'pointer declared without space before asterisk',
59
    'ASTERISKSPACE'    => 'pointer declared with space after asterisk',
60
    'BADCOMMAND'       => 'bad !checksrc! instruction',
61
    'BANNEDFUNC'       => 'a banned function was used',
62
    'BANNEDPREPROC'    => 'a banned symbol was used on a preprocessor line',
63
    'BRACEELSE'        => '} else on the same line',
64
    'BRACEPOS'         => 'wrong position for an open brace',
65
    'BRACEWHILE'       => 'A single space between open brace and while',
66
    'COMMANOSPACE'     => 'comma without following space',
67
    'COMMENTNOSPACEEND' => 'no space before */',
68
    'COMMENTNOSPACESTART' => 'no space following /*',
69
    'COPYRIGHT'        => 'file missing a copyright statement',
70
    'CPPCOMMENTS'      => '// comment detected',
71
    'DOBRACE'          => 'A single space between do and open brace',
72
    'EMPTYLINEBRACE'   => 'Empty line before the open brace',
73
    'EQUALSNOSPACE'    => 'equals sign without following space',
74
    'EQUALSNULL'       => 'if/while comparison with == NULL',
75
    'EXCLAMATIONSPACE' => 'Whitespace after exclamation mark in expression',
76
    'FOPENMODE'        => 'fopen needs a macro for the mode string',
77
    'INCLUDEDUP',      => 'same file is included again',
78
    'INDENTATION'      => 'wrong start column for code',
79
    'LONGLINE'         => "Line longer than $max_column",
80
    'SPACEBEFORELABEL' => 'labels not at the start of the line',
81
    'MULTISPACE'       => 'multiple spaces used when not suitable',
82
    'NOSPACEEQUALS'    => 'equals sign without preceding space',
83
    'NOTEQUALSZERO',   => 'if/while comparison with != 0',
84
    'ONELINECONDITION' => 'conditional block on the same line as the if()',
85
    'OPENCOMMENT'      => 'file ended with a /* comment still "open"',
86
    'PARENBRACE'       => '){ without sufficient space',
87
    'RETURNNOSPACE'    => 'return without space',
88
    'SEMINOSPACE'      => 'semicolon without following space',
89
    'SIZEOFNOPAREN'    => 'use of sizeof without parentheses',
90
    'SNPRINTF'         => 'use of snprintf',
91
    'SPACEAFTERPAREN'  => 'space after open parenthesis',
92
    'SPACEBEFORECLOSE' => 'space before a close parenthesis',
93
    'SPACEBEFORECOMMA' => 'space before a comma',
94
    'SPACEBEFOREPAREN' => 'space before an open parenthesis',
95
    'SPACESEMICOLON'   => 'space before semicolon',
96
    'SPACESWITCHCOLON' => 'space before colon of switch label',
97
    'TABS'             => 'TAB characters not allowed',
98
    'TRAILINGSPACE'    => 'Trailing whitespace on the line',
99
    'TYPEDEFSTRUCT'    => 'typedefed struct',
100
    'UNUSEDIGNORE'     => 'a warning ignore was not used',
101
    );
102

103
sub readskiplist {
104
    open(my $W, '<', "$dir/checksrc.skip") or return;
105
    my @all=<$W>;
106
    for(@all) {
107
        $windows_os ? $_ =~ s/\r?\n$// : chomp;
108
        $skiplist{$_}=1;
109
    }
110
    close($W);
111
}
112

113
# Reads the .checksrc in $dir for any extended warnings to enable locally.
114
# Currently there is no support for disabling warnings from the standard set,
115
# and since that's already handled via !checksrc! commands there is probably
116
# little use to add it.
117
sub readlocalfile {
118
    my $i = 0;
119

120
    open(my $rcfile, "<", "$dir/.checksrc") or return;
121

122
    while(<$rcfile>) {
123
        $i++;
124

125
        # Lines starting with '#' are considered comments
126
        if (/^\s*(#.*)/) {
127
            next;
128
        }
129
        elsif (/^\s*enable ([A-Z]+)$/) {
130
            if(!defined($warnings_extended{$1})) {
131
                print STDERR "invalid warning specified in .checksrc: \"$1\"\n";
132
                next;
133
            }
134
            $warnings{$1} = $warnings_extended{$1};
135
        }
136
        elsif (/^\s*disable ([A-Z]+)$/) {
137
            if(!defined($warnings{$1})) {
138
                print STDERR "invalid warning specified in .checksrc: \"$1\"\n";
139
                next;
140
            }
141
            # Accept-list
142
            push @alist, $1;
143
        }
144
        else {
145
            die "Invalid format in $dir/.checksrc on line $i\n";
146
        }
147
    }
148
    close($rcfile);
149
}
150

151
sub checkwarn {
152
    my ($name, $num, $col, $file, $line, $msg, $error) = @_;
153

154
    my $w=$error?"error":"warning";
155
    my $nowarn=0;
156

157
    #if(!$warnings{$name}) {
158
    #    print STDERR "Dev! there's no description for $name!\n";
159
    #}
160

161
    # checksrc.skip
162
    if($skiplist{$line}) {
163
        $nowarn = 1;
164
    }
165
    # !checksrc! controlled
166
    elsif($ignore{$name}) {
167
        $ignore{$name}--;
168
        $ignore_used{$name}++;
169
        $nowarn = 1;
170
        if(!$ignore{$name}) {
171
            # reached zero, enable again
172
            enable_warn($name, $num, $file, $line);
173
        }
174
    }
175

176
    if($nowarn) {
177
        $suppressed++;
178
        if($w) {
179
            $swarnings++;
180
        }
181
        else {
182
            $serrors++;
183
        }
184
        return;
185
    }
186

187
    if($w) {
188
        $warnings++;
189
    }
190
    else {
191
        $errors++;
192
    }
193

194
    $col++;
195
    print "$file:$num:$col: $w: $msg ($name)\n";
196
    print " $line\n";
197

198
    if($col < 80) {
199
        my $pref = (' ' x $col);
200
        print "${pref}^\n";
201
    }
202
}
203

204
$file = shift @ARGV;
205

206
while(defined $file) {
207

208
    if($file =~ /-D(.*)/) {
209
        $dir = $1;
210
        $file = shift @ARGV;
211
        next;
212
    }
213
    elsif($file =~ /-W(.*)/) {
214
        $wlist .= " $1 ";
215
        $file = shift @ARGV;
216
        next;
217
    }
218
    elsif($file =~ /-A(.+)/) {
219
        push @alist, $1;
220
        $file = shift @ARGV;
221
        next;
222
    }
223
    elsif($file =~ /-i([1-9])/) {
224
        $indent = $1 + 0;
225
        $file = shift @ARGV;
226
        next;
227
    }
228
    elsif($file =~ /-m([0-9]+)/) {
229
        $max_column = $1 + 0;
230
        $file = shift @ARGV;
231
        next;
232
    }
233
    elsif($file =~ /^(-h|--help)/) {
234
        undef $file;
235
        last;
236
    }
237

238
    last;
239
}
240

241
if(!$file) {
242
    print "checksrc.pl [option] <file1> [file2] ...\n";
243
    print " Options:\n";
244
    print "  -A[rule]  Accept this violation, can be used multiple times\n";
245
    print "  -D[DIR]   Directory to prepend file names\n";
246
    print "  -h        Show help output\n";
247
    print "  -W[file]  Skip the given file - ignore all its flaws\n";
248
    print "  -i<n>     Indent spaces. Default: 2\n";
249
    print "  -m<n>     Maximum line length. Default: 79\n";
250
    print "\nDetects and warns for these problems:\n";
251
    my @allw = keys %warnings;
252
    push @allw, keys %warnings_extended;
253
    for my $w (sort @allw) {
254
        if($warnings{$w}) {
255
            printf (" %-18s: %s\n", $w, $warnings{$w});
256
        }
257
        else {
258
            printf (" %-18s: %s[*]\n", $w, $warnings_extended{$w});
259
        }
260
    }
261
    print " [*] = disabled by default\n";
262
    exit;
263
}
264

265
readskiplist();
266
readlocalfile();
267

268
do {
269
    if("$wlist" !~ / $file /) {
270
        my $fullname = $file;
271
        $fullname = "$dir/$file" if ($fullname !~ '^\.?\.?/');
272
        scanfile($fullname);
273
    }
274
    $file = shift @ARGV;
275

276
} while($file);
277

278
sub accept_violations {
279
    for my $r (@alist) {
280
        if(!$warnings{$r}) {
281
            print "'$r' is not a warning to accept!\n";
282
            exit;
283
        }
284
        $ignore{$r}=999999;
285
        $ignore_used{$r}=0;
286
    }
287
}
288

289
sub checksrc_clear {
290
    undef %ignore;
291
    undef %ignore_set;
292
    undef @ignore_line;
293
}
294

295
sub checksrc_endoffile {
296
    my ($file) = @_;
297
    for(keys %ignore_set) {
298
        if($ignore_set{$_} && !$ignore_used{$_}) {
299
            checkwarn("UNUSEDIGNORE", $ignore_set{$_},
300
                      length($_)+11, $file,
301
                      $ignore_line[$ignore_set{$_}],
302
                      "Unused ignore: $_");
303
        }
304
    }
305
}
306

307
sub enable_warn {
308
    my ($what, $line, $file, $l) = @_;
309

310
    # switch it back on, but warn if not triggered!
311
    if(!$ignore_used{$what}) {
312
        checkwarn("UNUSEDIGNORE",
313
                  $line, length($what) + 11, $file, $l,
314
                  "No warning was inhibited!");
315
    }
316
    $ignore_set{$what}=0;
317
    $ignore_used{$what}=0;
318
    $ignore{$what}=0;
319
}
320
sub checksrc {
321
    my ($cmd, $line, $file, $l) = @_;
322
    if($cmd =~ / *([^ ]*) *(.*)/) {
323
        my ($enable, $what) = ($1, $2);
324
        $what =~ s: *\*/$::; # cut off end of C comment
325
        # print "ENABLE $enable WHAT $what\n";
326
        if($enable eq "disable") {
327
            my ($warn, $scope)=($1, $2);
328
            if($what =~ /([^ ]*) +(.*)/) {
329
                ($warn, $scope)=($1, $2);
330
            }
331
            else {
332
                $warn = $what;
333
                $scope = 1;
334
            }
335
            # print "IGNORE $warn for SCOPE $scope\n";
336
            if($scope eq "all") {
337
                $scope=999999;
338
            }
339

340
            # Comparing for a literal zero rather than the scalar value zero
341
            # covers the case where $scope contains the ending '*' from the
342
            # comment. If we use a scalar comparison (==) we induce warnings
343
            # on non-scalar contents.
344
            if($scope eq "0") {
345
                checkwarn("BADCOMMAND",
346
                          $line, 0, $file, $l,
347
                          "Disable zero not supported, did you mean to enable?");
348
            }
349
            elsif($ignore_set{$warn}) {
350
                checkwarn("BADCOMMAND",
351
                          $line, 0, $file, $l,
352
                          "$warn already disabled from line $ignore_set{$warn}");
353
            }
354
            else {
355
                $ignore{$warn}=$scope;
356
                $ignore_set{$warn}=$line;
357
                $ignore_line[$line]=$l;
358
            }
359
        }
360
        elsif($enable eq "enable") {
361
            enable_warn($what, $line, $file, $l);
362
        }
363
        else {
364
            checkwarn("BADCOMMAND",
365
                      $line, 0, $file, $l,
366
                      "Illegal !checksrc! command");
367
        }
368
    }
369
}
370

371
sub nostrings {
372
    my ($str) = @_;
373
    $str =~ s/\".*\"//g;
374
    return $str;
375
}
376

377
sub scanfile {
378
    my ($file) = @_;
379

380
    my $line = 1;
381
    my $prevl="";
382
    my $prevpl="";
383
    my $l = "";
384
    my $prep = 0;
385
    my $prevp = 0;
386
    open(my $R, '<', $file) || die "failed to open $file";
387

388
    my $incomment=0;
389
    my @copyright=();
390
    my %includes;
391
    checksrc_clear(); # for file based ignores
392
    accept_violations();
393

394
    while(<$R>) {
395
        $windows_os ? $_ =~ s/\r?\n$// : chomp;
396
        my $l = $_;
397
        my $ol = $l; # keep the unmodified line for error reporting
398
        my $column = 0;
399

400
        # check for !checksrc! commands
401
        if($l =~ /\!checksrc\! (.*)/) {
402
            my $cmd = $1;
403
            checksrc($cmd, $line, $file, $l)
404
        }
405

406
        # check for a copyright statement and save the years
407
        if($l =~ /\* +copyright .* (\d\d\d\d|)/i) {
408
            my $count = 0;
409
            while($l =~ /([\d]{4})/g) {
410
                push @copyright, {
411
                  year => $1,
412
                  line => $line,
413
                  col => index($l, $1),
414
                  code => $l
415
                };
416
                $count++;
417
            }
418
            if(!$count) {
419
                # year-less
420
                push @copyright, {
421
                    year => -1,
422
                    line => $line,
423
                    col => index($l, $1),
424
                    code => $l
425
                };
426
            }
427
        }
428

429
        # detect long lines
430
        if(length($l) > $max_column) {
431
            checkwarn("LONGLINE", $line, length($l), $file, $l,
432
                      "Longer than $max_column columns");
433
        }
434
        # detect TAB characters
435
        if($l =~ /^(.*)\t/) {
436
            checkwarn("TABS",
437
                      $line, length($1), $file, $l, "Contains TAB character", 1);
438
        }
439
        # detect trailing whitespace
440
        if($l =~ /^(.*)[ \t]+\z/) {
441
            checkwarn("TRAILINGSPACE",
442
                      $line, length($1), $file, $l, "Trailing whitespace");
443
        }
444

445
        # no space after comment start
446
        if($l =~ /^(.*)\/\*\w/) {
447
            checkwarn("COMMENTNOSPACESTART",
448
                      $line, length($1) + 2, $file, $l,
449
                      "Missing space after comment start");
450
        }
451
        # no space at comment end
452
        if($l =~ /^(.*)\w\*\//) {
453
            checkwarn("COMMENTNOSPACEEND",
454
                      $line, length($1) + 1, $file, $l,
455
                      "Missing space end comment end");
456
        }
457
        # ------------------------------------------------------------
458
        # Above this marker, the checks were done on lines *including*
459
        # comments
460
        # ------------------------------------------------------------
461

462
        # strip off C89 comments
463

464
      comment:
465
        if(!$incomment) {
466
            if($l =~ s/\/\*.*\*\// /g) {
467
                # full /* comments */ were removed!
468
            }
469
            if($l =~ s/\/\*.*//) {
470
                # start of /* comment was removed
471
                $incomment = 1;
472
            }
473
        }
474
        else {
475
            if($l =~ s/.*\*\///) {
476
                # end of comment */ was removed
477
                $incomment = 0;
478
                goto comment;
479
            }
480
            else {
481
                # still within a comment
482
                $l="";
483
            }
484
        }
485

486
        # ------------------------------------------------------------
487
        # Below this marker, the checks were done on lines *without*
488
        # comments
489
        # ------------------------------------------------------------
490

491
        # prev line was a preprocessor **and** ended with a backslash
492
        if($prep && ($prevpl =~ /\\ *\z/)) {
493
            # this is still a preprocessor line
494
            $prep = 1;
495
            goto preproc;
496
        }
497
        $prep = 0;
498

499
        # crude attempt to detect // comments without too many false
500
        # positives
501
        if($l =~ /^(([^"\*]*)[^:"]|)\/\//) {
502
            checkwarn("CPPCOMMENTS",
503
                      $line, length($1), $file, $l, "\/\/ comment");
504
        }
505

506
        if($l =~ /^(\#\s*include\s+)([\">].*[>}"])/) {
507
            my ($pre, $path) = ($1, $2);
508
            if($includes{$path}) {
509
                checkwarn("INCLUDEDUP",
510
                          $line, length($1), $file, $l, "duplicated include");
511
            }
512
            $includes{$path} = $l;
513
        }
514

515
        # detect and strip preprocessor directives
516
        if($l =~ /^[ \t]*\#/) {
517
            # preprocessor line
518
            $prep = 1;
519
            goto preproc;
520
        }
521

522
        my $nostr = nostrings($l);
523
        # check spaces after for/if/while/function call
524
        if($nostr =~ /^(.*)(for|if|while|switch| ([a-zA-Z0-9_]+)) \((.)/) {
525
            my ($leading, $word, $extra, $first)=($1,$2,$3,$4);
526
            if($1 =~ / *\#/) {
527
                # this is a #if, treat it differently
528
            }
529
            elsif(defined $3 && $3 eq "return") {
530
                # return must have a space
531
            }
532
            elsif(defined $3 && $3 eq "case") {
533
                # case must have a space
534
            }
535
            elsif(($first eq "*") && ($word !~ /(for|if|while|switch)/)) {
536
                # A "(*" beginning makes the space OK because it wants to
537
                # allow function pointer declared
538
            }
539
            elsif($1 =~ / *typedef/) {
540
                # typedefs can use space-paren
541
            }
542
            else {
543
                checkwarn("SPACEBEFOREPAREN", $line, length($leading)+length($word), $file, $l,
544
                          "$word with space");
545
            }
546
        }
547
        # check for '== NULL' in if/while conditions but not if the thing on
548
        # the left of it is a function call
549
        if($nostr =~ /^(.*)(if|while)(\(.*?)([!=]= NULL|NULL [!=]=)/) {
550
            checkwarn("EQUALSNULL", $line,
551
                      length($1) + length($2) + length($3),
552
                      $file, $l, "we prefer !variable instead of \"== NULL\" comparisons");
553
        }
554

555
        # check for '!= 0' in if/while conditions but not if the thing on
556
        # the left of it is a function call
557
        if($nostr =~ /^(.*)(if|while)(\(.*[^)]) != 0[^x]/) {
558
            checkwarn("NOTEQUALSZERO", $line,
559
                      length($1) + length($2) + length($3),
560
                      $file, $l, "we prefer if(rc) instead of \"rc != 0\" comparisons");
561
        }
562

563
        # check spaces in 'do {'
564
        if($nostr =~ /^( *)do( *)\{/ && length($2) != 1) {
565
            checkwarn("DOBRACE", $line, length($1) + 2, $file, $l, "one space after do before brace");
566
        }
567
        # check spaces in 'do {'
568
        elsif($nostr =~ /^( *)\}( *)while/ && length($2) != 1) {
569
            checkwarn("BRACEWHILE", $line, length($1) + 2, $file, $l, "one space between brace and while");
570
        }
571
        if($nostr =~ /^((.*\s)(if) *\()(.*)\)(.*)/) {
572
            my $pos = length($1);
573
            my $postparen = $5;
574
            my $cond = $4;
575
            if($cond =~ / = /) {
576
                checkwarn("ASSIGNWITHINCONDITION",
577
                          $line, $pos+1, $file, $l,
578
                          "assignment within conditional expression");
579
            }
580
            my $temp = $cond;
581
            $temp =~ s/\(//g; # remove open parens
582
            my $openc = length($cond) - length($temp);
583

584
            $temp = $cond;
585
            $temp =~ s/\)//g; # remove close parens
586
            my $closec = length($cond) - length($temp);
587
            my $even = $openc == $closec;
588

589
            if($l =~ / *\#/) {
590
                # this is a #if, treat it differently
591
            }
592
            elsif($even && $postparen &&
593
               ($postparen !~ /^ *$/) && ($postparen !~ /^ *[,{&|\\]+/)) {
594
                checkwarn("ONELINECONDITION",
595
                          $line, length($l)-length($postparen), $file, $l,
596
                          "conditional block on the same line");
597
            }
598
        }
599
        # check spaces after open parentheses
600
        if($l =~ /^(.*[a-z])\( /i) {
601
            checkwarn("SPACEAFTERPAREN",
602
                      $line, length($1)+1, $file, $l,
603
                      "space after open parenthesis");
604
        }
605

606
        # check spaces before close parentheses, unless it was a space or a
607
        # close parenthesis!
608
        if($l =~ /(.*[^\) ]) \)/) {
609
            checkwarn("SPACEBEFORECLOSE",
610
                      $line, length($1)+1, $file, $l,
611
                      "space before close parenthesis");
612
        }
613

614
        # check spaces before comma!
615
        if($l =~ /(.*[^ ]) ,/) {
616
            checkwarn("SPACEBEFORECOMMA",
617
                      $line, length($1)+1, $file, $l,
618
                      "space before comma");
619
        }
620

621
        # check for "return(" without space
622
        if($l =~ /^(.*)return\(/) {
623
            if($1 =~ / *\#/) {
624
                # this is a #if, treat it differently
625
            }
626
            else {
627
                checkwarn("RETURNNOSPACE", $line, length($1)+6, $file, $l,
628
                          "return without space before paren");
629
            }
630
        }
631

632
        # check for "sizeof" without parenthesis
633
        if(($l =~ /^(.*)sizeof *([ (])/) && ($2 ne "(")) {
634
            if($1 =~ / *\#/) {
635
                # this is a #if, treat it differently
636
            }
637
            else {
638
                checkwarn("SIZEOFNOPAREN", $line, length($1)+6, $file, $l,
639
                          "sizeof without parenthesis");
640
            }
641
        }
642

643
        # check for comma without space
644
        if($l =~ /^(.*),[^ \n]/) {
645
            my $pref=$1;
646
            my $ign=0;
647
            if($pref =~ / *\#/) {
648
                # this is a #if, treat it differently
649
                $ign=1;
650
            }
651
            elsif($pref =~ /\/\*/) {
652
                # this is a comment
653
                $ign=1;
654
            }
655
            elsif($pref =~ /[\"\']/) {
656
                $ign = 1;
657
                # There is a quote here, figure out whether the comma is
658
                # within a string or '' or not.
659
                if($pref =~ /\"/) {
660
                    # within a string
661
                }
662
                elsif($pref =~ /\'$/) {
663
                    # a single letter
664
                }
665
                else {
666
                    $ign = 0;
667
                }
668
            }
669
            if(!$ign) {
670
                checkwarn("COMMANOSPACE", $line, length($pref)+1, $file, $l,
671
                          "comma without following space");
672
            }
673
        }
674

675
        # check for "} else"
676
        if($l =~ /^(.*)\} *else/) {
677
            checkwarn("BRACEELSE",
678
                      $line, length($1), $file, $l, "else after closing brace on same line");
679
        }
680
        # check for "){"
681
        if($l =~ /^(.*)\)\{/) {
682
            checkwarn("PARENBRACE",
683
                      $line, length($1)+1, $file, $l, "missing space after close paren");
684
        }
685
        # check for "^{" with an empty line before it
686
        if(($l =~ /^\{/) && ($prevl =~ /^[ \t]*\z/)) {
687
            checkwarn("EMPTYLINEBRACE",
688
                      $line, 0, $file, $l, "empty line before open brace");
689
        }
690

691
        # check for space before the semicolon last in a line
692
        if($l =~ /^(.*[^ ].*) ;$/) {
693
            checkwarn("SPACESEMICOLON",
694
                      $line, length($1), $file, $ol, "no space before semicolon");
695
        }
696

697
        # check for space before the colon in a switch label
698
        if($l =~ /^( *(case .+|default)) :/) {
699
            checkwarn("SPACESWITCHCOLON",
700
                      $line, length($1), $file, $ol, "no space before colon of switch label");
701
        }
702

703
        if($prevl !~ /\?\z/ && $l =~ /^ +([A-Za-z_][A-Za-z0-9_]*):$/ && $1 ne 'default') {
704
            checkwarn("SPACEBEFORELABEL",
705
                      $line, length($1), $file, $ol, "no space before label");
706
        }
707

708
        # scan for use of banned functions
709
        if($l =~ /^(.*\W)
710
                   (gmtime|localtime|
711
                    gets|
712
                    strtok|
713
                    v?sprintf|
714
                    (str|_mbs|_tcs|_wcs)n?cat|
715
                    LoadLibrary(Ex)?(A|W)?)
716
                   \s*\(
717
                 /x) {
718
            checkwarn("BANNEDFUNC",
719
                      $line, length($1), $file, $ol,
720
                      "use of $2 is banned");
721
        }
722
        if($warnings{"STRERROR"}) {
723
            # scan for use of banned strerror. This is not a BANNEDFUNC to
724
            # allow for individual enable/disable of this warning.
725
            if($l =~ /^(.*\W)(strerror)\s*\(/x) {
726
                if($1 !~ /^ *\#/) {
727
                    # skip preprocessor lines
728
                    checkwarn("STRERROR",
729
                              $line, length($1), $file, $ol,
730
                              "use of $2 is banned");
731
                }
732
            }
733
        }
734
        if($warnings{"STDERR"}) {
735
            # scan for use of banned stderr. This is not a BANNEDFUNC to
736
            # allow for individual enable/disable of this warning.
737
            if($l =~ /^([^\"-]*\W)(stderr)[^\"_]/x) {
738
                if($1 !~ /^ *\#/) {
739
                    # skip preprocessor lines
740
                    checkwarn("STDERR",
741
                              $line, length($1), $file, $ol,
742
                              "use of $2 is banned (use tool_stderr instead)");
743
                }
744
            }
745
        }
746
        # scan for use of snprintf for curl-internals reasons
747
        if($l =~ /^(.*\W)(v?snprintf)\s*\(/x) {
748
            checkwarn("SNPRINTF",
749
                      $line, length($1), $file, $ol,
750
                      "use of $2 is banned");
751
        }
752

753
        # scan for use of non-binary fopen without the macro
754
        if($l =~ /^(.*\W)fopen\s*\([^,]*, *\"([^"]*)/) {
755
            my $mode = $2;
756
            if($mode !~ /b/) {
757
                checkwarn("FOPENMODE",
758
                          $line, length($1), $file, $ol,
759
                          "use of non-binary fopen without FOPEN_* macro: $mode");
760
            }
761
        }
762

763
        # check for open brace first on line but not first column only alert
764
        # if previous line ended with a close paren and it wasn't a cpp line
765
        if(($prevl =~ /\)\z/) && ($l =~ /^( +)\{/) && !$prevp) {
766
            checkwarn("BRACEPOS",
767
                      $line, length($1), $file, $ol, "badly placed open brace");
768
        }
769

770
        # if the previous line starts with if/while/for AND ends with an open
771
        # brace, or an else statement, check that this line is indented $indent
772
        # more steps, if not a cpp line
773
        if(!$prevp && ($prevl =~ /^( *)((if|while|for)\(.*\{|else)\z/)) {
774
            my $first = length($1);
775
            # this line has some character besides spaces
776
            if($l =~ /^( *)[^ ]/) {
777
                my $second = length($1);
778
                my $expect = $first+$indent;
779
                if($expect != $second) {
780
                    my $diff = $second - $first;
781
                    checkwarn("INDENTATION", $line, length($1), $file, $ol,
782
                              "not indented $indent steps (uses $diff)");
783

784
                }
785
            }
786
        }
787

788
        # if the previous line starts with if/while/for AND ends with a closed
789
        # parenthesis and there's an equal number of open and closed
790
        # parentheses, check that this line is indented $indent more steps, if
791
        # not a cpp line
792
        elsif(!$prevp && ($prevl =~ /^( *)(if|while|for)(\(.*\))\z/)) {
793
            my $first = length($1);
794
            my $op = $3;
795
            my $cl = $3;
796

797
            $op =~ s/[^(]//g;
798
            $cl =~ s/[^)]//g;
799

800
            if(length($op) == length($cl)) {
801
                # this line has some character besides spaces
802
                if($l =~ /^( *)[^ ]/) {
803
                    my $second = length($1);
804
                    my $expect = $first+$indent;
805
                    if($expect != $second) {
806
                        my $diff = $second - $first;
807
                        checkwarn("INDENTATION", $line, length($1), $file, $ol,
808
                                  "not indented $indent steps (uses $diff)");
809
                    }
810
                }
811
            }
812
        }
813

814
        # check for 'char * name'
815
        if(($l =~ /(^.*(char|int|long|void|CURL|CURLM|CURLMsg|[cC]url_[A-Za-z_]+|struct [a-zA-Z_]+) *(\*+)) (\w+)/) && ($4 !~ /^(const|volatile)$/)) {
816
            checkwarn("ASTERISKSPACE",
817
                      $line, length($1), $file, $ol,
818
                      "space after declarative asterisk");
819
        }
820
        # check for 'char*'
821
        if(($l =~ /(^.*(char|int|long|void|curl_slist|CURL|CURLM|CURLMsg|curl_httppost|sockaddr_in|FILE)\*)/)) {
822
            checkwarn("ASTERISKNOSPACE",
823
                      $line, length($1)-1, $file, $ol,
824
                      "no space before asterisk");
825
        }
826

827
        # check for 'void func() {', but avoid false positives by requiring
828
        # both an open and closed parentheses before the open brace
829
        if($l =~ /^((\w).*)\{\z/) {
830
            my $k = $1;
831
            $k =~ s/const *//;
832
            $k =~ s/static *//;
833
            if($k =~ /\(.*\)/) {
834
                checkwarn("BRACEPOS",
835
                          $line, length($l)-1, $file, $ol,
836
                          "wrongly placed open brace");
837
            }
838
        }
839

840
        # check for equals sign without spaces next to it
841
        if($nostr =~ /(.*)\=[a-z0-9]/i) {
842
            checkwarn("EQUALSNOSPACE",
843
                      $line, length($1)+1, $file, $ol,
844
                      "no space after equals sign");
845
        }
846
        # check for equals sign without spaces before it
847
        elsif($nostr =~ /(.*)[a-z0-9]\=/i) {
848
            checkwarn("NOSPACEEQUALS",
849
                      $line, length($1)+1, $file, $ol,
850
                      "no space before equals sign");
851
        }
852

853
        # check for plus signs without spaces next to it
854
        if($nostr =~ /(.*)[^+]\+[a-z0-9]/i) {
855
            checkwarn("PLUSNOSPACE",
856
                      $line, length($1)+1, $file, $ol,
857
                      "no space after plus sign");
858
        }
859
        # check for plus sign without spaces before it
860
        elsif($nostr =~ /(.*)[a-z0-9]\+[^+]/i) {
861
            checkwarn("NOSPACEPLUS",
862
                      $line, length($1)+1, $file, $ol,
863
                      "no space before plus sign");
864
        }
865

866
        # check for semicolons without space next to it
867
        if($nostr =~ /(.*)\;[a-z0-9]/i) {
868
            checkwarn("SEMINOSPACE",
869
                      $line, length($1)+1, $file, $ol,
870
                      "no space after semicolon");
871
        }
872

873
        # typedef struct ... {
874
        if($nostr =~ /^(.*)typedef struct.*{/) {
875
            checkwarn("TYPEDEFSTRUCT",
876
                      $line, length($1)+1, $file, $ol,
877
                      "typedef'ed struct");
878
        }
879

880
        if($nostr =~ /(.*)! +(\w|\()/) {
881
            checkwarn("EXCLAMATIONSPACE",
882
                      $line, length($1)+1, $file, $ol,
883
                      "space after exclamation mark");
884
        }
885

886
        # check for more than one consecutive space before open brace or
887
        # question mark. Skip lines containing strings since they make it hard
888
        # due to artificially getting multiple spaces
889
        if(($l eq $nostr) &&
890
           $nostr =~ /^(.*(\S)) + [{?]/i) {
891
            checkwarn("MULTISPACE",
892
                      $line, length($1)+1, $file, $ol,
893
                      "multiple spaces");
894
        }
895
      preproc:
896
        if($prep) {
897
          # scan for use of banned symbols on a preprocessor line
898
          if($l =~ /^(^|.*\W)
899
                     (WIN32)
900
                     (\W|$)
901
                   /x) {
902
              checkwarn("BANNEDPREPROC",
903
                        $line, length($1), $file, $ol,
904
                        "use of $2 is banned from preprocessor lines" .
905
                        (($2 eq "WIN32") ? ", use _WIN32 instead" : ""));
906
          }
907
        }
908
        $line++;
909
        $prevp = $prep;
910
        $prevl = $ol if(!$prep);
911
        $prevpl = $ol if($prep);
912
    }
913

914
    if(!scalar(@copyright)) {
915
        checkwarn("COPYRIGHT", 1, 0, $file, "", "Missing copyright statement", 1);
916
    }
917

918
    # COPYRIGHTYEAR is a extended warning so we must first see if it has been
919
    # enabled in .checksrc
920
    if(defined($warnings{"COPYRIGHTYEAR"})) {
921
        # The check for updated copyrightyear is overly complicated in order to
922
        # not punish current hacking for past sins. The copyright years are
923
        # right now a bit behind, so enforcing copyright year checking on all
924
        # files would cause hundreds of errors. Instead we only look at files
925
        # which are tracked in the Git repo and edited in the workdir, or
926
        # committed locally on the branch without being in upstream master.
927
        #
928
        # The simple and naive test is to simply check for the current year,
929
        # but updating the year even without an edit is against project policy
930
        # (and it would fail every file on January 1st).
931
        #
932
        # A rather more interesting, and correct, check would be to not test
933
        # only locally committed files but inspect all files wrt the year of
934
        # their last commit. Removing the `git rev-list origin/master..HEAD`
935
        # condition below will enforce copyright year checks against the year
936
        # the file was last committed (and thus edited to some degree).
937
        my $commityear = undef;
938
        @copyright = sort {$$b{year} cmp $$a{year}} @copyright;
939

940
        # if the file is modified, assume commit year this year
941
        if(`git status -s -- "$file"` =~ /^ [MARCU]/) {
942
            $commityear = (localtime(time))[5] + 1900;
943
        }
944
        else {
945
            # min-parents=1 to ignore wrong initial commit in truncated repos
946
            my $grl = `git rev-list --max-count=1 --min-parents=1 --timestamp HEAD -- "$file"`;
947
            if($grl) {
948
                chomp $grl;
949
                $commityear = (localtime((split(/ /, $grl))[0]))[5] + 1900;
950
            }
951
        }
952

953
        if(defined($commityear) && scalar(@copyright) &&
954
           $copyright[0]{year} != $commityear) {
955
            checkwarn("COPYRIGHTYEAR", $copyright[0]{line}, $copyright[0]{col},
956
                      $file, $copyright[0]{code},
957
                      "Copyright year out of date, should be $commityear, " .
958
                      "is $copyright[0]{year}", 1);
959
        }
960
    }
961

962
    if($incomment) {
963
        checkwarn("OPENCOMMENT", 1, 0, $file, "", "Missing closing comment", 1);
964
    }
965

966
    checksrc_endoffile($file);
967

968
    close($R);
969

970
}
971

972

973
if($errors || $warnings || $verbose) {
974
    printf "checksrc: %d errors and %d warnings\n", $errors, $warnings;
975
    if($suppressed) {
976
        printf "checksrc: %d errors and %d warnings suppressed\n",
977
        $serrors,
978
        $swarnings;
979
    }
980
    exit 5; # return failure
981
}
982

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.