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

Implicit function-to-function casts allow for undefined behavior in generated C #143

Open
ashn-dot-dev opened this issue Nov 25, 2024 · 0 comments

Comments

@ashn-dot-dev
Copy link
Owner

Sunder allows implicit casting of a function with parameter types and/or a return type of type *T to a function type where those same parameter types and/or return type are of type *any. In the original NASM-flavored assembly emitted when Sunder was targeting x64 Linux, this function-to-function casting was explicitly permitted, as the stack-based Sunder calling convention guaranteed function calls with these types to be ABI-compatible. However, ISO C does not permit this form of casting, leading to undefined behavior when UBSan encounters a function call made using a function value that was the result of such a cast:

~/sources/sunder[main]$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 24.04.1 LTS
Release:        24.04
Codename:       noble
~/sources/sunder[main]$ clang -v
Ubuntu clang version 18.1.3 (1ubuntu1)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/13
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/13
Candidate multilib: .;@m64
Selected multilib: .;@m64
~/sources/sunder[main]$ git rev-parse HEAD
b426793813d5d943fec12d6f005ae4294391580d
~/sources/sunder[main]$ SUNDER_CC=clang SUNDER_CFLAGS='-fsanitize=undefined' sunder-run examples/hello.sunder
a.out.tmp.c:4285:310: runtime error: call to function std_file_write through pointer to incorrect function type 'struct std_result_TEMPLATE_BGN_usize_COMMA_pointer_to_std_error_info_TEMPLATE_END (*)(void *, __sunder_slice_of_byte)'
(/home/ashn/sources/sunder/a.out+0x50ae8): note: std_file_write defined here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior a.out.tmp.c:4285:310
Hello, world!

In practice, it is expected that these casts should be well behaved on modern Unix-like platforms, as one would expect all pointer types to be represented the same at the ABI level. However, there is no strict guarantee that this behavior will remain true for all current and future supported platforms.

See these comments in codegen.c for additional context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant