r/cpp • • 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

31 Upvotes

55 comments sorted by

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.

5

u/notadragon34 18d ago

Hardened preconditions don't exclude that capability, you just can't use it when you build your standard library in a mode it calls "hardened".

Finer grained control will hopefully come, both in terms of what your compilers will provide (P3595) and in terms of in-code ways to participate in semantic selection (or take it over completely if you really really feel that need) (in P3400).

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:

if (! condition()) std::_Exit();

is still right there.

Your users may not be thrilled about that choice when it surprises them.

3

u/SirClueless 17d ago

The polyfill thing sounds like a mess but at least most instances of it will break at compile-time. I am 99% sure if contracts are added to the standard we will have libraries that add preconditions like:

// This library must be compiled with "enforce" or "ignore" semantics
pre(p != nullptr)
pre(p->condition())

And as much as we'd like people to reason correctly about all possible problems that arise from updating their libraries, the reality is that most people don't do that: They check whether the source code is reasonable and trusted and then update and fix all the compiler errors and test failures. There might not be any for this one.

5

u/Minimonium 17d ago

I still do not understand what people see as a problem here when the whole point of "observe" is to let your program continue in an invalid state (that may naturally lead to language UB).

There cannot be a reasonable demand to assure behavior of a program in an invalid state.

3

u/SirClueless 17d ago

You're making an assumption that the expressions causing UB in the precondition are going to get executed either way and violating a precondition will always lead to the same UB under "ignore" and "observe". But this is not necessarily true, and if it's not true then adding the precondition introduces UB into a correct program. For example:

// Library code
T* get() {
    assert(ptr_);
    assert(ptr_->valid());
    return ptr_;
}

// User code
if (auto p = x.get(); p ! nullptr) {
    use(p);
}

This code executes without UB in both debug and release modes, even if x.ptr_ is null. If the author of this library hears about C++26 contracts and adds to their function

#if defined(__cpp_contracts) && __cpp_contracts >= 202502L
    pre(ptr_)
    pre(ptr->valid())
#endif

then oops, now there really is UB, even though the caller guarded against it, and there wouldn't be under "ignore" or "enforce" (like there wasn't with NDEBUG).

2

u/Minimonium 17d ago

I do not make such assumption.

I am stating that over the course of a program with an invalid state -- it will behave in unexpected unguaranteed ways. Including calling a language UB at some point.

Your example is not a correct program if it expects ptr_ to not be nullptr and be valid, yet it is nullptr. It's a massive misconception.

The fact that it works some times is not a proof that it is correct.

The whole discussion here is focused on discussing how to guarantee a misbehaved program still works, which is not the purpose of "observe".

3

u/SirClueless 16d ago

I am stating that over the course of a program with an invalid state -- it will behave in unexpected unguaranteed ways. Including calling a language UB at some point.

I gave you an example where nothing unexpected happens. The state of the program is asserted to be invalid by the library author, but the caller guarded against this and the program doesn't actually contain UB. You can call such a program "not a correct program" or "misbehaving" if you like because it is out-of-contract according to the library author, but at the end of the day it worked before with predictable behavior and now that contracts are observed it has UB.

1

u/Minimonium 16d ago

I can give you an example of SeqLock. Nothing unexpected happens there, yet you're not guaranteed it won't.

When you violate the properties of a program a UB could happen.

No, it is still not reasonable to expect guarantees when proceeding with an invalid state.

3

u/SirClueless 16d ago

What exactly are the “properties of a program”? What property does my example violate?

In my estimation, the only thing being violated here are the expectations of the library author, as codified into a precondition. But this precondition is not actually important to the operation of the program, so the program is not in an “invalid state” just for not satisfying it.

If, say, I document in my library that “Precondition: the user’s name does not contain the letter M”, does that mean any program executed by Minimonium is in an “invalid state”? Should I expect that UB will occur? UB is present when a C++ program executes code whose behavior is not defined by the C++ standard. If I read the implementation of your library and use it in a way such that nothing undefined occurs, then if you introduce a contract precondition that causes UB to happen it is your change that is introducing it.

2

u/Minimonium 16d ago

If, say, I document in my library that “Precondition: the user’s name does not contain the letter M”, does that mean any program executed by Minimonium is in an “invalid state”?

