News for hackers. Stuff that matters.
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by jononor on Friday April 21, 2017 @05:16AM (#14164093)
We need a -Wundefined-behavior, which can be used in combination with -Werror. It is a practically impossible job to be so aware of the standard while working to get this right without assistance.
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by masklinn on Friday April 21, 2017 @05:37AM (#14164161)
> We need a -Wundefined-behavior, which can be used in combination with -Werror.

The problem is that you probably won't be able to use any optimising compiler if you do that. As a result of a bunch of optimisation (mainly inlining) the compiler "uncovers" lots of UBs which it can use to pare down the code, that's why inlining is one of the most important intermediate/early optimisation.

Here's an old example by mikeash:

    int ComputeStuff(int *value) {
        if(value == NULL) {
            long and complex computation for a NULL value
            return result
        } else {
            long and complex computation using the data pointed to by value
            return result
        }
    }

    void DoStuff(int *value) {
        int pointedTo = *value; // value *must* be non-NULL
        // do some work with pointedTo
        int computedResult = ComputeStuff(value);
        // do some more work with whatever
    }
Here the compiler can inline ComputeStuff, at which point it can rely on UB to assert that half the inlined code is dead and can remove it. What would it even do on "-Werror -Wundefined-behavior", fault on the original DoStuff? On the inlined one? On both?

Would -Wundefined-behaviour forbid assuming a pointer is non-null ever, requiring (and outputting) a check before each use of a pointer in a given scope/lifetime?

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by Asooka on Friday April 21, 2017 @07:29AM (#14164582)
> Would -Wundefined-behaviour forbid assuming a pointer is non-null ever, requiring (and outputting) a check before each use of a pointer in a given scope/lifetime

Either emit the if, or throw an error that the code is internally inconsistent. I mean, it IS inconsistent - first it dereferences the pointer, then it checks if it's NULL or not! This is pretty much obviously an error! I'd much rather add a bunch of assert(value != NULL); to my code to signal to the compiler that yes, this pointer is really not NULL within this scope, than have to deal with the current UB-hell.

Another acceptable alternative would be to rewrite the if(value == NULL) branch to call terminate() since if we get there, then the program has executed UB and cannot continue. Since UB is rare, we can even arrange things such that the branch doesn't slow down the CPU in the general case.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by zAy0LfpBZLC8mAC on Friday April 21, 2017 @02:12PM (#14167864)
> This is pretty much obviously an error!

No, in most cases that's the result of defensive programming and macros or inlining, where there is a perfectly useful sanity check in some inlined function, but the compiler can see that in some specific context where it was inlined, the check is actually redundant, and thus removes it.

> Since UB is rare, we can even arrange things such that the branch doesn't slow down the CPU in the general case.

It's an additional instruction, so it always has the potential to slow the code down, if only because it makes the code bigger than the cache. Also, it's usually not one such branch, but lots and lots of them throughout the program. That's why the optimizer tries to eliminate them.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by jononor on Friday April 21, 2017 @06:14AM (#14164288)
For such inlining optimization it is the compiler that 'introduces' the UB in its intermediate step. That is not a fault of the input code, so no warning should be emitted?

If the compiler can know that the pointer is non-null, why would it need to rely on UB to optimize it? Problem I guess is the ever-present possibility of pointer aliasing and such nearly allowing anything to change anything else at any time... Not easy making things more sound on such a foundation.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by derf_ on Friday April 21, 2017 @07:08AM (#14164499)
If the compiler can know that the pointer is non-null, why would it need to rely on UB to optimize it?

You've got this backwards. The compilers "knows" the pointer is non-null because you dereferenced it, and dereferencing null would have been undefined behavior. That's what allows the compiler to assume that didn't happen.

There are many operations which will produce undefined behavior for some inputs (e.g., every pointer dereference, every signed integer arithmetic operation). Figuring out if it is possible for a program to encounter such inputs at runtime is equivalent to the halting problem.

This is why any attempt to craft a -Wundefined-behavior that works on non-trivial programs is doomed to failure. It may be possible to prove a program will definitely invoke undefined behavior in some useful subset of cases. Compilers already do this in some of them, even. But those cases (and many more, besides) would also be caught with ubsan and a unit test.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by jononor on Friday April 21, 2017 @07:41AM (#14164629)
You're right, it is an intractable problem in general. I guess just use Rust if one cares about this..
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by masklinn on Friday April 21, 2017 @07:29AM (#14164583)
> For such inlining optimization it is the compiler that 'introduces' the UB in its intermediate step.

Technically the UB is in the original code, it's the dereferencing of a pointer without checking it. The compiler can merely use that to assert dead code (checking for a null pointer after having already deref'd the pointer is nonsensical) and optimise it away.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by jononor on Friday April 21, 2017 @07:47AM (#14164650)
I don't support this unsafe compiler behavior. There should be a check on the pointer in sight, or a manual declaration that "this is safe, trust me". Otherwise, emit a UB warning...
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by adrianN on Friday April 21, 2017 @09:20AM (#14165283)
Then you want to use a different language. Java for example throws NullPointerException instead of having UB for null pointer accesses.
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by benibela on Friday April 21, 2017 @01:25PM (#14167473)
Object Pascal just calls the function with this == null (well self = nil)
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by adrianN on Friday April 21, 2017 @01:45PM (#14167636)
ON ERROR RESUME NEXT
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by Manishearth on Friday April 21, 2017 @04:24PM (#14169116)
The presence of UB is not statically detectable. Global analysis may help, but it's probably reducible to the halting problem. (of course, you can detect some common mistakes, which is what many analysis tools do)

UB is not a property of the local code. It's a property of the code and the values you feed to it. Without explicit annotations of contracts you won't be able to statically detect this for C/C++.

At runtime UBSan exists to detect this.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by kbenson on Friday April 21, 2017 @08:48PM (#14170541)
This isn't about statically detecting undefined behavior in general, it's about using detected undefined behavior to make assumptions that don't play well with later stages in the optimization pipeline.

Deciding that a statement must be true because otherwise it would contain undefined behavior (which is assuming the developer won't cause undefined behavior), and then using it's truthiness to elide the check the developer included to attempt to make sure they weren't causing undefined behavior is some contorted reasoning that I'm confident isn't something that compiler authors decided specifically should be included, but instead is an unfortunate interaction between two separate aspects of compilation.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by Manishearth on Saturday April 22, 2017 @04:16PM (#14174509)
I don't think it's that clear cut. It's not "an unfortunate interaction between two separate aspects of compilation", it's how it's supposed to work -- the optimizer gathers invariants about the control flow and then makes optimizations based on it. The problem here is that the intent of the code is not something the optimizer can pick up on. Regular bounds check elimination works pretty much exactly the same way.
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by kbenson on Saturday April 22, 2017 @05:14PM (#14174849)
There is a difference between whether something is an invariant based entirely on mathematical properties and rules that the compiler ensures, and one that also includes expected programmer behavior.

In this case, the optimizer made an assumption that required the programmer to have ensured than an addition could not overflow, otherwise it would be undefined behavior. The compiler assuming that holds as true when it isn't necessarily so (and in this case was not so), is a problem. Optimizations that assume a programmer was diligent enough to follow those rules should not be attempted, period, if they result in the removal of some code (or possibly ever, just to be safe).

That's not to say those optimization are forever lost to us. It just requires the programmer be more careful about the actions they take such that no assumptions need be made. For example, if you are adding two types which could cause an overflow, and overflows are undefined, you can cast and use larger types, or rely on compiler knowledge. Examples of that might be casting in the comparison or casting to larger types earlier on and not modifying it prior to comparison, in which case a sufficiently smart compiler might infer that since it was an unsigned char originally and you haven't modified it since you casted it to an unsigned int, while its type is actually an unsigned int, for comparisons of overflow detection for optimization you can treat it as an unsigned char.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by Manishearth on Saturday April 22, 2017 @08:56PM (#14175808)
I still don't think it's that clear cut, most optimizations are based on these assumptions, it's just that some assumptions are more reasonable than others. A lot of compilers do this to some extent already, avoiding using certain kinds of information for optimization even if they could.
Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by kbenson on Saturday April 22, 2017 @11:33PM (#14176327)
Sure, I'm specifically talking about assumptions that rest on programmers having followed some constraint purposefully. Humans are fallible, and if the compiler can't actually prove it, it shouldn't be taking any action that might remove statements.

That's not to say programmers can't take steps to make it provable for the compiler.

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by Manishearth on Sunday April 23, 2017 @12:46AM (#14176556)
Right, my point is that most of the assumptions made are like that. Some are more obvious than others.

Yes, this could help construct a "warn on assumption made" mode, but you'd likely be inundiated with a lot of mundane assumptions as well. You could filter by kind of assumption, but scary-ub-triggering assumptions like the one in the post happen all the time too, and they usually depend on the runtime properties of the program, which are hard to statically figure out. Basically, this is a very nontrivial problem, and quite likely intractable to solve in a way that doesn't produce a deluge of unnecessary info.

(In the presence of annotations to help the compiler -- like the ISOC++ core guidelines -- the problem becomes significantly easier because you have local information on the runtime properties)

Re:Cap'n'Proto remote vuln: pointer overflow check optimized... by kbenson on Monday April 24, 2017 @02:55PM (#14186957)
> Right, my point is that most of the assumptions made are like that. Some are more obvious than others.

My argument is that any optimization that requires the compiler to infer intent rather than make concrete decisions based on known facts and this results in a change in the output of the program, then that is an optimization that is irresponsible to apply. The only part hard to know about this is how it affects execution, as the rest is already done currently. If that's too hard to determine, the correct stance is to disallow the optimization in that instance.

It is not irresponsible to have undefined behavior that the programmer can leverage.

It is not irresponsible to optimize out instructions that do not affect the result.

It is irresponsible to allow undefined behavior, and then change the output based on how that undefined behavior is interpreted but only if a specific optimization is applied. Optimizations should never change deterministic output. Code that is non-deterministic purely because of undefined behavior needs to noted.

That people have gotten used to some speed improvements at the expense of consistency, but not necessarily to their knowledge, is no excuse not to fix it. In many cases the code could be changed to once again take advantage of the same optimizations which are more strict, or to avoid undefined behavior. In this case, that would mean either casting to a type with defined overflow prior to addition or using a large data type to accumulate the values and test if it's too large. Neither of those allows the optimization, because that optimization is actually wrong in this case. In the cases where the optimization would be correct, correct use of types and casting should yield the same result.

I would love to see a specific counter-example where this would be unworkable. I do not consider code having to be changed from what was previously a possible undefined behavior to definitively not undefined behavior as unworkable. I don't see how C could be considered a systems language without this. I understand how this is an unpopular stance with C programmers, but without it, there's actually a bunch of non-deterministic source code in the wile that's an allowed compiler tweak away from changing how it functions, not just what instructions it uses to achieve that function.