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

Consider -ftrapv for C and C++ Compiler Hardening Guide #685

Open
thomasnyman opened this issue Oct 31, 2024 · 2 comments · May be fixed by #694
Open

Consider -ftrapv for C and C++ Compiler Hardening Guide #685

thomasnyman opened this issue Oct 31, 2024 · 2 comments · May be fixed by #694

Comments

@thomasnyman
Copy link
Contributor

thomasnyman commented Oct 31, 2024

Splitting this off from Dominik Czarnota's extensive feedback in #330.

The -ftrapvoption that can be used to trap integer overflows instead of letting the compiler optimize on the undefined wrapping behavior.

We currently suggest the opposite, -fwrapv as option to the-fno-strict-overflow recommendation (which has identical semantics as-fno-strict-overflow in Clang). For the cases where it's desirable to trap on overflow, it might better to recommend the use of sanitizers, specificall -fsanitize=signed-integer-overflow part of UBSAN.

Considering more optimization-affecting options was also brought up in the discussion to #660.

Resources:

@thomasnyman thomasnyman changed the title Consider -ftrapv Consider -ftrapv for C and C++ Compiler Hardening Guide Oct 31, 2024
@thomasnyman thomasnyman self-assigned this Oct 31, 2024
@thomasnyman
Copy link
Contributor Author

This issue was discussed during the C/C++ Compiler CP Call 2024-10-31 and that discussion came to the conclusion that section 3.21 Integer overflow may occur should be reworked to list the different alternative ways of introducing defined behavior for signed integer overflows, i.e., the (-fno-strict-overflow/ -fwrapv covered in the current guide and as well as the -ftrapv / -fsanitize=signed-integer-overflow alternatives in this issue) together with a explicit statement of how the options change C / C++ behavior, their tradeoffs, and that different projects may have different considerations for which behavior they might rely on.

@david-a-wheeler
Copy link
Contributor

That word "rely" makes me worry a little.

The C standard does not impose any particular behavior on integer overflow/underflow. I think it's best to try to write code that does not require any particular behavior, then use the flags to detect/handle mistakes made by the developer. If a program is intentionally written to require a specific behavior, that'll make the code less portable in a very subtle way.

I think we should recommend trying to write code that doesn't assume any specific behavior, and using these flags to try to deal with inevitable mistakes.

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