Re: [RFC] Mitigating unexpected arithmetic overflow

From: Martin Uecker
Date: Sun May 12 2024 - 04:11:11 EST


Am Mittwoch, dem 08.05.2024 um 16:47 -0700 schrieb Linus Torvalds:
> On Wed, 8 May 2024 at 15:54, Kees Cook <keescook@xxxxxxxxxxxx> wrote:
> >
..
>
> No, the only point where that actually failed was then when a
> (non-overflowing, non-wrapping) final value was assigned to a 16-bit
> field, ie the problem only ever happened at the final assignment:
>
> event->read_size = size;
>
> where no overflow had ever happened before that.
>
> So in *that* case, you actually have a much more interesting
> situation. Not wrap-around, not overflow, but "implicit cast drops
> significant bits".
>
> And yes, I do think implicit integer casts are dangerous. Often *more*
> dangerous than arithmetic overflow and wrapping. We've had absolutely
> tons of them. Some of our most traditional bugs have very much been
> about implicit casting losing bits and causing problems as a result.

In principle, GCC has -Wconversions which looks like that it is
meant to catch this. It seems not entirely stupid, e.g. it warns 
about  the first assignment and not the second (x86):

void f(int i)
{
unsigned short y = i;
unsigned short x = i & 0xFFF;
}

But I guess it still could be smarter. Or does it have to be a
sanitizer because compile-time will always have too many false 
positives?

Martin