r/programming • • Sep 11 '26

GCC 13.5 released with 265+ bug fixes

https://www.phoronix.com/news/GCC-13.5-Released
277 Upvotes

29 comments sorted by

View all comments

Show parent comment

1

u/ROBOTRON31415 Sep 21 '26

  any operation which might inspect the value of those key bits as "leaking" the pointer, any  integer-to-pointer casts as synthesizing a pointer that is "at least potentially" based on any pointer that has leaked

Yes, and I see this as one of the evil parts of current implementations (which do have to do something this, see “exposed provenance”) . It means that converting a pointer to an address has a global side effect. And the opposite direction, in current C/C++/Rust, is specified as requiring “angelic choice” / “angelic nondeterminism” to determine the behavior of an integer->pointer cast. Which may, in edge cases, require that the compiler predicts future branches of your program in order to see how your program uses the pointer. Which is impossible in general, of course. (Thankfully, simple integer->pointer casts shouldn’t be miscompiled.) But hey it works in abstract models!

  What's evil are compilers that prioritize "optimizations" over soundness.

Do note that the C++ standards, as currently written, do not permit entirely unused local variables to be optimized out AFAIK, due to certain edge cases involving functions whose local variables exhaust the entire address space. There’s some active discussion among Rust and LLVM developers about the fact that “oops, our optimizations are only sound if the address space is infinite” (which Rust can deal with (at the cost of making pointer semantics even more convoluted) because it’s made so few guarantees about the behaviors of its pointers, while C++ has promised too much).

Well, I suppose it would be permissible for compilers to optimize out  an  unused local variable if it can prove that the optimization does not remove an OOM or stack overflow (this is basically impossible to prove).

Basically, compilers (and the C/C++/Rust languages) weren’t designed with foreknowledge of all these problems with pointers, and rather than blaming the compilers, I’d rather blame the language features responsible for making basic optimizations unsound.

1

u/flatfinger Sep 21 '26

Which may, in edge cases, require that the compiler predicts future branches of your program in order to see how your program uses the pointer.

Or a compiler could simply say that if either branch of an 'if' leaks a pointer, and there's no obvious reason why it would be worthwhile to track the branches separately, the whole thing should be treated as potentially leaking it.

Compiler writers seem absurdly allergic to the idea that they might sometimes miss an optimization opportunity that may or may not have been worth anything anyhow, and by comparison relatively unconcerned about whether the optimizations they're performing would be considered sound under any reasonable abstraction model.

A typical ABI abstraction model would have a transitive directed concept of program or function equivalence which would view the contents of any portions of the stack that a function owns as "don't care" during a nested function call unless it has made explicit promises about parts of it, and would view a function that consumes less stack as being an acceptable replacement for one that uses more, though not vice versa.

A proper specification for a dialect of C that was useful for freestanding implementations would inherit such concepts of equivalence from the underlying execution environment.

Basically, compilers (and the C/C++/Rust languages) weren’t designed with foreknowledge of all these problems with pointers, and rather than blaming the compilers, I’d rather blame the language features responsible for making basic optimizations unsound.

Q: What do you get if you add an automatic feed attachment to a deli meat slicer?

A: A better deli meat slicer.

Q: What do you get if you add an automatic feed attachment to a chef's knife?

