Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix invalid function pointer cast in cpuinfo.c #275

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

davidben
Copy link

While casting function pointers is allowed in C, the function must ultimately be called through a pointer with the same type signature as the function itself. Type signature mismatches, even decaying T* to void* is undefined behavior.

UBSan flags this with -fsanitize=function. The easiest way I found to repro this was:

CC=clang-18 CXX=clang++-18 \
CFLAGS="-fsanitize=function -fno-sanitize-recover=function" \
CXXFLAGS="-fsanitize=function -fno-sanitize-recover=function" \
cmake -GNinja -B build -DCPUINFO_BUILD_BENCHMARKS=OFF

ninja -C build

./build/cpu-info

That gives the following error:

[...]/src/linux/multiline.c:85:11: runtime error: call to function parse_line through pointer to incorrect function type 'bool (*)(const char *, const char *, void *, unsigned long)'
cpuinfo.c: note: parse_line defined here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior [...]/src/linux/multiline.c:85:11

The fix is fairly straightforward: just keep the function at the type signature the expected, and cast void* instead the function instead.

While casting function pointers is allowed in C, the function must
ultimately be called through a pointer with the same type signature as
the function itself. Type signature mismatches, even decaying T* to
void* is undefined behavior.

UBSan flags this with -fsanitize=function. The easiest way I found to
repro this was:

    CC=clang-18 CXX=clang++-18 \
    CFLAGS="-fsanitize=function -fno-sanitize-recover=function" \
    CXXFLAGS="-fsanitize=function -fno-sanitize-recover=function" \
    cmake -GNinja -B build -DCPUINFO_BUILD_BENCHMARKS=OFF

    ninja -C build

    ./build/cpu-info

That gives the following error:

    [...]/src/linux/multiline.c:85:11: runtime error: call to function parse_line through pointer to incorrect function type 'bool (*)(const char *, const char *, void *, unsigned long)'
    cpuinfo.c: note: parse_line defined here
    SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior [...]/src/linux/multiline.c:85:11

The fix is fairly straightforward: just keep the function at the type
signature the expected, and cast void* instead the function instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants