r/cpp • u/James20k P2005R0 • Feb 17 '25
ODR violations and contracts: It seems extremely easy for contract assertions to be quietly turned off with no warning
With contracts being voted into the standard, I thought it'd be a good time to give the future of safety in C++ a whirl. The very first test of them seems...... suboptimal for me, and I'm concerned that they're non viable for anything safety critical
One of the key features of contracts is that different TU's can have different contract level checks. Bear in mind in C++, this includes 3rd party libraries, so its not simply a case of make sure your entire project is compiled with the same settings: we're talking about linked in shared libraries over which you have no control
I'm going to put forwards a test case, and then link some example code at the end. Lets imagine we have a common library, which defines a super useful function as so:
inline
void test(int x) [[pre: x==0]]This function will assert if we pass anything other than 0 into it. This is all well and good. I can toggle whether or not this assertion is fired in my own code via a compiler flag, eg compiling it like this:
-fcontracts -c main.cpp -o main.o -fcontract-semantic=default:abortMeans that we want our assertions to be checked. With contracts, you can write code that looks like this:
#include <cstdio>
#include <experimental/contract>
#include "common.hpp"
void handle_contract_violation(const std::experimental::contract_violation &)
{
printf("Detected contract violation\n");
}
int main()
{
test(1);
printf("Everything is totally fine\n");
return 0;
}This code correctly calls the violation handler, and prints Detected contract violation. A+, contracts work great
Now, lets chuck a second TU into the mix. We can imagine this is a shared library, or 3rd party component, which also relies on test. Because it has performance constraints or its ancient legacy code that accidentally works, it decides to turn off contract checks for the time being:
g++.exe -fcontracts -c file2.cpp -o file2.o -fcontract-semantic=default:ignore#include "common.hpp"
#include "file2.hpp"
void thing_doer()
{
test(1);
}Now, we link against our new fangled library, and discover something very troubling: without touching main.cpp, the very act of linking against file2.cpp has disabled our contract checks. The code now outputs this:
Everything is totally fineOur contract assertions have been disabled due to ODR violations. ODR violations are, in general, undetectable, so we can't fix this with compiler magic
This to me is quite alarming. Simply linking against a 3rd party library which uses any shared components with your codebase, can cause safety checks to be turned off. In general, you have very little control over what flags or dependencies 3rd party libraries use, and the fact that they can subtly turn off contract assertions by the very act of linking against them is not good
The standard library implementations of hardening (and I suspect contracts) use ABI tags to avoid this, but unless all contracts code is decorated with abi tags (..an abi breaking change), this is going to be a problem
Full repro test case is over here: https://github.com/20k/contracts-odr/tree/master
This is a complete non starter for safety in my opinion. Simply linking against a 3rd party dependency being able to turn off unrelated contract assertions in your own code is a huge problem, and I'm surprised that a feature that is ostensibly oriented towards safety came with these constraints
27
u/kamrann_ Feb 17 '25
I'm not going to say I think this is particularly great, but I'm not sure I really see where there is anything new and alarming here specific to contracts. It's not new that you can create an ODR violation by linking together TUs compiled with differing options (e.g.
-Dfoo=defined differently and used within aninlinefunction). And if you have an ODR violation then your program is just broken - the fact that it may manifest as silently disabling some feature seems somewhat moot.Seems to me the issue here is one that has always existed, and is outside the scope of a new language feature, safety-related or not. No language feature gives guarantees about an ill-formed program.
4
u/100GHz Feb 17 '25
A minor request for clarification, is this with respect to the standard or the initial implementation?
10
u/matthieum Feb 17 '25
That's a terrible implementation...
From an optimization perspective:
Why? Context!
That is:
I'm saddened to see pre-conditions being checked within the callee, they are much harder to optimize there, and thus many redundant checks will not be optimized out, which in turn will increase the overhead of turning on contracts checking... and thus likely reduce their usage :'(
In fact, with the pre-conditions checked in caller/post-conditions checked in callee pattern, one can easily scan for missed optimizations by scanning the final assembly for contract handler calls, making it fairly trivial to keep contracts on without paying their cost.
This is somewhat orthogonal to the ODR issue, obviously. Notably, it would still be a problem with post-conditions, and of course with any instantiated template function...
11
u/14ned LLFIO & Outcome author | Committee WG14 Feb 17 '25
I was asked by many people of my opinion throughout the Hagenberg meeting. I said I did not love Contracts as proposed, and I would be unlikely to use them in any code I write in the future. Equally, I don't hate them enough to be opposed - I just don't see the value being added compared to a C preprocessor macro assert, which we already have.
Getting these into the IS was quite tortuous - not as bad as Filesystem, but certainly not much fun for anybody. I'd personally rank them about as pleasant as getting Modules in was - though note that with both efforts, I observed from afar and I did not participate.
I wish we had not - once again - gone for what committee consensus allowed. We should have either gone for full SPARK type contracts whereby functions which don't meet their contract won't compile, or for contracts with no observable side effects which would have eliminated many of the issues with these Contracts (in my opinion, which is not shared by almost anybody). What we've ended up with is in my opinion a bit like with Modules where we would really need a v2 proposal to make them actually useful to most end users solving real world problems. WG21 does not have a good track record on following up on minimum viable solution releases - where is the originally promised Coroutine support library for example (and no, it's not S&R)?
I was asked during Hagenberg what was my opinion on the worst thing in the C++ language? I answered non-deterministic exception throw-catch caused by a very unfortunate design of RTTI which was entirely avoidable. It's the only part of the language which cannot be made deterministic no matter what you do. Unsurprisingly, it's still turned off globally by as much as half of all C++ users. Why the committee refuse to fix this I do not know, as it genuinely impacts most C++ users daily. As of this committee meeting, all my open source libraries now work with C++ exceptions and RTTI globally disabled. Yes, the demand for that really is that strong, it was by far the most often requested feature.
5
u/angry_cpp Feb 17 '25
Could you clarify where is ODR violation in your example? I see that
testdefinition is token to token equal in both TUs.4
u/sweetno Feb 17 '25
I once was renting a flat with a kind of door that you can lock from outside without the key. It was only a matter of time before I locked myself out of the keys I left in. I had to drive to another town to pick the spare key set from the landlady. After I loudly complained to her about this door design, her response was, "Just don't leave the keys inside".
In this vein, while you in principle can link your code with things you didn't compile or compiled, but with different options, you're asking for trouble. Just don't leave the keys inside, just compile it all from source in a consistent configuration.
That is, until you change your doors.
21
u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB Feb 17 '25
This is the same problematic thing as with all compiler-injected code that is enclosed in functions
inline, i.e. the 'contract' between the developers and the linker says: entities with the same name are the same in all translation units that constitute the entire program.There are ways to diagnose such cross-TU tensions.
The funny thing is: as currently specified, this is not an ODR violation because the token sequence as seen by the compiler is the same in all TUs.
7
u/fdwr fdwr@github 🔍 Feb 17 '25
Did they go with a double square bracket approach? I thought it was more like noexcept() with parentheses?
6
u/ContraryConman Feb 17 '25
I guess it's a bit unintuitive but this is not worth not having contracts in the standard over
2
u/dexter2011412 Feb 17 '25
I'm still learning contracts, so please do correct me if I'm wrong. This is inline-ed code so I guess that's kinda "expected" when odr violations happen. Does this happen when the test function is honest-to-god compiled as a shared object?
But yeah, I think additional name mangling (say, with a standard inline namespace for contacts) is helpful here to prevent this issue.
I really wish there was at least a heuristic way to find and warn for odr violations.
Is my understanding accurate here?
1
u/Ambitious-Method-961 Feb 17 '25
Interesting find. I have a few questions, most of these are kinda thinking out loud.
8
u/[deleted] Feb 17 '25
[removed] — view removed comment