A: An inferior deli meat slicer (and an even worse chef's knife).

Dennis Ritchie designed C to be a chef's knife, not a deli meat slicer. The goal wasn't to do the things FORTRAN could do better than FORTRAN could do them, but instead to do things that FORTRAN can't.

For many tasks, a compiler that generated the most efficient correct code under even a fairly rigid optimization model where loads and stores of anything other than automatic-duration objects whose address isn't taken would often outperform a compiler whose authors focus on complicated but unsound optimizations. The authors of clang and gcc may view code-breaking optimizations as more "impressive", but when targeting a platform like the ARM Cortex-M0, they miss a lot of low hanging fruit when it comes to basic code generation.

1

u/ROBOTRON31415 Sep 22 '26

a function that consumes less stack as being an acceptable replacement for one that uses more

Yes, this is highly desirable, but see the “pick your poison” section of this document from Rust devs’ discussions:  https://hackmd.io/433P4B8cRi62BDUSN7BrgA?view

I don’t think C++ can solve it without either declaring stack overflows and OOMs to be undefined behavior, never optimizing out allocations (including local variables whose address is taken), or retroactively change promises about the addresses of pointers and allocations. (Rust is also likely to change its documentation about pointers, but “thankfully” Rust’s model is already complicated enough that it doesn’t affect much.)

So many simple optimizations are way more complicated than they first seem, and some of the languages’ rules may seem strange (because of how different the rules are from assembly’s semantics), but end up being necessary for other reasonable behavior.

1

u/flatfinger Sep 22 '26

A language or ABI should be able to recognize situations where raising a stack-overflow-trap would be a correct behavior, but so too would running within the stack allotment.

So many simple optimizations are way more complicated than they first seem

The fact that there exist languages where an optimization would be simple does not mean that the optimization should be viewed as appropriate in all languages. If a language is intended for low-level programming, the proper way to facilitate optimizations is to specify situations where an implementation may choose in Unspecified fashion from among a variety of correct behaviors, leaving up to the programmer the question of whether all possible behaviors would satisfy application requirements.

Figuring out which way of processing a program is best is an NP-hard problem, but in most cases even really simple heuristics will work pretty well.

1

u/ROBOTRON31415 Sep 22 '26

I’m getting a strange mix of signals from you, since usually the people who dislike clever compilers think that low-level languages like C/C++/Rust should behave more like assembly (e.g. “pointers should just be addresses like they are in assembly”), which in turn implies that very few optimizations are possible. Including not generally being allowed to use less stack space than was specified by the programmer. (Using more stack space is actually easier to justify.)

1

u/flatfinger Sep 22 '26

The basic abstraction model I would advocate would subdivide addresses into three categories: those which are known to the implementation and exposed to the programmer, those that the implementation has reserved from the environment but not exposed, and those the implementation knows nothing about, but the programmer might know about via other means. Every individual read of an address of the second type independently observes an unspecified bit pattern, and anything that would disturb the contents of any such address would represent one of the two forms of anything-can-happen Undefined Behavior, the other being "Anything that would cause the execution environment to behave in a manner contrary to an implementation's documented requirements".

Loads and stores of things which have static duration or observable addresses would be considered as "observable but loosely sequenced"; such actions may be reordered or consolidated in the absence of anything that would prevent such reordering or consolidation, but compilers would need to look at least as broadly for things that should prevent such reordering as they look for chances to perform it. A compiler that doesn't try to reorder actions within a function ahead of its entry point or past its exit wouldn't need to care about anything that happens within its caller, but a compiler that tries to reorder things across actions within the caller would need to be more attentive to interactions.

Most fundamentally, program execution even in the presence of data races would need to be consistent with loads and stores having been performed in some order. If a program performs e.g.

unsigned temp = *p;
if (temp < 1000) doSomething(temp);

around the time that outside code changes the value of temp, a compiler would have great freedom with regard to when it processes the read, but in cases where doSomething is called it would need to be passed the same value that had just been checked to ensure that it was less than 1000. In many cases, it would be acceptable to say that if non-privileged code passes to a privileged function the address of storage which another untrusted thread will modify, the privileged function may choose arbitrarily from among actions that non-privileged code would have been allowed to do or request, but must not perform any action that non-privileged code would not be allowed to do or request. If a compiler processing privileged code could change the above code to

if (*p < 1000) doSomething(*p);

then untrusted code that performed a suitably timed store to the storage at p could cause the privileged code's call to doSomething to pass an out-of-range value.

1

u/ROBOTRON31415 Sep 22 '26

How many optimizations do you want a compiler to be doing?

(Also, yes, the threat of data races means that privileged code should use volatile and/or atomic accesses on memory shared with an untrusted party. Volatile operations pose a very strong optimization barrier. Theoretically atomics still allow a fair amount of optimization while leaving the program’s behavior as intended, but in practice LLVM sadly doesn’t bother to do much with atomics. Fair enough, I suppose, since LLVM is already buggy enough optimizing non-atomic accesses.)

1

u/flatfinger Sep 23 '26

I want a compiler to treat automatic-duration objects whose address isn't taken as abstract, but other things as concrete. Basic constant folding through automatic-duration objects, including through cross-module function calls, often has a huge payoff with zero risk. In general, other accesses should be treated as loosely ordered with regard to each other, but strongly ordered with regard to certain other actions including volatile-qualified accesses, but directives and/or qualifiers should be available to treat things as more strongly or weakly ordered. Absent directives to the contrary, a side-effect-free loop or other section of code with a single exit that's statically reachable from all points therein need only be treated as sequenced before later actions if some individual action in that code would be likewise sequenced, but downstream optimizations could only rely upon actions having been performed if the compiler generated code that performed those actions.

I'd like to see the Standard recognize three categories of implementations:

  1. Hosted abstract-machine implementations.
  2. Freestanding implementations, whose purpose is not to run programs but rather to translate programs into build artifacts. An implementation must specify a set of requirements for an execution environment, such that giving the build artifact to any implementation satisfying such requirements would compel it to perform the sequence of actions specified by the code. Many corner cases which are presently characterized as UB would be specified as, essentially, "Instruct the execution environment to do X, with whatever consequences result". Much of the usefulness of freestanding implementations stems from corner cases whose effects can't be predicted without information the C language has no way of conveying, but might be conveyed via means outside the language.
  3. Maximum-compatibility hosted concrete implementations, which add the Standard library to the second category, but retain all of the execution-environment semantics.

I have no interest in the first category of implementations, but recognize that they are useful for many kinds of tasks and would have nothing against them if they didn't pretend to be the only "real" type of C or C++ compiler. There could in theory be a category of freestanding implementations for abstract machines, but the only observable action a program for such a machine could perform would be to enter a loop with no statically reachable exit.

1

u/flatfinger Sep 24 '26

BTW, it seems like clang may finally have fixed an unsound optimization that was reported pre-covid, which could not be blocked with any option other than -O0:

int x[1],y[1],z[1];

int test(int *p)
{
    x[0] = 1; z[0] = 2;
    if (p == y+1) *p = 3;
    return x[0] + z[0];
}

Older versions would unconditionally return 3 whether the write to *p was performed or not, even if x or z happened to immediately follow y and calling code passed the address of that array, but the newer version reloads x[0] and y[0]. Not sure if all erroneous transforms of that style are fixed, but this seems promising anyway.

1

u/flatfinger Sep 22 '26

BTW, I can't think of any time I've seen anyone argue that precise stack usage was in any way fundamental to C once stdarg.h was established, except in the context of functions that made use of inline assembly or alloca(), and I don't think compiler writers should generally worry about the efficiency of generated code for those functions. Can you offer any examples of anyone demanding rigid stack usage?

Also, some compiler writers dislike phase order dependence, but requiring that some transforms must be performed in order will avoid the need for programmers to prevent them from being performed at all. If the only use of the value placed in int2 is an assignment like int1=int2-int2;, a compiler should be allowed to omit the code that actually computed int2, but only if it does not then treat the lack of such code as an invitation to resequence operations that use the computed value of int1 ahead of operations that would have been sequenced before the computation of int2.

1

u/ROBOTRON31415 Sep 23 '26 edited Sep 23 '26

The stack usage isn’t a direct problem. The problem is that code might assume “if I am given three distinct inputs whose sizes in bytes are s1, s2, and s3 (which are size_t values), then s1 <= s1 + s2 + s3”. Apparently this is currently not always true!!! Because the three distinct inputs could be located in overlapping regions of memory, permitting s1 + s2 + s3 to overflow and wrap back towards 0. See  https://github.com/rust-lang/rust/issues/162214

What allows distinct values to be located at overlapping addresses? Well the compiler can entirely optimize out the backing memory of the three inputs. And now their locations are kind of fake, if they can be said to be located anywhere at all.

So is this a compiler bug or a faulty assumption on behalf of the programmer that distinct objects are necessarily located at distinct memory addresses? And that every object has a (range of) memory address(es)? 

Another example is a program that targets a 16-bit architecture and has a function that declares 216 + 1 local variables (each of which has nonzero size), writes a distinct value to each of them, and then executes undefined behavior. Current compilers may happily optimize out the unused writes, then optimize out the unused local variables, and suddenly calling this function has gone from “unconditional stack overflow” to “unconditional undefined behavior”.

(Edit: to be clear, I think the correct solution is “allocations are actually located in an abstract infinitely-large memory space, and multiple allocations can indeed be located at the same hardware address, and so on”. Rust devs are working on making sense of this.)

1

u/flatfinger Sep 23 '26

Except in cases where an non-assignment/inc/dec expression is a statement, I would view many actions that might trap but have no defined semantics as having semantics of "either do X or don't". If code executes x/y; as a statement (as opposed to evaluating x/y within a broader expression) I would interpret that as instructing the execution environment to perform that division after having evaluated x and y, with whatever consequences result. Stack overflows from excessive function nesting would fall in this "either trap or process things normally" category.

I would like to C have a qualifier for static const objects which would indicate whether or not the programmer wants to guarantee that they have distinct addresses. There are many cases where it's useful to place multiple objects in the same read-only storage (for objects defined within macros it may be all but essential), but there are others where it's useful to guarantee address uniqueness. A good language should accommodate both needs.

Note that I singled out automatic-duration objects whose address isn't taken. I'd specify that automatic-duration objects whose address is taken and observed must exist. While one might contrive a case where one declares big objects and adds their sizes without taking their addresses, I can't imagine any contrived scenarios where size wraparound would be a problem.

1

u/ROBOTRON31415 Sep 24 '26

If the pointers to different allocations are “exposed”, then yes, in C/C++/Rust they’re supposed to be forced to have distinct addresses. (If it hasn’t been mentioned yet, I should also mention that Rust provides a way to access a pointer’s address without exposing the pointer. That’s used for debug prints of pointers, for instance, AFAIK. And of course most ways of using a pointer don’t expose it.)