209 points · by philzook · 2y ago · 125 comments
int main(){
int x;
if (x <= 42){
assert(x != 12345);
}
}
is of course UB in C, even though under a "uninitialized is random" model the program is valid and does not assert (as the model checker concludes).(even in O1 clang gets rid of the whole function, including even the ret instruction, I'm surprised it does not at least leave an ud2 for an empty function to help debugging since it would not cost anything https://godbolt.org/z/eK8cz3EPe )
This isn't perfect, of course. In this case, the compiler can rightly treat x as uninitialized, meaning that its value could be <= 42 at one point, and not be <= 42 at another point. Since the uninitialized variable isn't "pinned", it could technically be different values in different locations.
CBMC's machine model works differently. In this case, x is assigned a non-deterministic value. The branch condition creates a refinement of this value within the scope of that statement. If the branch is taken, then by SMT rules, x can't equal 12345, because it was already refined as being <= 42.
On its own, a model checker can miss situations like these. It's why I recommend -Wall -Werror -Wpedantic in conjunction with CBMC. The compiler should catch this as a warning, and it should be upgraded as an error.
LLVM has a "freeze" command to stop propagation of undefined values (although I think that command was added later than the first version), so that the value is "pinned" as you say. However, the "undef" command, if you do not use "freeze", will not do this.
I think that the C compiler should "pin" such undefined values where they are used, but I don't know which compilers have an option to do this. (Perhaps CBMC should also have such a switch, so that you can use the same options that you will use with the C compiler.)
With this ex.3 file, the optimizer should be allowed to result in a function that does nothing and has an unspecified return value (which might or might not be the same each time it is executed). (If optimizations are disabled, then it should actually compile the conditional branch instruction.)
The reasoning about nondeterministic values should be spared for situations when it's other than undefined behavior. For instance, accessing an uninitialized structure member that came from malloc isn't undefined behavior. It's (I think) unspecified behavior. In an implementation that has trap representations for some types, it could hit a trap.
Practically speaking, -Wall -Werror should catch this. Any use of a tool like CBMC should be part of a defense in depth strategy for code safety.
It does in clang.
$ cc -Wall -Werror bar.c
bar.c:5:11: error: variable 'x' is uninitialized when used here [-Werror,-Wuninitialized]
if (x <= 42){
^
bar.c:4:12: note: initialize the variable 'x' to silence this warning
int x;
^
= 0
$ cc --version
clang version 16.0.6
It also does in gcc. $ gcc -Wall -Werror bar.c
bar.c: In function 'main':
bar.c:5:10: error: 'x' is used uninitialized [-Werror=uninitialized]
5 | if (x <= 42){
| ^
bar.c:4:11: note: 'x' was declared here
4 | int x;
| ^
cc1: all warnings being treated as errors
$ gcc --version
gcc 12.2.0use of the variable as an lvalue is not undefined
I don't think accepting the random initial value means that the value may continue to change until the first time you set a value.
Weird things happen to uninitialized variables during optimization. Basically, nothing can be assumed about the value, because using an uninitialized variable results in undefined behavior. The original un-optimized generated code may very well have some default value, maybe. Probably not. But, the optimizer can decide that this value is represented by register R0 here and R4 there, and since the variable is uninitialized, there's no point in doing a spill or a load. It really comes down to how the optimization passes were written.
So the checker treats them as defined, but with an unknown variable. You could have written this instead:
extern int unknown_int_value(void);
int x = unknown_int_value();
And leaving unknown_int_value undefined (so it's not visible to the analyzer). Or write a function and use x as a parameter.I suspect CBMC does this to have a convenient syntax for this frequent scenario. Apparently, it's used quite often, as in these examples: https://model-checking.github.io/cbmc-training/cbmc/overview...
It seems that CBMC is not intended to check production sources directly against C semantics, but to prove things about programs written in a C-like syntax.
Any invocation of undefined behavior should be considered an assertion failure as far as any model checker should be concerned. Compilers can--and will--treat undefined behavior as license to alter the semantics of your program without any constraint, and most instances of undefined behavior are clearly programmer error (there is no good reason to read uninitialized memory, for example).
Reading an uninitialized variable is not "subtle" undefined behavior. It's one of the most readily accessible examples not only of what undefined behavior can exist, but also the ways compilers will mutilate your code just because you did it. To be honest, if something as simple as the consequences of reading uninitialized memory are shaky understanding for someone trying to prove code correct, that will completely undermine any trust I have in the validity of your proofs.
Your operating system likely feels entitled to assume that if you never wrote to this page of RAM you don't care what exactly is in it. After all what kind of lunatic reads a bunch of unknown data, says "Yeah, that's coincidentally what I wanted" and just leaves it unmodified? No, almost anybody would write data they want to keep instead. So, if you never wrote to this particular page of RAM and your OS finds it convenient to swap that page for a different one, no harm no foul right? But now the contents of your uninitialized variable changed!
The C standard text is barely sufficient for the purposes of compilers, but wholly insufficient for what a model checker would need to know.
That's an assumption on your part.
One very good reason might be to ensure that memory really is there given the optimistic allocation schemes and to force a page to be read into core. You could also write to it to get the same effect. Another good reason to do a read on uninitialized memory is to see what's still there from the previous program that ran. Now arguably that's a nefarious reason but it is still a good one and it may help uncover bugs in the underlying system.
- UB sanitizer https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
- Cerberus Semantics https://www.cl.cam.ac.uk/~pes20/cerberus/
I gave a talk about Frama-C a few years ago. It's very interesting technology, but not too useful at any scale (http://oirase.annexia.org/tmp/2020-frama-c-tech-talk.mp4) One aim we had with Bounds Checking GCC back in '95 was to make it possible to use with real programs. Although it was quite slow, any open source program of the era could use it (https://www.doc.ic.ac.uk/~phjk/BoundsChecking.html).
CBMC works best with a contract-based programming style, where contracts are enforced by assertions and shadow functions exist to simplify model checking.
A single reply on HN is hardly a place where idiomatic styles can be expounded, but it is quite possible to build a resource-oriented idiomatic style that is reinforced with CBMC.
This led to the creation of function contracts and shadow functions. When evaluating functions, we actually want any calls that it makes to go to shadow functions instead of real functions. When we write a function, we include a contract that includes anything it may return, any side-effects it may have, and any memory it may touch / allocate / initialize. We then write a twin function -- its shadow function -- that technically follows the same contract in the most simplified terms, randomly choosing whether to succeed or fail. From CBMC's perspective, it's equivalent enough for model checking. But, it removes additional stack depth or recursion.
A good example of this would be a shadow function for the POSIX read function. Its contract should verify that the descriptor it is passed is valid. It should also assert that the memory region it is passed is bounded by the size it is given. The shadow function picks a non-deterministic state based on how it should set errno and how it should return. This state follows the POSIX standard, but the underlying system calls don't matter. Likewise, depending on the return code, it should initialize a number of bytes in the read buffer with non-deterministic values.
I used this shadow read function to find a buffer overflow in networking code and also to find a DOS infinite loop error in a tagged binary file format reader we were using.
CBMC isn't perfect, but when coupled with a good linter and -Wall / -Werror / -Wpedantic, it is a very useful layer in a defense in depth strategy for safer software.
Not that I'm an expert in processing what exactly is being tested, but it basically looks only able to prove that an individual function doesn't overrun buffers. If you tell it to assume that integer overflows can't happen (!). So I'm not impressed.
In hardware design, verification is done simultaneously with design, and semiconductor companies would be bankrupt if they did not verify the hell out of their designs before committing millions in manufacturing these chips.
Even among hobbyists this is getting traction with yosys.perhaps its time for programmers to adapt this kind of tooling so there will be less buggy software released...
int x;
if (x < 42) { assert (x != 12345); }
isn't to have a checker is clever enough to know that the assert will not go off, but to be informed that the automatic variable x is being accessed without being initialized!!!Intelligence is knowing that the assert will never go off.
Wisdom is knowing that it might.
extern int nondet (void);
int x = nondet();
if (x < 42) { assert (x != 12345); }When the variable definition and its use are together in the same basic block, it's immediately obvious that the variable has a next-use on entry into the block, and that its definition hasn't supplied it with a value.
From there it gets complicated. GCC has a history of emitting overly zealous diagnostics in this area, warning about possibly uninitialized variables that can be proven not to be.
The difficulty is equivalent to the halting problem:
void f()
{
int x;
if (invokes_undefined_behavior(f))
x = 'A';
putchar(x);
}No, it does not. It probably does constraint based verification or looks for "proofs" of possible error conditions or asserts. In the case shown, an uninitialized variable is trivial to prove that it could equal the asseted value.
Of course the toy example is a toy, and of course it does not "run" anything, but this is a sound technique: if there is an execution that violates a property, it will be found.
I highly suggest reading the paper that introduced it [1], it is remarkably clear!
[1] Edmund Clarke, Daniel Kroening, and Flavio Lerda. 2004. A Tool for Checking ANSI-C Programs. In 10th International Conference on Tools and Algorithms for the Construction and Analysis of Systems (TACAS) (LNCS), 2004, Barcelona, Spain. Springer, 168–176. https://doi.org/10.1007/978-3-540-24730-2_15
int main(){
char buffer[10];
buffer[10] = 0;
}
are so rare they are hardly worth bothering with. The more usual case is: int get(char* buffer)
{
return buffer[10];
}
void test() {
char buffer[10];
get(buffer);
}
I.e. the array bounds for buffer get lost in the function call. I have proposed a fix:https://www.digitalmars.com/articles/C-biggest-mistake.html
that is compatible with existing code.
And yet, nobody cares. Oh well! Instead, we have overly complex solutions like this:
https://developers.redhat.com/articles/2022/09/17/gccs-new-f...
cbmc /tmp/walter.c --bounds-check --pointer-check --function test
...
[get.pointer_dereference.5] line 3 dereference failure: pointer outside object bounds in buffer[(signed long int)10]: FAILURE
...
There are many footguns. People love their guns. Makes them feel powerful.Well, duh: if you remove the most egregious footguns from C, you end up basically with Pascal, and here is Why Pascal Is Not My Favorite Programming Language.
And when you try to explain to them that C's abstract machine has semantics of "when you omit a safety check, you actually makes a promise to the compiler that this check is redundant, that you'll promise that you'll make sure in some other way that in no possible execution will the illegal values ever show up in this place, and the compiler will actually hold you to this promise" — they throw tantrums and try to argue that no, it hasn't this semantics, and even if has, it's not the semantics as originally intended by K&R and it is the authors of the C compilers who are wrong (even though the authors of C compilers are the people who actually write both the C standards and the C compilers...)
Must have to do something with imprintment: I've learned C as my 3rd language, and from the start I was taught that its UB is absolutely insane — and I've never felt "nah, it should just do what I meant, dangit" denial about it, only "this is sad, how can I even know while writing code when I am making a baseless promise especially when it's made by omitting something?" But like you've said, people like their footguns.
Which anyway was not an issue in the PL/I variants that predated C, nor the Mesa/Modula-2 descendents from the mid-70's.
EDIT:
Walter's example with 1978's Modula-2.
MODULE Example;
FROM InOut IMPORT WriteString, Write, WriteLn;
PROCEDURE get(buffer : ARRAY OF CHAR): CHAR;
BEGIN
RETURN buffer[10]; (* This will boom unless compiled with bounds checking disabled, in which case who knows *)
END get;
VAR
buffer : ARRAY [0..9] OF CHAR;
BEGIN
WriteString('The out of bounds character is');
Write(get(buffer));
WriteLn;
END Example.Eh, I think most C programmers frustrations with UB stem from knowing that the C standard has fundamental flaws and modern compilers abuse that fact for "optimizations" on UB. This paper covers the topic pretty well[0].
I fully support Casey Muratori's viewpoint that undefined behavior should not exist in the standard[1]. Instead, the C standard should enumerate all valid behaviors compliant compilers can implement. This would allow compilers to make unintuitive optimizations for the platforms that need them, but still allow programmers to be certain that their program semantics will not change in different versions of the said compiler.
[0] https://www.complang.tuwien.ac.at/kps2015/proceedings/KPS_20... [1] https://youtu.be/dyI0CwK386E?si=vsqJ8uWHY8xkGmFm
int get(char* buffer, int i)
{
return buffer[i];
}
#include <stdio.h>
void test() {
char buffer[10];
get(buffer, getc(stdin));
}So, it will find a counter-example.
[1]: https://thephd.dev/_vendor/future_cxx/papers/C%20-%20Non-own...
BTW, it's simple to implement.
What matters is if enough people in WG14 with voting rights care.
T f(args)[..] { body }
This would be hard to parse. Then what about: T[..] f(args) { body }
But if adding [] after T is allowed in function declaration, then why not for arrays as well: T[..] a;int get(int n, char (*buffer)[n]) { return buffer[10]; }
int main() { char buffer[10]; get(10, &buffer); }
Then a run-time bounds checker or a model checker can find the bug: https://godbolt.org/z/a4ExKMn1s
int get(int n, char buf[n])
{
return buf[10];
}
It's if you want to use sizeof that you need a pointer to array. But if you have n, why would you need to query the size of your array?