Re: [RFC] Mitigating unexpected arithmetic overflow

From: Linus Torvalds
Date: Wed May 08 2024 - 20:06:34 EST


On Wed, 8 May 2024 at 16:47, Linus Torvalds
<torvalds@xxxxxxxxxxxxxxxxxxxx> wrote:
>
> But again, maybe it would be worth looking into, at least for some
> limited cases. To go back to your particular example, it might be
> worth trying to limit it for unusual type sizes like implicit casts to
> 'u16' or bitfields: not because those type sizes are magical, but
> because it might be a way to limit the pain.

I think it would be interesting in general to have some kind of
warning for "implicit cast drops bits".

I fear that we'd have an enormous about of them, and maybe they'd be
unsolvable without making the code *much* uglier (and sometimes the
fix might be to add an explicit cast to document intentionally dropped
bits, but explicit casts have their own issues).

So that's why I feel like it might be interesting to see if limiting
such checks to only "unusual" types might give us a manageable list of
worrisome places.

I think it *would* have flagged the perf u16 overflow case. Again: I
don't think that was actually ever overflow or wrap-around in the
arithmetic sense, and it was purely a "assignment to smaller field
truncated bits" issue.

Which again is most definitely not undefined behavior, but I would not
be at all surprised if it was a much more common issue than actual
arithmetic overflow is.

Linus