Clang link-time optimization with replaced operator new causes mismatched free()/delete in valgrind

前端 未结 1 2000
旧巷少年郎
旧巷少年郎 2021-01-13 08:02

When using clang 3.5.0 with -flto and linking with a shared library, it seems that calls to operator delete in the shared library don\'t follow the same symbol

相关标签:
1条回答
  • 2021-01-13 08:28

    Looking at the object-dump, it is obvious operator delete(void*) is not exported by main.

    $ objdump -T main | c++filt | grep operator
    0000000000400990 g    DF .text  0000000000000033  Base        operator new(unsigned long)
    0000000000000000      DF *UND*  0000000000000000  Base        operator delete(void*)
    

    See that the section where operator delete(void*) is stored is *UND*: It is not there!

    Now, that's an obvious failure on clang's part, might make a good bug-report, as we already have a minimal test-case.

    Now, how to force clang to keep and export operator delete(void*) as a band-aid?
    The answer is looking at the possible attributes, there's a good one:

    used
    This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly. When applied to a member function of a C++ class template, the attribute also means that the function is instantiated if the class itself is instantiated.

    Putting that in the code:

    void operator delete(void* ptr) noexcept  __attribute__((used)) {
    

    And voilá, clang no longer improperly prunes it.

    0 讨论(0)
提交回复
热议问题