File: malloc-init.pl

package info (click to toggle)
0ad 0.0.23.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,412 kB
  • sloc: cpp: 245,162; ansic: 200,249; javascript: 19,244; python: 13,754; sh: 6,104; perl: 4,620; makefile: 977; xml: 810; java: 533; ruby: 229; erlang: 46; pascal: 30; sql: 21; tcl: 4
file content (70 lines) | stat: -rw-r--r-- 2,028 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/perl

# Check for malloc calls not shortly followed by initialisation.
#
# Known limitations:
# - false negative: can't see allocations spanning more than one line
# - possible false negatives, see patterns
# - false positive: malloc-malloc-init-init is not accepted
# - false positives: "non-standard" init functions (eg, the things being
# initialised is not the first arg, or initialise struct members)
#
# Since false positives are expected, the results must be manually reviewed.
#
# Typical usage: scripts/malloc-init.pl library/*.c

use warnings;
use strict;

use utf8;
use open qw(:std utf8);

my $limit = 7;
my $inits = qr/memset|memcpy|_init|fread|base64_..code/;

# cases to bear in mind:
#
# 0. foo = malloc(...); memset( foo, ... );
# 1. *foo = malloc(...); memset( *foo, ... );
# 2. type *foo = malloc(...); memset( foo, ...);
# 3. foo = malloc(...); foo_init( (type *) foo );
# 4. foo = malloc(...); for(i=0..n) { init( &foo[i] ); }
#
# The chosen patterns are a bit relaxed, but unlikely to cause false positives
# in real code (initialising *foo or &foo instead of foo will likely be caught
# by functional tests).
#
my $id = qr/([a-zA-Z-0-9_\->\.]*)/;
my $prefix = qr/\s(?:\*?|\&?|\([a-z_]* \*\))\s*/;

my $name;
my $line;
my @bad;

die "Usage: $0 file.c [...]\n" unless @ARGV;

while (my $file = shift @ARGV)
{
    open my $fh, "<", $file or die "read $file failed: $!\n";
    while (<$fh>)
    {
        if( /mbedtls_malloc\(/ ) {
            if( /$id\s*=.*mbedtls_malloc\(/ ) {
                push @bad, "$file:$line:$name" if $name;
                $name = $1;
                $line = $.;
            } else {
                push @bad, "$file:$.:???" unless /return mbedtls_malloc/;
            }
        } elsif( $name && /(?:$inits)\($prefix\Q$name\E\b/ ) {
            undef $name;
        } elsif( $name && $. - $line > $limit ) {
            push @bad, "$file:$line:$name";
            undef $name;
            undef $line;
        }
    }
    close $fh or die;
}

print "$_\n" for @bad;