Re: [PATCH] Enhanced stats for fullvirt domains

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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@xxxxxxxxxx> 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;
}

--
Libvir-list mailing list
Libvir-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/libvir-list

[Index of Archives]     [Virt Tools]     [Libvirt Users]     [Lib OS Info]     [Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]     [Fedora Tools]