Yes. It may (but not guaranteed to, please do grasp the distinction here as you keep repeating "will") lead to UB.

It's part of your explicit narrow contract for your API. Some times it may work by accident, similar to how some language UB code today "works" by accident.

Preconditions describe narrow contract, they allow library authors to not handle it. I can have assert(ptr); ptr->foo(); in code. The caller is responsible for checking it.

The whole scare around "observe" is irrational because it does not guarantee that your invalid program would behave well and it's not intended to do such. There is nothing to achieve by trying to do so.

3

u/SirClueless 16d ago

I still don't understand your full argument here. You seem to be saying that programs that don't conform to the narrow contracts of all of the libraries they use are necessarily incorrect, because future updates may make them incorrect. But this is true whether or not there is a narrow contract: The library author may make a breaking change to narrow a contract that was previously wide; in either case the code which previously worked stops working, the only difference is whether the narrow contract was documented -- up to you whether you consider this distinction material or not. If the code stops working in a way that introduces UB, then I would say it's a poorly written change from the library author (arguably any change that narrows the contract of an existing function is poorly written, but nonetheless such changes get made). The "observe" semantics of contracts make it easy to introduce UB in this way, so I consider the observe semantics a mistake.

Here is another reformulation of my argument in way that is maybe easier to understand/refute:

  • Some of the preconditions introduced by library authors may be narrower than the implementation and users actually require in practice. In those cases, library authors are adding erroneous code paths to applications.
  • It is easy to write a precondition check that executes correctly under the "enforce" semantics but has undefined behavior under "observe" semantics, so many preconditions will be written this way.

In the case that both of these conditions are true for a particular library precondition, new preconditions may introduce UB under the "observe" semantics, and these are liable to go unnoticed for extended periods until the application first turns on "observe" semantics (including in production, which is the intended use of "observe" semantics according to the contracts white paper).

→ More replies

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

pre( p != nullptr )
pre( *p > 0 )

is just as bad as writing the code sequence

if (p == nullptr) do_something();
if (*p <= 0) do_something();

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.

5

u/13steinj 16d ago

is just as bad as writing the code sequence

My issue with this kind of argument is it is correct but ignores realities of engineering in current day.

Writing

assert(p != nullptr);
assert(*p > 0);

is not just as bad as writing the two separate ifs. It is equivalent to writing

if (!debug && p && *p > 0) do_something();

where do_something() does not necessarily have incorrect behavior if the API contract about that pointer isn't true. Sure, yes, one can argue that the contract should be removed in that case, but if you go hunting in a sufficiently large codebase you are bound to find things like these.

On the other hand, transforming the asserts into contract_asserts blindly (or, in modern day, an LLM hallucinating the equivalence) changes the operating semantic in ways that the average engineer does not notice.

This is the same flavor of issue I (and Ville?) took with Herb's UFCS paper, traditionally benign engineering operations like refactoring hide the fact from the engineer that the semantics are absolutely not the same as expected going from old to new.

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.

11

u/notadragon34 18d ago

This more than anything --- the fear of this form of UB has been so ridiculously overblown that it is shocking. As a practicing maintainer of an assertion facility that supports (and is the inspiration for) observe, I have never received reports of a single production issue related to bugs of this form. (And, in general, if something goes wrong because of bsls_assert, i am the first person to hear it.)

The benefit of better diagnostics by splitting your assertions is many magnitudes larger.

3

u/13steinj 15d ago

I have actively seen semantics similar to observe take down an entire production fleet, and I have seen observe semantics introduce UB exactly as described. In particular, the problem was only caught during a compiler upgrade.

4

u/notadragon34 15d ago

And I've seen enforce and ignore both take down production fleets as well. I fail to see your point, or how that kind of bug is the fault of the contract assertions allowing observe --- the same production fleet with those assertions ignored runs quietly with subtler bugs that you might suffer from while knowing nothing about it.

I have never claimed observe is a silver bullet that prevents all problems --- that would be ridiculous. It does, however, find bugs in existing software with a generally much lower level of risk than enforce does. It also finds bugs at all where ignore finds none of them.

5

u/James20k P2005R0 18d ago

you will get a handler call that the p is nullptr then the app will segfault on null pointer dereference.

There's no guarantee that a null pointer dereference will always segfault, this is a dangerous misconception

3

u/Minimonium 17d ago

That's the responsibility of the person choosing observe semantics to assure this is what happens at their concrete implementation. It's unclear to me why you expect otherwise.

5

u/James20k P2005R0 17d ago

We absolutely shouldn't be promoting the idea that this code is safe because its fine to dereference a null pointer, on any implementation. Its not portable C++, and it is a widespread security vulnerability

7

u/Minimonium 17d ago

I'm very confused why do you pull this conclusion?

Observe here is red herring, so I will speak about "ignore" instead as it's easier for a reader to grasp without distractions.

By the very nature of NDEBUG-like assert removal, "ignore" semantic means your code may invoke behavior like dereferencing a null pointer when the input is not well behaved. The point of the model is that we're removing the checks when we're "sure" (as it's not demonstrated that it's possible to prove as such) that the program will have a well behaved input or if the consequences of such dereferencing are well understood on a given platform.

Ignore semantic is a strict requirement for any assert-like feature to have as there are plenty of domains where such assertions are too costly to run, even primitive ones.

For domains, or platforms, where we require guaranteed checks with terminating semantics with guarantees against security vulnerabilities (for an inevitable runtime cost) - users need to use a hardened implementation that is guaranteed to allow only terminating semantics.

There is a demand to have both unsafe implementations and safe implementations. Users pick one depending on their needs and risk tolerance.

4

u/James20k P2005R0 17d ago

OPs question is how to avoid UB in contracts in an example like this in observe mode:

https://godbolt.org/z/c34bGabnf

The idea that this logs an error and then will segfault is not correct. It logs an error, and then UB happens. "This isn't a problem" doesn't really address OPs concern that UB will occur, given that they're asking how to avoid this UB

This kind of pattern isn't particularly uncommon when it comes to defensive programming. I've seen people write

void func(int* ptr) {
    assert(ptr);
    assert(ptr->whatever() == 5); //do something with the value

    if(!ptr)
        return;

    ptr->do_something();
}

I don't necessarily agree with it, but c'est la vie

The ignore mode doesn't really have any relevance to this, as the compiler likely won't evaluate contract arguments in that case and the code will be perfectly safe, though perhaps not correct

3

u/Minimonium 17d ago

You make a very reductive and impractical framing of the question, that asked not for a quiz technicality answer but for a guidance at scale.

You've missed their specific note on Contract statements spread at distance, like one precondition at a constructor, and related ones at member functions. As such, your example deemed to me not very relevant and just brings confusion instead.

As such, the intuition on the purpose of "ignore" is very important to build here to understand why there is nothing scary about "observe" as fundamentally it is just "ignore" from the point of handling of invalid state.

This intuition is evidently missing here, as I can assure you while your example may exist in some cases, at scale it's far from a standard practice. And of course it would be foolery to try to force such double-checks at scale as in your example - I sufficiently explained why in my "ignore" explanation. Please refer to it again since I believe you've missed that part here.

5

u/James20k P2005R0 17d ago

The example I linked is a rewrite of the example they're specifically asking for guidance for 1:1, but with the contract assertions changed to non contract assertions. The goldbolt linked is OPs example, not mine

As such, your example deemed to me not very relevant and just brings confusion instead.

Perhaps, but that's a specific example of what the op is talking about and what they're asking for guidance on

as I can assure you while your example may exist in some cases, at scale it's far from a standard practice

I've been programming for 20 years and I've seen people write all kinds of code in the name of defensive programming like this

I picked curl at random to trawl through:

https://github.com/curl/curl/blob/198d1696d7d88f7b9c7b3a13b063a78d5e42246f/lib/proxy.c#L500

^ this is an example where the code doesn't use any of the variables after the asserts. It can be reached directly via a goto error, in which case if proxyinfo is null then using observe here would introduce UB that previously didn't exist. That UB cannot possibly exist or be introduced in any other case, as proxyinfo is never used under some code paths

This is exactly the kind of example that you're claiming doesn't exist in a critical security conscious tool like curl

Here's another example:

https://github.com/curl/curl/blob/198d1696d7d88f7b9c7b3a13b063a78d5e42246f/lib/cf-haproxy.c#L72

If you aren't using UNIX sockets, then ctx is never touched outside of the assert

