5 ms·
The Dangers of Super Smart Compilers
- nothrabannosir 11y agoHow does this not segfault on -O0 if the pointer is NULL?
- jzwinck 11y agoConceptually, dereferencing a pointer then taking the address of the result is a no-op, you get back what you put in. There's no requirement for dereferencing a null pointer to segfault, only an expectation of many modern commodity-system programmers. Some systems allow you to dereference NULL and just return a bunch of zeros there. It's allowed by C and C++. The real question is, how does anyone compile without "-Wall -Werror" in 2015? Ignoring your compiler when it tells you your code is wrong is negligence.
- Kristine1975 11y agoSome systems allow you to dereference NULL For example inside the Linux kernel. GCC has the special switch "-fno-delete-null-pointer-checks" that turns off the assumption that a dereferenced pointer is never null: https://homes.cs.washington.edu/~akcheung/papers/apsys12.html https://homes.cs.washington.edu/~akcheung/papers/apsys12.htm...
- gizmo686 11y agoMy understanding of the C standard is that is explicitly does not allow you to dereference NULL, even if you really want to know what is at memory address 0. Of course this behaviour is only undefined, so an implementation if free to let you do it if it wants to.
- Kristine1975 11y agoMinor nitpick: A NULL pointer need not point to memory address 0 (e.g. it could point to the highest possible address, or have a special "this is a NULL pointer" bit set). The C11 Standard does a little dance with "null pointer" and "null pointer constant" there, c.f. chapter 6.3.2.3: An integer constant expression with the value 0 [...] is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
- Deregibus 11y agoIt's not dereferencing NULL that causes the segfault, its the actual reading or writing of the memory at the invalid address. So, ignoring undefined behavior etc, "* ptr;" doesn't actually generate a load or store since its not really doing anything, but "x = * ptr;" or "* ptr = x;" would. You can also see similar behavior when calling a non-virtual member function on a NULL pointer, the crash doesn't occur until the function actually tries to access some data on "this". This is all with the caveat that the actual behavior depends on the system and compiler as many others have pointed out.
- deleted 11y ago[deleted]
- saurik 11y agoIn C++, dereferencing a pointer doesn't give you a value: it gives you a "reference". While a compiler is possibly allowed to do so, I would be shocked to the point of saying "this compiler doesn't work" at a compiler that actually went out of its way, even with optimizations turned off (as this isn't an optimization issue), to access the memory at the address of the pointer in any way if the reference was never actually used.
- dklsf 11y agoIt's not really surprising that invalid code doesn't go along with compiler optimizations. The correct way to deal with this here is probably either _NOT_ using nullptr, and instead using a special null object (similar to the end iterator); or using pointers instead of references (because you really want pointer behaviour). Their fix is insane, and not something I'd want in production code. Unless you carefully vet your code and compiler version, you should never rely on undefined behaviour. (There are some cases in the c standard that technically undefined but all compiler vendors have essentially agreed to handle in the same way; so those are fine. IIRC unions are a common example.)
- throwaway999888 11y agoThe author should just be glad that his code didn't launch any missiles.
- Kristine1975 11y agoJohn Regehr did a contest in 2012: Craziest Compiler Output due to Undefined Behavior: http://blog.regehr.org/archives/759 http://blog.regehr.org/archives/759 No launched missiles though.
- Kristine1975 11y agoIIRC unions are a common example. If you mean type punning: That is fine in C (chapter 6.5.2.3 of the C11 Standard even mentions "type punning" in footnote 95), but not in C++, where it's undefined behavior. I would just use memcpy. It works even when C code is compiled as C++, and modern compilers know what memcpy does and can optimize its call to a move operation: http://blog.regehr.org/archives/959 http://blog.regehr.org/archives/959
- barrkel 11y agoType punning is not fine in C99 - you need to use a correctly typed pointer or a char pointer.
- sklogic 11y agoIt was LLVM, not Clang. And it is a really great idea to treat UB as "it never happened". Just do not rely on UB and always use static analysis.
- Kristine1975 11y agoAnd turn on the Undefined Behavior Sanitizer (http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) with -fsanitize=undefined It would have caught this bug at run-time.
- pjmlp 11y agoIf it was that easy. CppCon 2015, Herb Sutter's talk about writing safe code in C++14, just check how many in the audience use such tools. https://www.youtube.com/watch?v=hEx5DNLWGgA&feature=youtu.be&t=2053 https://www.youtube.com/watch?v=hEx5DNLWGgA&feature=youtu.be... A tiny 1%, this on the conference of with many of the top C++ developers. Now imagine how little they get used on the typical enterprise environment, specially worse with C, that lacks many of the C++ added safety layers.
- barrkel 11y agoMost C and C++ programmers' mental models of the machine is different to the abstract machine in the respective specifications. [1] There's a genuine problem here of overly clever optimizers wilfully misreading code to produce fast, wrong code. But the compiler exists to map our ideas into code; it's a tool to help us, not catch us out in a lawyerly fashion. I will say that the article isn't a fantastic example, but at the same time it isn't too far off a more common idiom that is also UB as it is usually expressed - type punning. And type punning almost always works, except when it doesn't - http://blog.qt.io/blog/2011/06/10/type-punning-and-strict-aliasing/ http://blog.qt.io/blog/2011/06/10/type-punning-and-strict-al... [1] In particular, most programmers think pointers are simply numbers that represent memory addresses and that the chief distinguishing thing about null pointers is that accesses through them usually cause a memory page error owing to how the OS has mapped memory.
- buster 11y agoTo me, depending on undefined behavior sounds more like a bug and unclean code then a fault of the compiler. Just because C gives you the power to shoot yourself in the foot doesn't make it a compilers error if you do.
- lazyjones 11y agoThe various C abuses don't really merit further comments, but compilers could help avoid many similar issues by always printing warnings about undefined or unexpected behavior (when warnings are turned on at all), not only when the problem will actually manifest itself due to a high optimization level. This is (or was) probably due to high CPU cost of the required analysis steps.
- deleted 11y ago[deleted]
- twoodfin 11y agoThe problem, as I've heard it, is that all but the most trivial instances of statically detectable UB are only noticeable once optimizations have been performed (or simulated by an analyzer), and at that point they're indistinguishable from potential UB introduced by the optimizations themselves. The compiler does a bunch of inlining, constant propagation, other optimizing transformations... and it ends up with some code paths that statically represent UB. If the original code couldn't display UB (up to the user to get this right), and the transformations preserve the original code's defined behavior (as of course they should), then it's safe to exploit the fact that these paths are impossible for further optimization or dead code elimination. Reversing layers of optimization to decide "Is this UB something introduced by me or by the user?" is not something compilers are traditionally architected to do, nor can they typically perform the analysis necessary to determine if a UB code path from either source is guarded by some high level invariants. In such cases, warnings would be actively harmful, as they'd suggest unneeded corrections.
- Kristine1975 11y agoThis blog post (the third in a series about undefined behavior) talks about why compilers don't always warn on undefined behavior, even when they exploit it: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
- mikeash 11y agoThis function can invoke undefined behavior: int f(int x) { return x + 1; } So can this one: int get(struct Something *s) { return s->field; } Figuring out when undefined behavior needs a warning and when it's unnecessary because it's known by the programmer to be impossible is a Hard Problem. Especially since the compiler has no idea whether the programmer wrote f() knowing that they'll never pass in INT_MAX, or whether the programmer actually does expect to pass in INT_MAX and expects to receive INT_MIN as the result.
- fizixer 11y agoInteractive optimizers? Take whatever author wrote as "dialog and thinking" of the optimizer and turn it into prompts. There should be at least some (aggressive) optimizations which should require user's permission. And if the user gives permission once or twice (or whatever), then it happens automatically. And since we're talking about LLVM/Clang, the project that is supposed to take the compilation process to the "next level", why not.
- Too 11y agoHe doesn't mention which type of smart handle it is but shouldn't null in shared_ptr be compared after doing get(), or simply with the bool override?
- rsp1984 11y agoI really like The Hacks of Life and think it's one of the best blogs on the Internet, but this time they really got it wrong. The title should not be The Dangers of Super Smart Compilers but rather The Dangers of Engineers Trying to be Super Smart with C++. Yes that's right. Having operator== and operator!= overloads for stuff like pointers in your code means that you're either a 0.01% Super Engineer who 100% of the time knows what the f* he's doing and knows that it's actually necessary for the problem at hand (overall not so likely), or it means that your code is unnecessarily complicated and there's an easier and more elegant and more readable solution if you take a step back and re-factor some stuff (more likely, and yes sometimes it means taking a lot of steps back). But please when stuff goes wrong, don't blame the compiler first.
- crazy2be 11y agoWhat? These are overloads for smart pointers, not regular pointers, and thus require special code to get the semantics of regular pointers that are usually expected and desired by developers. Even the standard library unique_ptr overloads these operators (http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_cmp http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_...). Of course, you could argue that smart pointers shouldn't be a thing, but I think most C++ developers would disagree given the significant advantage of essentially automatic ownership management, at least for tree-like structures (cycles are more complicated, as always). What would you propose as a simpler solution? Many languages have GC, which is arguably the simpler solution you speak of, but would be unacceptable in C++, since the large majority of applications it is used for require predictable low-latency responses. Manually managing pointers is how you do things in C, but has it's own sets of problems, since it can't be checked in any way by the compiler, so things like forgetting to free, double free, use after free, etc, are common, while with smart pointers these errors are impossible.
- to3m 11y agoI claim this is all highly unhelpful. Both the C and C++ standards explicitly permit an implementation to do something sensible in the face of undefined behaviour, the sort of thing that a regular user of the system in question might expect. It's a bit unclear to me why compiler authors don't just do that. Undefined means exactly what it says, nothing more, but people seem to love this idea that it has to be some kind of here-be-dragons nightmare scenario. Mandatory reading: http://blog.metaobject.com/2014/04/cc-osmartass.html http://blog.metaobject.com/2014/04/cc-osmartass.html, http://robertoconcerto.blogspot.co.uk/2010/10/strict-aliasing.html http://robertoconcerto.blogspot.co.uk/2010/10/strict-aliasin...
- mikeash 11y agoDoing "something sensible" sounds good, but it's hard to actually do. You can point out the sensible approach to specific examples, but writing the optimizer to take a "sensible approach" in all cases is hard. For every example like this, where the programmer wants a NULL check to be done even when the value "can't be NULL," there's an opposite example where the programmer wants a NULL check to be elided because the value actually can't be NULL. Taking advantage of undefined behavior isn't done because compiler writers are sadists who enjoy writing perverse implementations which rely on the letter of the law. It's done because it allows the compiler to generate better, faster code. I think a lot of the trouble is that too many programmers learn C in a completely ad-hoc, informal fashion and never take the time to actually become familiar with the fundamentals of the language. People simply don't know how the language is specified, what operations are legal and what operations aren't, why there are illegal operations that the compiler won't (and can't) warn you about, etc. C is definitely a dangerous language and is a difficult language to use well. But that's all the more reason people who plan to use it need to ensure they understand it. More mandatory reading: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
- andrewflnr 11y ago> It's done because it allows the compiler to generate better, faster code. Why? Why is this OK? You say doing "something reasonable" is hard, but it obviously doesn't include entirely ignoring code I wrote. That's basically saying "I see you did something weird there, but going to assume the rest of your code and ask the libraries you link to are perfectly standard-compliant, which lets me generate faster code here. I'm so smart!" Default safe, not fast, wherever possible.
- tines 11y agoI don't know about you guys, but as a reader unfamiliar with their codebase, when I see return &*rhs == NULL; I think exactly what the optimizer thought: "Well, the address of an object can't ever be NULL, so this expression always evaluates to false." I don't think code that does this is "semi-legit"; it's completely counter-intuitive to abuse the expected semantics of unary `operator*` that way, even if the compiler did have no problem with it. You can't expect a new member of the team to read this and not have fire alarms go off in their head. As a side note, I also think that this optimization would be done by any compiler capable of basic pointer analysis. This isn't really GCC being out-of-the-ordinary "super-smart."
- Animats 11y agoRight. C++ does not allow null references. I've seen this before from the "I can use null references because I know what I'm doing." crowd. It's really a problem of C++, though, that it's possible to create null references. References were an afterthought in C++ (Strostup admits "this" should have been a reference) and it shows. The abstraction is leaky. Rust is stricter about references not being null, as in you get a compile time error if you try.
- makecheck 11y agoInvalid references are a GOOD thing. The problem is that the C++ language does not allow sane behavior for the common case of objects going away. The C++ language creates the impression that holding a reference is stable, when in fact it is still possible for a reference to point to bogus memory (same as a dangling pointer). The C++ reference starts out on the right track with some nice compile-time guarantees like required initialization but then messes everything up by being immutable. The memory can be deallocated, and people with references are screwed; they cannot possibly change their own state to reflect the fact that the object is now gone. And C++ has some inconsistent hacks, such as the fact that a "const" reference to a temporary object will prevent object deallocation until scope exit but this is not the case for other uses of references. Compare that behavior to something like Objective-C's "weak" properties, where ANY weak pointer to an object is set to 0 when the target object is destroyed. This guarantees that the property values will have one of two values: a pointer to valid memory, or "nil"; never a bogus pointer. In addition, Objective-C ignores messages sent to "nil". While clearly this can still create hurdles for debugging, it is fantastic for end users because the program itself is quite stable. The language created facilities for making invalid references hard, and mostly eliminated the penalty for screwing up.