Search code examples
c++undefined-behaviorubsan

How to suppress some unsigned-integer-overflow errors from UBsan?


Most of my -fsanitize=unsigned-integer-overflow errors are bugs, but sometimes I explicitly use it as intended, which results in UBSan producing false positives.

Is there a way to turn UBSan unsigned-integer-overflow check off for a particular expression?

EDIT in response to Shafik comment, here is an example:

unsigned a = 0;
unsigned b = a - 1; // error: unsigned integer overflow

Most of the time that is a bug, sometimes it isn't. With UBSan one can find every time that happens, fix the bugs, but I haven't found a way to silence the false positives.

EDIT 2: to enable the check one needs to pass either -fsanitize=integer (to enable all integer checks) or fsanitize=unsigned-integer-overflow. From the comments below it seems that the check is only available in clang and not in GCC yet.


Solution

  • If you want to wrap the operation in a function you can use __attribute__((no_sanitize("integer"))) like so (see it live):

    __attribute__((no_sanitize("integer")))
    unsigned calc( unsigned a )
    {
        return a - 1 ;
    }
    

    I found this via a bug report/feature request Suppression support for UbSAN.

    The clang documentation on attributes does not indicate any way to apply this except to a function:

    Use the no_sanitize attribute on a function declaration to specify that a particular instrumentation or set of instrumentations should not be applied to that function. The attribute takes a list of string literals, which have the same meaning as values accepted by the -fno-sanitize= flag. For example, attribute((no_sanitize("address", "thread"))) specifies that AddressSanitizer and ThreadSanitizer should not be applied to the function.