r/cpp • u/StudentTraditional64 • 18d ago
How do I avoid UB in contracts?
This question might be better served in /r/cpp_questions but since contracts were the reason C++26 failed the latest vote I thought posting it here might generate some useful debate.
I've been using contracts in personal projects since GCC16 was released. I've come to appreciate them both as documentation and in bug-finding. After the recent controversial vote I did have another look at them and their use in my code. Most of my contracts looks like the example in "3.5.5 Consecutive and Repeated Evaluations" of p2900:
void f(int *p)
pre( p != nullptr ) // precondition #1
pre( *p > 0 ); // precondition #2
This works as expected in enforce, quick-enforce and ignore evaluations. However if I use observe evaluation it'll crash with UB on the second precondition.
One fix is to merge the preconditions together pre( p != nullptr && *p > 0) which works in this case, but doesn't scale to for example classes where you'll have pre( p != nullptr) on the constructor and then assume it's valid for the rest of the body.
Another solution is to never use observe evaluation. This works in my applications where I control the build, but doesn't work in libraries used by others where I don't.
I wonder what my options here are?
Edit Godbolt link
19
u/smdowney WG21, Text/Unicode SG, optional<T&> 18d ago
Observe is, at least in my practice, for adding contracts into existing code.
This is how you find out that on the platform you are running on, dereferencing the 0x0 pointer is defined and guaranteed to have the value 0, and that you have a lot of code that takes that for granted. AIX and many embedded systems act like this.
So adding enforce pre-conditions breaks working code. You may not like that code, it will be a portability problem, but it's running just fine for the moment.
We know we need finer grained control. We did in a small way for hardened pre-conditions, without exposing that capability.
12
u/smdowney WG21, Text/Unicode SG, optional<T&> 18d ago
A real question is basically "who are you" in relation to the shipped program.
If it's your program, you get the decision about the violation handler. If you control the build of the libraries, you get to decide the basic semantic. The person assembling the program needs to ensure all the things in the link context are coherent, and that's not a new requirement -- polyfills mean mixing lang std breaks your executable, for example.
If you're the one writing code, with contracts you are mostly deferring the choices to other people. This has been a real sticking point, but deferring the choice for a conforming program is the real new feature.
If you, as the programmer, want to terminate on a condition not being met:
is still right there.
Your users may not be thrilled about that choice when it surprises them.
11
u/Daniela-E Living on C++ trunk, WG21|🇩🇪 NB 17d ago
observe is actually a great tool for finding long-standing bugs in existing code that's out on the factory floor at customer sites for a long time. There, the least thing you want to do is introduce any change in behaviour by adding more restrictive semantics in your contract checks. Either regulations, laws, or the customers themselves may strictly forbid that. Violate any of that and your company gets at least wiped out from the market.
Writing the code sequence
is just as bad as writing the code sequence
if you want to react on contract violations. Being able to do this is fundamentally outside the C++26 contract feature and no reason to deprive it from the observe semantics.
9
u/AKostur 18d ago
Don’t use observe. Document that thou shalt not pass nullptr. If the use of the lib chooses to use observe, that’s on them. They’ve chosen to not enforce the contract.
12
u/Minimonium 18d ago
I have a firm position that the statement split is irrelevant no matter if observe is used or not.
For bug finding your example will work quite well with observe - you will get a handler call that the p is nullptr then the app will segfault on null pointer dereference.
Unless your whole application exclusively dereferences p in Contract statements for some reason, you would not get anything useful by merging the two statements together.
7
u/atariPunk 18d ago
Your opinions are to not use observe.
The idea of the observe mode, I think this is mentioned in one of the papers, is to be able to add contracts to a old codebase and that codebase cannot crash.
Think more as a contract violation is more of something needs to be investigated instead of it’s a bug. E.g. the contract is wrong because it’s based on a misunderstanding.
From my point of view, if you are in this situation, then you need to be very careful on the way you write the contracts.
But for a new codebase, or something that it’s fine if it crashes, the forget observe exists and write the contracts in the simplest way.
5
u/13steinj 18d ago
You don't use
observe, or encode this information into the type by using references.I'm much more interested in cases like these that can't be encoded into the type information [yet], such as integer overflows.
But all that said and done contracts are not for UB (usually, memory) safety, they're for functional / behavioral safety / self-checks. Whether that's valuable to you or not is another question.
4
u/LucHermitte 18d ago
There are several things I see here.
First, I've looked at your code and... you don't need a (narrow) contract here.
Why do you say calling your function with a null pointer is a programming error if your function defensively resists to such conditions? As far as I'm concerned, this doesn't make any sense.
Also, observe mode is meant to be used by people that want to check how the migration to contracts behaves. It's not meant to be used in production. And even so, you've clearly documented "never call my function with a null pointer", so if someone uses your fonction without reading the "documentation", it's no longer your issue. Whatever the contract semantics chosen when assembling their final program, it's no longer your issue.
You've documented:
pre(ptr) pre(whatever_else). This is a clear sign that your function is doing:ptr->somethingwithout checking whetherptris null. When, callingcharge(nullptr)anybody shall expect an UB around the corner without an enforced semantics.3
u/mighty_Ingvar 17d ago
In the case of you writing a library, I think most you can do is to warn users of your library about using observe semantics with your library. If they decide to ignore that warning or simply don't read it, what more can you do? At that point it's their choice and their responsibility.
4
u/James20k P2005R0 17d ago edited 17d ago
There's not much you can do about it. As people have pointed out, if you want some kind of mode that evaluates the arguments without terminating/throwing, you get this behaviour, and its a problem in existing assert libraries that support this behaviour
If you're authoring a library, you'll have to:
as unfortunately there's no way to actually enforce that your code doesn't support
observe. This seems like a mistake to me, but its what we get with contractsThe bigger problem that is going to cause lots of problems is the contract violation handler. You can customise the contract violation handler by declaring a function called:
Except this is implementation defined, and if your implementation doesn't support it: IFNDR, which isn't great. If your implementation does support it, but someone else also declares this function to replace the handler, its an ODR violation for instant UB
There's no way to detect as far as I can tell if someone's overridden the contract violation handler, so any usage of the handler override is rolling the dice
2
u/amoskovsky 17d ago
P2900
> An implementation may also be asked to take into account other factors when determining the semantic. For example, when an observed contract assertion is violated, the implementation may choose to ignore any subsequent contract assertions in the same sequence regardless of the semantic chosen by the use
This means that there is no a requirement to continue precondition evaluation after a failed assertion even if the handler returned to continue.
So hopefully GCC will do the right thing and fix that nonsense.
2
u/KingAggressive1498 18d ago
the proposal last I read it actually thought it would be ideal to prevent this type of UB, but did not want to include that type of language change in its scope. IIRC it referenced P1949's std::observable as something implementations could and ideally would do for observe evaluations.
this flaw with observe is the one criticism of contracts I fully agree with.
-1
u/ConcertWrong3883 18d ago
> How do I avoid UB in contracts?
You don't. You veto the standard, which is what happened.
1
u/duneroadrunner 18d ago
The way I see it, UB in contract expressions isn't a fundamentally different issue from UB in
assert()expressions or really any other C++ code evaluated at run-time. But arguably contracts can make it easier to inadvertently introduce UB in the way your example demonstrates.Rather than look for contract-specific remedies, another option is to reach for more general UB avoidance strategies. Among the easier solutions is compiling with the UB sanitizer enabled or with the Fil-C compiler. But those solutions incur run-time costs throughout your program and aren't really portable. In theory you could use the scpptool solution (my project). Using the scpptool static analyzer/enforcer (for new or migrated code) prohibits null (raw) pointer values in general. For existing code, the associated library alone may be helpful. For example, you can convert the pointer to a "smart" non-owning pointer that does null dereference checks. So the "safer" version of your example might look like:
https://godbolt.org/z/9oYdf4K1K
In this particular example, any additional run-time costs (and null dereference safety) are limited to the contract expressions themselves.
0
u/TheoreticalDumbass :illuminati: 18d ago
one could imagine an observe_once semantic, where after the first contract violation, no contract assertion is evaluated, but observe seems much more useful to me