clanglto

Why is the address sanitizer only triggered when LTO is off for this code?


I have the following code, for which address sanitizer only catches the violation when LTO is off. Changing between -Os and -O0 doesn't affect it. Any ideas why?

char *__attribute((noinline)) SCObfuscatedMalloc();

void SCCauseAddressSanitizerViolation() {
    char *chars = SCObfuscatedMalloc();
    if (rand() & 1) {
        chars[2] = 3;
    } else {
        chars[2] = 2;
    }
    printf("yo: %zd\n", (NSInteger)chars[2]);
}

char *__attribute((noinline)) SCObfuscatedMalloc() {
    return malloc(1);
}

Solution

  • I recently ran into this problem, not on clang bug GCC though. I looked at the objdump with and without -flto: it appears LTO removed all calls to the instrumented checker functions.

    I guess what LTO did is: it looked at the inserted check code and found that these code can never be reachable, because they are checking UBs, which LTO assumes can never happen. So LTO just removed them.

    But O3 was good.