[Libvir] [PATCH] Enhanced stats for fullvirt domains

Jim Meyering jim at meyering.net
Wed Sep 26 06:50:47 UTC 2007


Hi Rich,

I know this patch just moved the code below,
and the probability of data corruption and file I/O errors
here is low, but...

"Richard W.M. Jones" <rjones at redhat.com> wrote:
> +static int64_t
> +read_stat (const char *path)
> +{
> +    char str[64];
> +    int64_t r;
> +    int i;
> +    FILE *fp;
> +
> +    fp = fopen (path, "r");
> +    if (!fp) return -1;
> +    /* stupid GCC warning */ i = fread (str, sizeof str, 1, fp);
> +    r = strtoll (str, NULL, 10);
> +    fclose (fp);
> +    return r;
> +}

Since all of fread, strtoll, and fclose can fail, and since the 64 bytes
from fread might be a valid prefix, but not terminated (i.e., strtoll
could overrun the STR buffer -- yeah, it's far-fetched, but still) the
above should probably be rewritten something like e.g.,

WARNING: the following may not even compile

/* Convert NUL-or-NL-terminated string to int64_t, detecting overflow,
   invalid string (i.e., non-digit), or a long long value that doesn't
   fit in int64_t (probably only theoretical). */
static int
xstrtoint64 (char const *s, int base, int64_t *result)
{
    long long int lli;
    char *p;

    errno = 0;
    lli = strtoll (s, &p, base);
    if (errno || !(*p == 0 || *p == '\n') || p == s || (int64_t) lli != lli)
        return -1;
    *result = lli;
    return 0;
}

static int64_t
read_stat (const char *path)
{
    char str[64];
    int64_t r;
    int i;
    FILE *fp;

    fp = fopen (path, "r");
    if (!fp)
      return -1;

    /* read, but don't bail out before closing */
    i = fread (str, sizeof str, 1, fp);

    if (fclose (fp) != 0
        || i < 2             /* ensure we read at least two bytes */
        || str[i - 1] != 0   /* the last byte must be zero */
        || xstrtoint64 (str, 10, &r) != 0)
      return -1;

    return r;
}




More information about the libvir-list mailing list