qemu-devel
[Top][All Lists]
Advanced

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

Re: [Qemu-devel] [PATCH v2] bitops.h: Add field32() and field64() functi


From: Peter Maydell
Subject: Re: [Qemu-devel] [PATCH v2] bitops.h: Add field32() and field64() functions to extract bitfields
Date: Wed, 27 Jun 2012 14:07:45 +0100

On 27 June 2012 12:39, Eric Blake <address@hidden> wrote:
> On 06/27/2012 04:29 AM, Peter Maydell wrote:
>> +static inline uint64_t field64(uint64_t value, int start, int length)
>> +{
>> +    assert(start >= 0 && start <= 63 && length > 0 && start + length <= 64);
>
> You're failing to account for wraparound:
>
> field64(value, 63, MAX_INT)
>
> gives undefined behavior in the addition, and even on (most) platforms
> where it silently wraps around to a negative number, you have then
> missed triggering the assert and proceed to do more unefined behavior
> with a negative shift.  You can solve that, and use one less conjunct,
> by using:
>
> assert(start >= 0 && length > 0 && (unsigned) start + length <= 64);

Yes, that works (took me a minute to figure out that it relies on
two positive ints not being able to overflow an unsigned int).

-- PMM



reply via email to

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