qemu-devel
[Top][All Lists]
Advanced

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

Re: [Qemu-devel] [PATCH] inet_listen_opts: add error checking


From: Eric Blake
Subject: Re: [Qemu-devel] [PATCH] inet_listen_opts: add error checking
Date: Thu, 12 Dec 2013 08:50:23 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.1.0


On 12/12/2013 05:27 AM, Gerd Hoffmann wrote:
>   Hi,
> 
>>> +    if (port_offset) {
>>> +        int baseport;
>>> +        errno = 0;
>>> +        baseport = strtol(port, NULL, 10);
> 
>> <rant>
>> WHY is strtol() such a PAINFUL interface to use correctly?
> 
> Crossed my mind too after reading the manpage, which sayed you should
> clear errno to reliable detect errors as checking the return value
> doesn't cut it.
> 
> Your points obviously underline that.
> 
>>   And WHY
>> can't qemu copy libvirt's lead of writing a SANE wrapper function, and
>> then mandating that the rest of the code base use the sane wrapper
>> instead of strtol()?
>> </rant>
> 
> Care to share a pointer to the code?

/* Like strtol, but produce an "int" result, and check more carefully.
   Return 0 upon success;  return -1 to indicate failure.
   When END_PTR is NULL, the byte after the final valid digit must be NUL.
   Otherwise, it's like strtol and lets the caller check any suffix for
   validity.  This function is careful to return -1 when the string S
   represents a number that is not representable as an "int". */
int
virStrToLong_i(char const *s, char **end_ptr, int base, int *result)
{
    long int val;
    char *p;
    int err;

    errno = 0;
    val = strtol(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s || (int) val != val);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

and other variants of virStrToLong_* for parsing into unsigned int,
long, etc.

Libvirt then couples that with a syntax check that gets run during 'make
syntax-check' (or we could even migrate it into 'make check') that
forbids all use of strtol() not on a line with the magic exemption
comment.  Therefore, the number of actual uses of strtol() in the source
code base is limited to just these wrapper functions, and everyone else
gets sane semantics.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]