Search code examples
c++suppress-warningsubsan

Suppress UndefinedBehaviorSanitizer warnings from external libraries


I have an UndefinedBehaviorSanitizer build (-fsanitize=undefined), and I am trying to suppress a warning for UB in an external library that is out of my control. The clang/gcc docs mention __attribute__((no_sanitize("undefined"))), but to my surprise it seems that this attribute does not suppress warnings from subroutines.

Simple example:

//__attribute__((no_sanitize("shift"))) // this correctly suppresses the warning
int bar() {
    return 1 << 64;
}

__attribute__((no_sanitize("shift"))) // this does not
int foo() {
    return bar();
}

int main() {
    foo();
    return 0;
}

Since this attribute doesn't seem to work, how can I suppress this warning? I could remove the entire target from my UBSan build, but that seems incredibly heavy-handed.


Solution

  • Clang has pragmas to apply attributes in bulk:

    #pragma clang attribute push (__attribute__((no_sanitize("undefined"))), apply_to=function)
    // ...
    #pragma clang attribute pop
    

    Wrapping the header in those disables the check in your example:

    #pragma clang attribute push (__attribute__((no_sanitize("undefined"))), apply_to=function)
    #include <boost/ptr_container/ptr_vector.hpp>
    #pragma clang attribute pop
    
    struct Foo{};
    
    void bar()
    {
        boost::ptr_vector<boost::nullable<Foo>> v;
        v.push_back(nullptr);
        v.push_back(new Foo);
    }
    
    int main()
    {
        bar();
    }