[rust-dev] Integer overflow, round -2147483648

Gregory Maxwell gmaxwell at gmail.com
Wed Jun 18 13:05:45 PDT 2014


On Wed, Jun 18, 2014 at 10:08 AM, Gábor Lehel <glaebhoerl at gmail.com> wrote:
> memory safety bugs.) This is a step up from C's insanity of undefined
> behavior for signed overflow, where the compiler assumes that overflow
> *cannot* happen and even optimizes based on that assumption, but it's still
> a sad state of affairs.

C's behavior is not without an advantage.  It means that every
operation on signed values in C has an implicit latent assertion for
analysis tools:  If wrapping can happen in operation the program is
wrong, end of story.  This means you can use existing static and
dynamic analysis tools while testing and have a zero false positive
rate— not just on your own code but on any third party code you're
depending on too.

In languages like rust where signed overflow is defined, no such
promises exists— signed overflow at runtime might be perfectly valid
behavior, and so analysis and testing require more work to produce
useful results.  You might impose a standard on your own code that
requires that all valid signed overflow must be annotated in some
manner, but this does nothing for third party code (including the
standard libraries).

The value here persists even when there is normally no checking at
runtime, because the tools can still be run sometimes— which is less
of a promise than always on runtime checking but it also has no
runtime cost.

So I think there would be a value in rust of having types for which
wrap is communicated by the developer as being invalid, even if it
were not normally checked at runtime. Being able to switch between
safety levels is not generally the rust way— or so it seems to me— and
may not be justifiably in cases where the risk vs cost ratio is
especially high (e.g. bounds checking on memory)... but I think it's
better than not having the safety facility at all.

The fact that C can optimize non-overflow is also fairly useful in
proving loop bounds and allowing the autovectorization to work.  I've
certantly had signal processing codebases where this made a
difference, but I'm not sure if the same communication to the
optimizer might not be available in other ways in rust.

> `CheckedAdd` and co. are important to have for flexibility, but they're far
> too unwieldy for general use. People aren't going to write
> `.checked_add(2).unwrap()` when they can write `+ 2`. A more adequate design
> might be something like this:

Not only does friction like that discourage use— it also gets in the
way of people switching behaviors between testing and production when
performance considerations really do preclude always on testing.


More information about the Rust-dev mailing list