google / sanitizers

AddressSanitizer, ThreadSanitizer, MemorySanitizer
Other
11.51k stars 1.03k forks source link

UBSan does't report UB for printf in signal handler #1523

Open rootkea opened 2 years ago

rootkea commented 2 years ago

Hello!

As per C17: (paraphrasing) "the behavior is undefined if \<snip>, or the signal handler calls any function in the standard library other than abort, _Exit, quick_exit, atomic_is_lock_free, signal and functions in <stdatomic.h>"

So this program invokes UB when tried to end with Ctrl+c (SIGINT):

#include <signal.h>
#include <stdio.h>

void handler(int sig)
{
    printf("Caught %d\n", sig);
}

int main(void)
{
    if (signal(SIGINT, handler) ==  SIG_ERR)
        perror("signal");
    else
        for(;;);

    return 0;
}

But UBSan doesn't report this undefined behavior.

$ clang --version
Ubuntu clang version 13.0.0-2
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
$ echo $CFLAGS 
-Wall -Wextra -g -O0 -fsanitize=address -fsanitize=leak -fno-omit-frame-pointer -fno-optimize-sibling-calls -fsanitize=undefined -fsanitize=float-divide-by-zero -fsanitize=unsigned-integer-overflow -fsanitize=implicit-conversion -fsanitize=local-bounds -fsanitize=nullability -std=c17 -pedantic
$ echo $LDFLAGS 
-g -fsanitize=address -fsanitize=leak -fsanitize=undefined -fsanitize=float-divide-by-zero -fsanitize=unsigned-integer-overflow -fsanitize=implicit-conversion -fsanitize=local-bounds -fsanitize=nullability
$ echo $ASAN_OPTIONS 
check_initialization_order=1:detect_stack_use_after_return=1:detect_invalid_pointer_pairs=2
$ echo $UBSAN_OPTIONS 
print_stacktrace=1
$
yugr commented 2 years ago

@rootkea UBSan does not detect all types of UB and in particular, not calling unsafe functions in signal handlers. You may be interested in sighandlercheck.