Re: [RFC][PATCH 0/5] Fixes for abs() usage on 64bit values

From: Jeff Epler
Date: Tue Sep 15 2015 - 08:48:23 EST


On Mon, Sep 14, 2015 at 11:46:32PM -0400, Tejun Heo wrote:
> Hello,
>
> On Mon, Sep 14, 2015 at 08:27:08PM -0700, John Stultz wrote:
> > Yea. The above make sense to me, but I suspect there's some very
> > subtle reason for the existing separated logic.
> > But I'd have to defer to akpm for hints on that.
>
> Hmmm... people could be using it for calculating the distance between
> two unsigned values and in that case the original behavior would be
> the correct one. e.g.
>
> unsigned diff, a, b;
> diff = abs(a - b);

This kind of construct can overflow whether a and b are signed or
unsigned. Only a two-argument function can correctly return the
absolute difference of two integers.

At my day job, we arranged for
abs(unsigned type) to be a compile-time error and supplied a two args
function absdiff for use in these situations -- absdiff(a,b) is the same
as abs(a-b) except it avoids overflow and returns an unsigned type.

(though I have no doubt that some instances of abs(a - b) still exist
where a and b are signed and the intermediate could still overflow...)

Jeff
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/