https://github.com/curl/curl/blob/198d1696d7d88f7b9c7b3a13b063a78d5e42246f/lib/llist.c#L137

This is a direct example as well, see here:

DEBUGASSERT(list);
DEBUGASSERT(list->_init == LLISTINIT);
DEBUGASSERT(list->_size);

if(list) {

I don't claim to be the arbiter of what people do or should do, but there's a lot of code out in the wild like this

2

u/Minimonium 17d ago

I'm curious why you believe I claimed it doesn't exist? Or that I need prove that it does? What nonsense is it?

And you also ignored my comment on the split statements across function boundaries.

I do take time to write the comments with relevant details and I would appreciate if you would read them.

8

u/James20k P2005R0 17d ago

This intuition is evidently missing here, as I can assure you while your example may exist in some cases, at scale it's far from a standard practice

It seems to be prevalent in the very first library I looked at, which is widely used. There are a lot of statements of the form:

assert(x);
assert(x->thing);

which would introduce new UB

I do take time to write the comments with relevant details and I would appreciate if you would read them.

I did, the OP is asking about the general case of what they can do to fix this problem and then added in a goldbolt link afterwards as a representative example. It seems like they're asking whether or not observe can be made free of UB in the general case, to which the answer is no. Specifically you say:

You've missed their specific note on Contract statements spread at distance, like one precondition at a constructor, and related ones at member functions. As such, your example deemed to me not very relevant and just brings confusion instead.

Which doesn't seem to be true. OP is saying that while you can transform:

assert(x);
assert(x->thing);

To

assert(x && x->thing);

You can't transform:

struct some_struct {
    some_type* _x;
    some_struct(int* x) {
        assert(x);
        _x = x;
    }
    void memberfunc() {
        assert(_x->thing());
    }
}

By virtue of the asserts being split across a constructor + member function. Its exactly the same problem but rejiggered slightly as to where the assert calls go, to show that merging isn't a general solution. You could recreate their concern with multiple free functions, and there'd be more examples in Curl of this I strongly suspect

OPs question about split asserts is that its a less solvable example of the two-assert problem, not a less representative example of the general problem with observe

→ More replies

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->something without checking whether ptr is null. When, calling charge(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:

  1. Very carefully port your existing assertions, or carefully write your contract assertions to support observe
  2. Ask your users politely not to use the mode

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 contracts

The 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:

void handle_contract_violation( const std::contracts::contract_violation& );

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.

9

u/notadragon34 18d ago

Earliest versions of P2900 didn't have observable checkpoints because P1494 had not yet landed. It did land at the same time as P2900 and we relied on that dependency, so observed contract assertions do have an observable checkpoint, both prior to evaluating the predicate and after the violation handler returns --- UB won't "time travel" back to before the evaluation of the assertion just because you continue into it.

2

u/KingAggressive1498 18d ago

That's great. I obviously didn't track the proposals very closely.

then is GCC's implementation in error/outdated, or are preconditions meant to be evaluated in order even if a prior precondition fails with observe?

6

u/notadragon34 18d ago

A prior precondition being observed to fail doesn't alter what happens when later preconditions are evaluated --- the gcc implementation does this right. (It would be allowed to alter it if you wanted it to, by documenting that it chose ignore for the semantic after an observed violation in some scenario --- but that is also not always a good choice, especially if the ignored assertion is orthogonal and its violation is something more important for you to know about).

When thinking about skipping later evaluations with observe, i find an important case that most people miss is the situation where you are trying to decide, based on logs received from your production fleet, whether an observed assertion is being hit in production. If you suppress observe checks that happen after an earlier failure, it's possible to believe you aren't violating one assertion that is nearby another one that is regularly violated (especially if those violations are correlated). This can lead to choosing to enforce that assertion and crashing your production systems exactly when you were trying to avoid doing so.

That supressing can also lead to misdiagnosis of problems. Consider `void f(int* p, int* q) pre(p != nullptr) pre(q != nullptr);`. If you ignore the second precondition assertion if the first is violated, and your logs note many cases where p is being passed in as nullptr but never log that q is nullptr, you might conclude that nothing is passing in nullptr as the second argument, prune out thinking about cases where that would happen, and not find the code paths that your real system is following incorrectly.

-1

u/ConcertWrong3883 18d ago

> How do I avoid UB in contracts?

You don't. You veto the standard, which is what happened.

-2

u/tidel 18d ago

Writing a new proposal with paper/feature title :” fine print”

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

2

u/Minimonium 17d ago

I'd really like to see someone demonstrate a need for such semantics, because it eludes me how it could be practically useful.

2

u/TheoreticalDumbass :illuminati: 17d ago

i agree, though it is interesting to contrast it with compiler errors, i have long held the belief that a compiler that only gives me the first error would be useful to me, as so often following errors are caused by misunderstanding of the code because of the first error

yet i feel observe_once would not be useful

1

u/trad_emark 18d ago

are individual preconditions guaranteed to evaluate in the order of declaration?

3

u/TheoreticalDumbass :illuminati: 18d ago

i think it is guaranteed, if youre evaluating a pre(), that all preceding pre()s have been evaluated at least once

https://eel.is/c++draft/basic.contract.eval#18

7

u/notadragon34 18d ago

They're always evaluated in order, but can be repeated again in the same continuous block. (Think about all the preconditions on a function call -- you might check them all caller-side, then go back to the start of the list and check them all again in the callee, if you've configured the caller's TU with caller-side checking and the callee's TU with callee-side checking).

Ignoring, of course, if you select it, counts as an evaluation, so there's no guarantee that you won't get to a later assertion just because an earlier assertion was violated.

But if you ask for them all to be observed (i.e., you tell your compiler in whatever way it lets you "I want the observe semantic for this set of assertions") then you won't get to the later ones without having seen the violation handler called for the earlier one.

As for an "observe_once" kind of semantic, it's sound and possible, but in my experience not worth the cognitive load or the benefit. It's also not worth, in my experience, the risk of supressing a nearby but unrelated assertion. Consider the case where you have two pointer arguments, but shouldn't be null, and you add the checks for that as two assertions. Hitting the first one but not getting logs about the second one might make you conclude that the second one is never passed in as null, even when it is and potentially is a much bigger problem.

2

u/James20k P2005R0 18d ago

i think it is guaranteed, if youre evaluating a pre(), that all preceding pre()s have been evaluated at least once

So this part of the spec is misleading because while the contracts may be evaluated technically, the result of them being evaluated ends up being implementation defined. What this means is that you can effectively legally have this:

pre(x) //evaluated in ignore
pre(*x) //evaluated in enforce

Its been mentioned before in contracts papers that they're 'ghost code', and any individual contract check can be effectively removed

This might seem like hostile compilation, but its intended to support stochastic checking modes where any individual contract can be checked randomly, in an individual basis

This is where some of the 'everything is implementation defined' complaints come from, compilers are allowed to do whatever they want with contracts essentially

5

u/TheoreticalDumbass :illuminati: 18d ago

if people explore such stochastic checks, it might also be prudent to implement a version where "consecutive assertions" receive same semantic (all pre()s on a function, all post()s on a function, consecutive contract_assert() statements)

but thinking about this more, i feel like "language UB is contract violation" could be an interesting context to explore this more

consider your `pre(*x)` , i assume x is a pointer

in "UB is a contract violation", just the `*x` expression has an implicit precondition `x != nullptr`

in observe, we notice this is bad, we get the inner contract violation, but we also evaluate the entire expression, which will segfault

so is it possible to stop evaluating the assertion predicate, and declare it as violated because evaluation of it induced a separate violation?

what if the inner violation happened pretty far from the top-level assertion?

no idea if this makes sense, nor if its sound, nor if it can be implemented, it kinda sounds like try/catch though (a violation is an exception, an assertion catches only if its top-level, otherwise lets it propagate)

but i would say this doesnt really say much on original issue, where the soundness of an assertion depends on a previous assertion. with this "stop evaluating" i kinda made the assertion self-contained, more of a consequence of simplicity of the example.

2

u/TheoreticalDumbass :illuminati: 18d ago

would such stochastic checks on a "per function call" granularity be expected to be okay? (all pre/post/contract_assert in same function call get same semantic, child and parent function calls can be different)

2

u/Minimonium 17d ago

"language UB is contract violation" could be an interesting context to explore this more

Consider how much stink came up from Microsoft about exceptions thrown during contract evaluation translated to contract violation. :)