40 points · by mpweiher · 9y ago · 62 comments
Let me just say: DON'T do that, ever. Uninitialized memory is rarely random. If you're lucky, it's quasi-constant because your own program always writes something else to it before. Worst case an attacker manages to write something to that memory before you read it, thereby controlling part of your seed. The cited article also recommends to "In short, just don’t use uninitialized memory for more randomness."
Really, exploiting undefined behaviour in crypto code is a bad idea, and you should make sure you compile with flags that at least catch the most common cases, like the one mentioned in the post.
[10] http://kqueue.org/blog/2012/06/25/more-randomness-or-less/
The problem is, you can't always know if (for example) you're reading from an uninitialized variable, unless you run the program with the possibly infinite number of valid inputs, thereby also solving p != np.
In my opinion, undefined behavior is what we have and we had enough time to learn how to deal with it. If at all possible, compilers should be able to detect UB, so I can use compile flags to make UB an error. Changing the language to "define" undefined behavior, might turn it into unexpected behavior and I wouldn't like that. At least we've learned the lesson with newer languages.
The thing is, we already knew that from older languages as well. C's UB is a consequence of the people involved in ANSI C89 not wanting to fully define the language, like the other languages were doing.
I think the lesson is that "Performance trumps correctness" is the wrong path to follow, specially since not everyone using C is a 10x coder that always makes use of best practices.
Then why not just write it like that? This is like deliberately shooting yourself in the foot and complaining that your shotgun works.
BTW if my example is actually valid, then that rule of reading uninitialized object being UB is some of the hugest shit, because depending of the type maybe reading an uninitialized byte will be UB, or maybe not, depending of how that byte was in a field of a type or just alignement... In practice, this is even more crazy, because it also depends on which parts of the code your compiler have seen, and it capabilities to break^W understand it, so you might as well considered it has a layer of non-determinism above all that.
C/C++ has become too dangerous. Use something safe instead.
This is the reason why padding for wire formats has to be made explicit and be explicitly initialized, otherwise the compiler is free to generate code packing bible quotes into the padding.
Ok so like I said: "depending of the [effective] type maybe reading an uninitialized byte will be UB, or maybe not, depending of how that byte was in a field of a type or just alignement... "
If I understand correctly this is so insane (to treat those that are UB in that context as effectively UB) that I still have no word.
I absolutely do not want to use a compiler made by people who consider that that situation is OK or even just tolerable for potential gains, regardless of the speedup you could obtain (even at 1000%, I just don't want it -- the risks are way too high)
EDIT: I reread and I think I misunderstood. This is not as bad as I thought, but this is extremely complex and I guess compiler bugs will happen (or have already?) in this area. [ Also what is the relationship with extensions? (like pre-standard or even standard explicit extra alignments...) ]
Also, the article goes on to argue that uninitialized memory is used to seed random generators, which is generally undefined behavior. I don't think this should be a valid use-case.
I think it's safe to say that x ^= x is equivalent to x = 0 and optimize it that way, just like compilers recognize common idioms for e.g. swapping, counting set bits, etc and emit the correct intrinsic instructions.
So why make reads of uninitialized values undefined at all? Consider code like this:
uint64_t x; // Will be initialized later
/* ... */
if(check_some_condition(y, z)) x = (uint8_t) f(b,d);
/* ... */
if(check_some_other_condition(foo)) x = (uint8_t) bar;
/* ... */
x &= 0xf;
/* ... */
if(x & 0x800) do_stuff();
Now the compiler has no way of knowing whether x will be initialized or not. But if it has been initialized, then it's value must be in 0..255, so the & 0xf can be limited to the lowest byte. But this means that the test for x & 0x800 will always be false, and stuff will never be done, so the compiler can optimize it out, reducing code size and thus cache pressure.If these assumptions don't hold, then some later code may get passed a value for x that has the bit in 0x800 set, and expect do_stuff() to have initialized some data structure, which didn't happen, and the code blows up. But the compiler was just working from what it knew, and under the assumption that the programmer wouldn't depend on completely arbitrary values that happened to be in memory, everything it did was perfectly sensible.
Why should it do that? Just stop compiling and yell at the user, demanding proper code. I'd not let the code you gave as an example pass any review because it is not clear what the author intended.
If the code really does make no sense, then why not disallow it or capture it with a compiler warning?
Instead the optimizer is to silently remove the code.
Isn't it possible that the programmer knows something that the optimizer is unaware of?
You answered your own question:
> Isn't it possible that the programmer knows something that the optimizer is unaware of?
Here's a fun exercise. Find the best static analyzer you can. Run it on some substantial body of C code. Count all the false positives and false negatives (good luck).
Now you should have an idea as to why you can't simply require the compiler to reject the code and issue a diagnostic. But making code like this UB is about as close you can get to "disallowing it."
Alternatively you could try to eliminate the problem entirely by removing the whole concept of uninitialized memory and requiring that all variables are initialized to some value per default. Depending on which camp you're in, this is a step forward or a step back. Some people just see the words UB and think it is Satan, bad bad bad. For them this is a step forward.
But if all variables are supposed to have a definitive starting value, compilers & static analyzers suddenly can't warn you about the cases where it can tell you forgot to initialize something, because all of a sudden such code is totally legit. The analyzer can't tell whether you forgot to make an initialization or whether you're actually intentionally relying on the default value.
That's a big step back as far as I am concerned. You eliminate a problem because "UB is bad!" and create another problem we can't even issue warnings for, without potentially generating loads of false positives.
Now if one wanted to complain that his compiler detects an obvious case of UB and doesn't warn him about it, he should take it up with the compiler developers (or see if he can help himself by turning on the right flags). Alternatively one could invest in a good static analyzer. The standard committee can't really fix this problem without making substantial changes to the language. Instead I'm glad they allow relatively simplistic implementations that don't do deep advanced analysis.
It is quite a different beast, but C# produces compile time failures when attempting to read from a potentially uninitialised variable. What is it that makes C different?
Yet that argument is stupid if we are talking about compilers issuing warnings for the UB they "detect", because by definition they have detected them. It might not be possible when it does not work exactly like that in some cases, but at least before removing some code, this is desirable.
It might also not be easy given the current internal design of compilers, but then I argue those design should be changed, because it is just too dangerous.
That said, I feel like C often lacks the expressiveness to properly define intent and allow the compiler to optimise well.
C is not self-explanatory at all and without good knowledge of the standard anyone will write broken code that will fall apart sooner or later. C is not a simple language, nor one with simple semantics. Without knowledge of the standards it is essentially not possible to write portable C code.
https://stackoverflow.com/questions/11962457/why-is-using-an...
edit: i recognised that it does not count as the original example is about an array element...
This is a flippant statement. It could be argued C++ falls into this category, but others are so new that they just haven't had the time to grow into the communities that would benefit from them.
> C’s advantages have preserved it as an indispensable systems and applications programming language.
But what about the disadvantages? I love C, I will always have fond memories of using it to do mind-bending things, but given the choice of using safe languages vs. an unsafe one at this point in time is a mistake.
Where there is an option to use a safe language instead of C, that option should always be chosen. It could potentially save lives depending on where it's deployed; it will definitely save money in the long term with fewer bugs.
C is not the only low cost abstraction and peak performance language available out there anymore.
It never was, it just happened to become one thanks to UNIX's adoption by the enterprise market.
Back in the 80's it was just yet another systems programming language fighting for a spotlight, and any junior Assembly developer could write better code than C compilers for 8 and 16 bit systems.
Oh, the pleasure of using Turbo Basic, Turbo Pascal and Modula-2 and not having to deal with the unsafety issues of C.
EDIT: I found this proposal (http://www.cl.cam.ac.uk/~pes20/cerberus/n2091.html) which has some discussion about existing trap representations (including whether to consider signaling NaNs to be trap representations). The conclusion seems to be that segmented pointers on the Motorola 68k are the only place trap representations are truly necessary -- maybe it's time to just remove them.
School of thought of programmers in the C language family of systems programming languages, "Performance trumps Correctness".
At least the C++ camp, which has quite a few Algol family refugees, there is some effort to remove few UB from the standard, but not all of them.
In resume, pick your side and don't be surprised for what you get in return.
It's not disallowed by compilers, because they're deficient. In this case I'd guess compiler front-end doesn't track which values in an array are initialized, and when optimizing back-end sees UB it's too late to emit an error.
A bunch of UB is of course static, and often comes with compiler warnings. Some UB doesn't have compiler warnings, but is found by linters and analysers (such as clang static analyzer).
I tolally agree that this is a bad mentality for software developement in general, but at least it is the "authentic C way" so I feel that part of the critics ungrounded...
The standard even says: "undefined behavior: behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements"
However, today, you should act as if the nonportable part of this statement don't exist anymore, and act as if ALL UB are absolutely forbidden and result in the worst non-deterministic consequences, in all cases and regardless of your actual target. Meaning that today on e.g. x86, if you use a mainstream compiler, you ARE limited by some of the limitations of e.g. some obscure outdated DSPs.
And this is likely impossible to check in a non-trivial program.
So just use another language. C for serious purposes is dead. (some projects that started in that language continue to be developed in it, but given the security issues it creates, this will become unacceptable in a not too far future; so don't wait it is too late to switch: lead that movement.)