Eigentactics / Research

The rotation that moved nothing

The setting

As in our last post from this project, we’re reverse engineering a large 32-bit x86 Linux program that ships without symbols, by rewriting its functions as C++ one small batch at a time. A fleet of language-model agents writes the rewrites. Each one has to match the original machine code on 10,000 inputs, inside one process, in a test that calls both versions and compares their results and the memory they change. About 34,700 functions have passed so far.

Machine code has no types. A load is a load, and a word of memory is whatever the next instruction treats it as. So rewrites often come out in one of two dialects: typed structs, when a worker has worked out the layout, and raw words at offsets, when it hasn’t. Different workers write different functions, and sooner or later one dialect calls the other.

That is the whole bug, but it took a while to look like that.

One byte

Two things were failing, and we didn’t know they were related.

First, a run of the whole collection in sorted order, in one process, aborted partway through. The natural suspect was state leaking from one batch into a later one, which is how such failures had usually turned out, or a stray write into the original program’s code. A debugger run ruled out the second: the code was byte-for-byte unchanged when the process crashed.

Second, we had built the collection with inlining turned off, for an unrelated sweep looking for tests that depend on stack garbage. Thirteen batches failed in that build before any garbage was added. The batch that had aborted the sorted run was one of the thirteen, which suggested one cause.

That batch inserts into a red-black tree. We printed the bytes that differed between the original’s memory and the rewrite’s, and exactly one did:

+4212 actual=01 expected=00
total differing bytes 1

Dumping the tree showed what that byte was. Every link and every key matched. Offset 4212 was the colour byte of one node. The other difference was in the tree’s header node, a stack object outside that memory: its colour was wrong too. The inputs were keys 10, 5 and 7, and the other three test patterns passed.

Those keys are the textbook case for a double rotation. 7 lands as the right child of 5, which is the left child of 10, so the fix-up rotates left at 5 and then right at 10.

Two dialects

Here is the insert’s fix-up, in the typed dialect. black is 1 for black and 0 for red:

if (z == z->parent->right) {
    z = z->parent;
    rotate_left(t, z);
}
z->parent->black = 1;              // z->parent was just changed
z->parent->parent->black = 0;
rotate_right(t, z->parent->parent);

And here is the start of the rotation it calls, a helper from elsewhere in the collection, in the raw dialect. Words 0, 1 and 2 of a node are its left, parent and right links:

inline void rotate_left(Tree* t, void* xv) noexcept {
    auto* x = reinterpret_cast<uintptr_t*>(xv);
    auto* y = reinterpret_cast<uintptr_t*>(x[2]);
    uintptr_t b = y[0];
    x[2] = b;
    ...
    y[0] = reinterpret_cast<uintptr_t>(xv);
    x[1] = reinterpret_cast<uintptr_t>(y);    // x->parent = y
}

Both are faithful to the machine code, and each passes its own test. Together they break a rule. The links are objects of type Node*, and the rotation writes them through an lvalue of type unsigned int, which is what uintptr_t is here. C++ allows access to an object only through its own type, its signed or unsigned counterpart, or a character type or std::byte ([basic.lval], paragraph 11 in the current draft). Anything else is undefined behaviour. GCC’s manual puts its side of that bargain plainly: under -fstrict-aliasing, on at -O2, “an unsigned int can alias an int, but not a void* or a double”.

What the compiler knew

Without inlining, rotate_left is a real call. A call to an unknown function normally forces the compiler to assume any memory might have changed, so it would reload z->parent afterwards.

But this call isn’t to an unknown function. Since GCC 11, a pass called IPA-modref summarises what each function reads and writes, and callers can consult the summary. Here is what it recorded for the rotation:

stores:
    Base 0: alias set 3
      Ref 0: alias set 3
        Every access

Alias set 3 is unsigned int, the only type the rotation stores through. The typed links are in a different set: the same dump records stores like x->left with ref_set=4. So as far as the caller can tell, this function moves integers, and no Node* link in the tree can be among them. The rotation moves nothing.

The caller has already read the value it wants. The test z->parent == z->parent->parent->left loaded the grandparent, so after z = z->parent the new z->parent is in hand. GCC’s final intermediate form shows it carrying that value across the call. _62 is the old parent, and _3 is its parent, loaded before any of this:

<bb 9>:
  _57 = MEM[(struct Node * *)t_37(D)];
  rotate_left.isra (_57, _62);

<bb 10>:
  # z_29 = PHI <z_63(8), _62(9)>
  # prephitmp_73 = PHI <pretmp_72(8), _3(9)>
  prephitmp_73->black = 1;

On the path through the rotation, the colour write goes through _3. In the machine code that value lives in %ebp, a register that survives calls:

.L22:
    movl    4(%ebx), %ebp           # %ebx = z->parent, so %ebp = its parent
    ...
.L26:
    movl    (%edi), %eax
    movl    %ebx, %edx
    movl    %ebx, %esi              # z = z->parent
    call    rotate_left.isra.0
    jmp     .L27
    ...
.L27:
    movb    $1, 28(%ebp)            # z->parent->black = 1, using the old value

With -fno-strict-aliasing the same source reloads, as you’d expect:

.L26:
    movl    4(%esi), %eax           # read z->parent again
    subl    $8, %esp
    movb    $1, 28(%eax)

Why the shape survives

A stale pointer in a tree rotation sounds like it should corrupt the tree. Here it doesn’t, because only that one read is stale. The very next z->parent is read from memory and is correct, probably because the colour store goes through uint8_t, a character type that may alias anything. After the left rotation, when 7 has taken 5’s place, the code should paint 7 black, paint 10 red and rotate right at 10. Then 7 is the black root, its children are red, and the loop ends. Hardware watchpoints on the four colour bytes show what happens instead:

  1. The stale write paints 10 black. 10 is the root and already black, so nothing changes, and 7 stays red.
  2. The next read is fresh: the grandparent of 5 is 10, which is painted red.
  3. The right rotation at 10 runs correctly. The shape is now right, and all the links are final.
  4. The loop checks z->parent, which is 7. It should be black, but it’s red, so the loop runs again.
  5. 7’s parent is the header node, whose left field points to the tree’s smallest node, 5. That isn’t 7, so the code concludes that 7 is a right child, and takes 5 as 7’s uncle. 5 is z itself.
  6. The “uncle” is red, so this is the recolouring case: 7 black, 5 black, the header red. z moves up to the header.
  7. The header’s parent is the root, 7, now black, so the loop ends.

The result is 7 black with a black child and a red child, so the two paths have different black heights, and a red header, which the loop relies on being black. Lookups only follow links, so they still work, and nothing fails straight away.

This survival depends on the details. An earlier version of our reduction, with a one-word key and the leaf check written through Node*, also reused the stale value for the grandparent. It rotated in the wrong place and scrambled the links, leaving 5 as the root and 10 with two children it shouldn’t have.

Why it hid

The rule was broken in every build. It only produced a wrong answer when rotate_left stayed a call.

When a batch is compiled on its own, as it is when a worker submits it, the rotation is inlined into the insert: its disassembly contains no call to it. The test passes. In the sorted combined build, with hundreds of batches in each translation unit, the same source with the same flags keeps the call, so modref’s summary applies. We saw that decision in the output rather than in the inliner’s reasoning. Limits on how much a unit may grow are the obvious candidate, but we didn’t confirm that. Our no-inlining build reached the same call by force. Our usual rounds, which shuffle batches into random groups, were passing with the same batch, presumably because the rotation was inlined there; we didn’t check those builds.

Inlining doesn’t make the code correct. In the inlined build’s final form, the rotation’s stores are MEM[(unsigned int *)…] and the next read of z->parent does go back to memory. Nothing obliges GCC to do that, since the same type rule applies.

Reproducing it

rbtree.cpp is the complete reduction, about 130 lines, and contains nothing from the program. With GCC 13.3 on x86-64 (-m32 needs the multilib packages):

