110 points · by luu · 10y ago · 80 comments
What it can be is "nonconforming".
A correct program which hits that situation continues to have well-defined behavior (which we know from the text of the program and the standard). Just the implementation isn't handling the requirements correctly; it is not conforming.
An implementation is not bound by the standard in its own use of the standard library functions. The implementation can use a function like memcpy in ways that would be formally undefined if they occured in user code; its implementation of memcpy just has to harmonize with that use, so that the intended behavior is ensured. This is because implementations can add their own requirements to areas that the standard leaves undefined. For instance, an implementation can add the requirement to its memcpy that the copy may overlap, if the destination has a lower address. Then, the implementation can generate code which uses memcpy that way, or make internal uses of memcpy from other library functions which use it that way. It's just using its own (possibly not publicly documented) extension.
Yes. But right now they do not do that, and it's not their implementation of memcpy they rely on, and they are exactly doing the kind of things they disallow their users to do, so the whole picture is just plain insane. They just call libc memcpy in some cases, and their rational is that "it happens to work". Except nobody is actually sure about that, it might be already buggy on PPC, and the guarantee is not documented anywhere. Completely insane - especially given their very own approach in similar situations. As usual, they are prioritizing "optimizations" over correctness, and lets not even think about defense in depth. It's a brand new level of insanity, even beyond their usual "the standard allows us to do that" excuse, because here it does not even allow that, and it seems that neither do officially all the used implementations!
Software engineers must loose the habit of taking all kind of crazy risks that can only lead to marginally faster execution of newly introduced bugs. That does not serve any purpose.
Layer M's memcpy doesn't have to have the same semantics as the C standard's memcpy, but the bug report implies that it does.
Think of that part of the transformed code as still C for relevant purposes.
The specific cases are when it has a genuine guarantee provided by that implementation vendor that it is OK. In the case discussed on this bug, at least one implementation provides that guarantee (Darwin). The problem is that not all provide it, and further than other parts of LLVM have started assuming that the memcpy more closely matches C semantics. At least something will have to change here, but the C semantics are really relevant at all, or what is "valid C code".
Clang could be also used "freestanding". Then the user might be informed: please supply your own memcpy function with such and such characteristics, since generated code needs it.
If those characteristics are just those described in ISO C, but the compiler needs something more, then that's a problem between clang and the user.
The compiler is only part of the implementation. So is the standard library. So would be a processor. An implementation as a whole, perhaps, cannot be said to cause "undefined behavior", but I think it's correct to say it's parts certainly can.
If a preprocessor took valid C, and emitted valid C that could be fed into any other complete freestanding C implementation, would it not be accurate to say that this preprocessor introduced undefined behavior if it replaced, say, memmove(a, a, s) with memcpy(a, a, s) - sans any guarantees about which compiler it would have the emitted C fed into?
When it's LLVM IR invoking glibc's memcpy instead of a memmove, why is that not "causing undefined behavior"? Because it's not a C program? And if I misinvoke it via C++, is it only undefined behavior because the C++ standard references the C one? What if I use C# to invoke memcpy, which doesn't?
> An implementation is not bound by the standard in its own use of the standard library functions.
This is all well and true from a theoretical sense, but an implementation is bound to it's own standards as a means of achieving a conforming compiler, and in this case those standards are clearly documented to mirror the standard's standards. These standards are being violated, leading to possible future misbehavior when combined with other optimizations which may leave the code behaving in indeterminate ways - and, for that matter, current misbehavior in the form of triggered "false" positive valgrind checks.
> The implementation can use a function like memcpy in ways that would be formally undefined if they occured in user code; its implementation of memcpy just has to harmonize with that use, so that the intended behavior is ensured. This is because implementations can add their own requirements to areas that the standard leaves undefined. For instance, an implementation can add the requirement to its memcpy that the copy may overlap, if the destination has a lower address. Then, the implementation can generate code which uses memcpy that way, or make internal uses of memcpy from other library functions which use it that way. It's just using its own (possibly not publicly documented) extension.
It can do these things, if the implementation as a whole is coordinated in this way, but I would hope for sanity's sake it would not. And in this case the implementation as a whole has not been coordinated in this way.
Invoke copy_forward from memcpy if you like, where the former has fewer preconditions - but to write code that relies on an implementation's memcpy having fewer preconditions than the standard, even if you control the entire implementation, sounds untenable. Someone will forget that your memcpy has fewer preconditions, and write optimizations, debug checks, etc. which misassume additional preconditions that are outlined by the C++ standard. They will also also accidentally write code assuming fewer preconditions in another context where they're not guaranteed some specific implementation's relaxed preconditions.
[1]: https://mehrdad.afshari.me/pubs/compiler-validation-via-equi...
I believe that C should have safer semantics, plus standard-defined modes of operation which restore the unsafe semantics selectively.
The optimizer then must obey whichever semantics in effect (safer or less safe).
Then, in addition to telling your compiler you want a certain optimization level, you could tell it which standard-defined modes of operation you would like.
Currently, this is already de facto the case outside of the standard. For instance, users of GCC who want to do certain pointer aliasing without unpredictable behavior tell the compiler to be in a mode in which that is allowed (effectively an altered C dialect) using -fno-strict-aliasing.
This kind of thing should be a standard, portable feature. Look, everywhere in this program, I want nice left-to-right evaluation within all expressions and among initializers and function arguments. Except in super-fast.c; when compiling super-fast.c to super-fast.o, please do it in a mode where unspecified-evaluation-order semantics applies and optimize accordingly. (I might even want this on a more finer-grained scale than translation units.)
We need safety, and we need to sometimes throw away safe semantics in exchange for better speed (whereby we still ensure that the code we are writing is correct with regard to the weakened semantics; i.e. we promise to the compiler that even if it relaxes the evaluation order, or whatever, we know what we are doing and everything is cool).
It would be good to do this without compiler-specific guesswork.
Optimization control alone over a language with a single set of semantics (which is largely unsafe) is a bad way to achieve this.
There really seems to be a large disconnect between the tool writers and the users of said tools. I've had countless discussions with compiler writers where we've essentially talked passed each other. The compiler writer arguing from a legalistic (and dare I say moral perspective) that the programmer must not write undefined code, and myself from the perspective that developers do write undefined code and we should therefore find a way to handle it in a safe way. Perhaps even by standardizing more than we do currently.
In reflection its not unlike the drug legalization debate.
I don't see anyone being blasé about this. The issue comes down to something really simple:
- The compiler can emit substantially simpler code if it has a guarantee from the platform's implementation of memcpy.
- The compiler authors thought they had such a guarantee and so chose to leverage it.
Now, maybe they don't have that guarantee on all platforms. If that's the case, its flat out and simply a bug in the compiler. And you'll find folks on that bug arguing that it doesn't actually hold, which is good and important.
But it's actually quite reasonable to have a guarantee from a platform's libc that this will work and leverage that. The compiler isn't generating C code or code bound by any standard. This is about two parts of the implementation of C agreeing about what internal invariants will hold.
The problem this bug highlights (and it is a real problem, and not one anyone takes lightly) is that we have insufficient agreement about these invariants, both for certain platforms (glibc) and even within LLVM. Fixing this remains absolutely critical, but may only involve documenting the agreement.
I should have clarified that the comments I was referring to were on this bug: https://llvm.org/bugs/show_bug.cgi?id=11763
I was surprised to see: "I don't think it's really worth warning about, considering I don't know of any real-world implementation where it doesn't work."
That sounds a lot like someone knowingly writing UB in a C program because no compiler they know of breaks the intended behavior. I doubt any memcpy() has ever guaranteed in any kind of official way that overlapping regions are ok, even if it has historically worked in practice.
I mean I'm sure it'll get fixed now, I was just surprised to see this kind of reasoning coming from someone who I presumes works on the compiler.
btw. I'm pretty sure I heard that glibc broke this behavior sometime recently. There's a new memcpy() symbol in glibc these days with a different symbol version that no longer provides correct behavior in the case of overlapping memory regions. This is all second-hand from some other people I was working with, but if I got their meaning correctly I think this issue will actually have relatively widespread impact.
We (the Clang community members, and I suspect the GCC community members as well) have also worked to change language standards to provide guarantees relied on consistently and where the lack of guarantee has no reasonable basis. Also that comment is very old, and predates us learning about all of why this is probably something actually worth warning on. That discussion ended up in a different forum, and we do actually warn on stuff like self assignment.
Understand that it is often precisely the people working on a compiler that do deal with the cases of when we discover widespread UB in real code and whether or not the code is incorrect and must be changed or the standard is incorrect and must be fixed.
But all of that is about a warning, and not about the actual question of how the compiler and the system library interact.
Note that both Clang and GCC have at least some variants of this bug, and so I don't actually expect glibc to break this in the foreseeable future. But we're still actively working to defend against this on platforms for which we don't have a guarantee.
You are perhaps thinking of this: https://sourceware.org/bugzilla/show_bug.cgi?id=12518
I'm not sure if that change broke glibc memcpy for identical arguments or just ones that were different but overlapped.
This quote suggests that Drepper wouldn't have had any problem breaking things that passed identical arguments to memcpy:
>The existence of code written by people who should never have been allowed to touch a keyboard cannot be allowed to prevent a correct implementation.
- Programmers can and do emit substantially simpler code if they have a guarantee from the platform's implementation of <feature x>.
- Programmers think they have such a guarantee. (I don't know a single programmer around me who knows the complete list of undefined behavior, myself included)
- Compiler injects bug -- and LLVM/CLang seek excuse in the "technically not a bug" completely useless answer.
- Sane projects actually disable all that kind of crazyness (adding -fno-<everything> options every now and then) so all that kind of cute optims are useless in the real world (either dangerous, or completely disabled)
It's actually reasonable to have a platform that e.g. gives you 2's complement arithmetic or defines the result of shifts, or allows unaligned access, because mainstream computer hardware does provide those guarantee. And at least half of C programmers are not even aware those kind of stuff are technically forbidden, (historically often because of other architectures, some obscure, and not compiler optimizations, btw). More knowledgeable people who know about the spirit of the standard (1) can also be bitten by compiler revelation of bugs because compilers devs are doing literal and insane interpretation. Bug ensues, including security holes.
(1): Let me remind you about the definition of undefined behavior: "behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements" One keyword is nonportable and it is clearly not considered enough. So yes, there are numerous constructs that are reasonable to expect on a given architecture when we do not learn the compiler manual by heart, but some people don't give a fuck about the principle of least astonishment when they can gain 1% on a synthetic benchmark.
ARM, PPC, and x86 all define the results of some shifts differently (for shift amounts >32UL) and behave differently with unaligned pointers (only x86 tends to accept them). Which mainstream hardware are you using?
Adding magical nice semantics to your language is another way to hide bugs in your program. Try building with ubsan and doing runtime testing instead.
2) Compilers leveraging undefined behavior knowledge get a lot of hate for breaking this implicit contract defining what they "should" do as expected by programmers. Unfortunately these feelings are rather misguided, compilers are just doing what they can to produce the best code for you using the explicit contract that exists: the language specification(s). Are these specifications perfect? No, but they're what we have. If someone were to define a new language that actually captures the assumptions "real" programmers "expect" when they write code then compilers could choose to support it (and probably would!) and everyone would be happier. Until then this is a big case of "how come you're not doing that thing you never said you'd do and no one is willing to define properly?" which is a bit silly. Imagine you're a compiler developer: what assumptions CAN you make to satisfy everyone? In short, compiler developers aren't your enemy, they're just doing everything they can to produce the best code they can for you.
2a) Use of -f* is in a way used to define that a special variant of a language is desired, for example -fwrapv builds the code using an unnamed variant of C where signed integer overflow is well-defined.
[1] http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
I have suddenly lost a great deal of respect and confidence for LLVM/Clang after reading this bug thread; I value software reliability above all else, and being able to write reliable software without the compiler negating that effort. It seems I can no longer be assured this is even a priority of my compiler any more, with Clang. All the more reason to switch to Rust I suppose.
That the Clang people are trying to deflect this bug as "fine, no fix necessary" is kind of disgusting software engineering behavior. Compilers spontaneously introducing undefined behavior in another layer (to the point of causing codegen warnings from perfectly correct C code, is as clearly cut a BUG as any, independent of current API implementations outside of the ISO spec.
If you want to make undefined API calls the norm, then make a new API where the behavior you want is defined. Invoking undefined behavior of a decoupled library that users can swap out is flat out indefensible.
That they are reluctant to fix this makes me shy away from ever using Clang/LLVM, which is sad because before I had always held them with very high respect.
The folks working on other platforms seem universally unhappy with that bug.
Yet they do exactly the same thing, and pretty much casually. And I actually don't really blame them for doing it. Everybody makes mistakes. But I blame them for the double standard, the risks, and the attitude. The problem in the first place: engineering is also about mitigating the fact that mistakes will happen, often mitigating even the mistake of others, and the modern approach in regard with undefined behavior does not help and is even ultra-hurtful for that. I don't see how stability will emerge with that kind of thought process.
What does this statement mean and why is it not tautological?
>An rvalue t is swappable if and only if t is swappable with any rvalue of type T while(pStart <= pEnd)
swap(*pStart++, *pEnd--);
If swap doesn't work for a self swap, this code would break in the case of an odd length string.
It's an easy fix in this case, but being able to swap an element with itself is convenient.The std::swap thing is only one pitfall, the reliance on "our memcpy will do the right thing with any overlap" is a bit risky (and doesn't hold with LD_PRELOAD, but I think it may have been switched to using the LLVM based librt project anyway, that is I'm not sure these calls are supposed to become naked memcpy).
The official pronunciation is "klang" with a hard C: http://lists.llvm.org/pipermail/llvm-dev/2008-July/015629.ht...
Exactly like the metallic "clang" http://www.thefreedictionary.com/clang which originates from the latin clangere
http://eatmyrandom.blogspot.com/2010/03/mallocfree-intercept...
>#define malloc(a) debug_malloc(a, __FILE__, __LINE__)
>#define free(a) debug_free(a, __FILE__, __LINE__)
>.
>.
>.
Then in your debug_malloc() function you can track where every allocation took place. Not always applicable but nice when it works.* check it out, I used a man reference, am I a professional UNIX developer yet?
Llvm goal is performance over correction. stop.
If old code breaks, it is you played with fire, correct your code to eliminate these undefined behaviours. Stop.
We made wonderful coloured warning to help you. Full Stop.
Well on one hand I get the point, people played with fire. Code should be "correct" by standards that are emerging, but I can predict one thing : before the new "correctness pattern" that enables lots of awesome robust high performing code spreads, there will be chaos.
My first self interrogation is in how much time llvm team can build a completly correct stable compiler without any surprises? It it takes 2 decades, it will be a lot of chaos involved...
My second interrogation is can the code that "is incorrect" per LLVM standard be obtained without rewriting the source code (I guess not), and how much will it costs before all the code is being "corrected". Do we even have the man power to do it?
You see, some C code may be used everyday but are so complex hardly any developers even well paid like to look at them. (openssl, gnutls, libpng, zlib, dhcpd, bind...). And with platform specific ASM, we may discover that code has lost portability, and it may take a lot of time to discover that it is already happening.
Don't we risk another strike of bad news one day like discovering old software/libraries are behaving differently and need to be rewritten and that no one want to do the same effort as libressl especially since some software have a LOT of dependencies on C code (I do not think to loud of PHP or python, or Perl).
Of course there are unit test, but there are so much of them, some tests (like for python on freeBSD with curses) have been disabled, because "no one has the time to fix them". It is ofc a bad example in this precise case, but in the context, it feels like a growing ghettoisation between the CPU/OS/langage with lots of eyeballs/investments, and the old/poor market. Especially non company backed open source software. A smell of obsolescence by attrition of resource to report bugs/rewrite code.
As a normal former experimental physicist I can feel a transition coming, it smells of chaos and instability, and the question is always, how long, how smooth before the new equilibrium if ever we reach it, and what will break in the process? And well since transitions are transitions, we may reach a new equilibrium, but nothing guarantees it will be reversible, hence some stuff may disappear in the process forever.
I don't know why, but I guess the most vulnerable ecosystem to the changes to come is the non commercial open source.
I would fear more for proprietary systems. Open source is relatively innovative and adaptable.
We are kind of crowning the right to rule of the x86 computer industry. llvm is very tied to apple, maybe it can extend to ARM. But it means that some HW platform that may be to old may be difficult to maintain in the future (HPPA, Dec alpha, MIPS, PDP, zseries?).
And some computers have life cycle that are more than 10 years. (Expensive industry robots, telco switches, some medical devices, aeronautic/space CPU, radars, some very old mainframe used for accounting, embedded automation devices)...
Is this push to obsolescence really cool?
Okay critical system already handle the problem, but what about the stuff in the grey zone? Stuff that were not critical but get adopted nonetheless because they just worked and good be updated?
What applications? I don't think I have anything in my computer that's running on these "safer" languages (not considering C++ or Obj-C "safer").
(Also in a lot of cases you wouldn't necessarily notice. If you've played a few recent games you've likely run at least one written in C#. I've seen commercial drivers written in Python that you only notice if you look in the internals)