-O2                                     head black; 10 red, 5 red,   7 black   correct
-O2 -fno-inline                         head RED;   10 red, 5 black, 7 black   wrong
-O3 -fno-inline                         head RED;   10 red, 5 black, 7 black   wrong
-O2 -fno-inline -fno-ipa-modref         head black; 10 red, 5 red,   7 black   correct
-O2 -fno-inline -fno-strict-aliasing    head black; 10 red, 5 red,   7 black   correct
-O1 -fno-inline                         head black; 10 red, 5 red,   7 black   correct
-Os -fno-inline                         head black; 10 red, 5 red,   7 black   correct

The wrong line is the exact state we saw in the real batch. Marking only the helper noinline gives the same wrong result with inlining otherwise on, so the condition is the helper staying out of line, not a global setting. Declaring the rotation’s word type __attribute__((may_alias)) fixes it in the source.

-O1 has modref but not strict aliasing, so that line is expected. -Os and -O1 -fstrict-aliasing have both and still happen to come out right, which shows they’re necessary rather than sufficient: the final step is a load-reuse decision that doesn’t always go this way.

Nothing warned us. -Wall -Wextra -Wstrict-aliasing=1, the most aggressive level of that warning, says nothing. UBSan and ASan builds report nothing and print the correct tree, since their instrumentation changes the code enough to lose the bug. We didn’t try Clang’s TypeSanitizer, which targets this class of error.

At full size

A reduction shows that a mechanism exists, not that it’s the one that bit you, so we ran the real thing at one commit in sorted order, changing only the flags:

no aliasing flag          aborts at the red-black batch; tree_insert calls rotate_left
-fno-ipa-modref only      34,712 / 34,712 functions match, 347,120,000 checks
-fno-strict-aliasing      34,712 / 34,712 functions match (the project’s build now)

The last line is from the project’s own full run at that commit, which uses a shuffled order rather than the sorted one. Of the thirteen no-inlining failures, one was a separate test bug and eight went away with the flag. Each of those eight, built alone, fails with -fno-inline and passes when -fno-ipa-modref is added, though we’ve only read the tree one closely enough to name the stale load.

Two things remain unexplained. Four more batches still fail in the no-inlining build with the flag on, though they pass in normal builds. And before the flag, the debugger run mentioned above crashed in a different batch from the one this post is about, as did an earlier full run. Neither crash has recurred in a run with the flag, but we never traced them, so we can’t say this bug caused them.

The fix, and whose fault it was

It wasn’t the compiler’s. GCC was told, by the language, that these accesses couldn’t overlap, and it used that to skip a load. It isn’t the flag’s fault either: -fstrict-aliasing just reflects the rule. The code broke the rule, and it couldn’t easily have done otherwise, because the rule describes a world of typed objects and the original program’s machine code never lived there. The GCC 6.3 that built the original had already compiled the types away.

Everything now builds with -fno-strict-aliasing, which tells GCC not to assume that accesses of different types can’t overlap. That’s the same choice the Linux kernel made long ago, for similar reasons: it’s low-level code that reinterprets memory on purpose. We preferred it to the narrower -fno-ipa-modref because modref is only one route to this. Type-based reasoning runs through the whole optimiser, and the next miscompile needn’t involve a call. We set it for the code that gets loaded into the real program too, where no comparison would catch a wrong colour byte. We haven’t measured what the flag costs in speed, and for a differential test harness we don’t much care. Whether it’s the right long-term answer for the reconstructed code itself is a question for when that code has its real types.

For a fleet, the lesson is about what a passing test certifies. The test certified that this function, compiled this way, matches the original on these inputs. A different build is a different program whenever the source relies on undefined behaviour, and passing doesn’t show that it doesn’t. A combined build, compiled differently from the one each worker tested, caught something no worker could have seen in its own batch. Neither function was wrong, and neither worker did anything we’d have flagged in review.

One store and one load, at the same address and the same width, had different types in the source and none at all in the machine code. That was enough to change the colour of one node.