Issue 240312
Summary [LLD][ELF][PPC64] TOC restore overwrites the instruction after a same-object call without a NOP
Labels lld
Assignees
Reporter basavesh
    ## Summary

LLD accepts a PPC64 call without the usual TOC-restore NOP when the callee is
defined in the same object. It then writes `ld r2,24(r1)` at the instruction
after the call even when that instruction is not a NOP.

The example below places `li r31,0` after a recursive call. LLD replaces that
instruction with the TOC restore. The missing clear makes a later branch depend
on the input. Both inputs still return the same value.

I reproduced this with LLD 21.1.8. LLVM main
`3fc59d072a82694a77fe1d700ccf9bd71464181f` still contains the same
unconditional write on 2026-11-09.

## Reproducer

The commands below require:

- `llvm-mc`, `llvm-objdump`, and `ld.lld`;
- `qemu-ppc64le`;
- a PPC64LE sysroot containing `lib64/ld64.so.2`;
- optionally, `powerpc64le-linux-gnu-ld.bfd` for the control.

Save this as `probe.s`:

```asm
        .abiversion 2
        .section .text.ct_probe,"ax",@progbits
        .globl ct_probe
        .type ct_probe,@function
ct_probe:
.Lprobe_gep:
        addis 2,12,.TOC.-.Lprobe_gep@ha
        addi 2,2,.TOC.-.Lprobe_gep@l
.Lprobe_lep:
        .localentry ct_probe,.Lprobe_lep-.Lprobe_gep
        mflr 0
        std 0,16(1)
 stdu 1,-64(1)
        std 31,56(1)

        mr 31,3              # keep the input in r31
        cmpdi 4,0
        beq .Lbase
        addi 4,4,-1
        bl ct_probe
        li 31,0              # LLD incorrectly replaces this instruction

        cmpdi 31,0
        beq .Ljoin
 nop
.Ljoin:
        li 3,42
        b .Lreturn
.Lbase:
        li 3,42
.Lreturn:
        ld 31,56(1)
        addi 1,1,64
        ld 0,16(1)
        mtlr 0
        blr
        .size ct_probe,.-ct_probe
```

Save this as `start.s`:

```asm
 .abiversion 2
        .text
        .globl _start
        .type _start,@function
_start:
.Lstart_gep:
        addis 2,12,.TOC.-.Lstart_gep@ha
        addi 2,2,.TOC.-.Lstart_gep@l
.Lstart_lep:
        .localentry _start,.Lstart_lep-.Lstart_gep
        ld 4,8(4)
        lbz 3,0(4)
 addi 3,3,-48
        li 4,1
        bl ct_probe
        nop

        # Exit 0 only if ct_probe returned 42.
        xori 3,3,42
        li 0,1
 sc
        b .
        .size _start,.-_start
```

Build the shared object and driver:

```sh
llvm-mc -triple=powerpc64le-linux-gnu -filetype=obj probe.s -o probe.o
llvm-mc -triple=powerpc64le-linux-gnu -filetype=obj start.s -o start.o

ld.lld -shared probe.o -soname libprobe.so -o libprobe.so
ld.lld start.o ./libprobe.so -o driver -e _start \
  --dynamic-linker /lib64/ld64.so.2 -rpath '$ORIGIN'
```

Disassemble `ct_probe`:

```sh
llvm-objdump -d --no-show-raw-insn libprobe.so | \
 sed -n '/<ct_probe>:/,/^$/p'
```

The output contains:

```text
bl __plt_ct_probe
ld      2, 24(1)       # this replaced li 31,0
cmpdi   31, 0
```

The input object still contains the clear:

```sh
llvm-objdump -dr --no-show-raw-insn probe.o | \
  sed -n '/<ct_probe>:/,/^$/p'
```

```text
bl      ...
li      31, 0
cmpdi 31, 0
```

## Runtime check

Set `SYSROOT` to the PPC64LE sysroot and run both inputs:

```sh
SYSROOT=/path/to/ppc64le/sysroot

qemu-ppc64le -d exec,nochain -D input-0.log \
  -L "$SYSROOT" ./driver 0
echo "input 0 exit: $?"

qemu-ppc64le -d exec,nochain -D input-1.log \
  -L "$SYSROOT" ./driver 1
echo "input 1 exit: $?"
```

Both exits are 0. To compare only translation blocks belonging to `ct_probe`,
save this as `normalize.py`:

```python
#!/usr/bin/env python3
import re
import subprocess
import sys

image, log = sys.argv[1:]
symbols = subprocess.check_output(
    ["readelf", "-sW", image], text=True
).splitlines()

for line in symbols:
    fields = line.split()
    if fields and fields[-1] == "ct_probe":
        start = int(fields[1], 16)
        size = int(fields[2])
        break
else:
 raise SystemExit("ct_probe symbol not found")

page_start = start & 0xfff
page_end = page_start + size
text = open(log, encoding="utf-8").read()
pcs = [
    int(value, 16)
    for value in re.findall(r"Trace .*?\[[0-9a-fA-F]+/([0-9a-fA-F]+)/", text)
]
inside = [pc for pc in pcs if page_start <= (pc & 0xfff) < page_end]
entries = [i for i, pc in enumerate(inside) if (pc & 0xfff) == page_start]
if not entries:
 raise SystemExit("ct_probe was not found in the trace")

trace = [(pc & 0xfff) - page_start for pc in inside[entries[-1]:]]
print(",".join(f"+0x{offset:x}" for offset in trace))
```

Run:

```sh
python3 normalize.py libprobe.so input-0.log
python3 normalize.py libprobe.so input-1.log
```

Observed output:

```text
input 0: +0x0,+0x24,+0x8,+0x44,+0x2c,+0x3c,+0x48
input 1: +0x0,+0x24,+0x8,+0x44,+0x2c,+0x38,+0x48
```

The results were stable across three runs per input.

## GNU ld control

GNU ld 2.46 preserves the instruction after the call when given the exact same
`probe.o`:

```sh
powerpc64le-linux-gnu-ld.bfd -shared probe.o \
 -soname libprobe.so -o libprobe-bfd.so

llvm-objdump -d --no-show-raw-insn libprobe-bfd.so | \
  sed -n '/<ct_probe>:/,/^$/p'
```

Its output still contains `li 31,0`, and the two normalized runtime traces are
equal. To run that control with the same driver:

```sh
cp libprobe.so libprobe-lld.so
cp libprobe-bfd.so libprobe.so

qemu-ppc64le -d exec,nochain -D bfd-0.log \
  -L "$SYSROOT" ./driver 0
qemu-ppc64le -d exec,nochain -D bfd-1.log \
  -L "$SYSROOT" ./driver 1

python3 normalize.py libprobe.so bfd-0.log
python3 normalize.py libprobe.so bfd-1.log
```

Both control traces are:

```text
+0x0,+0x24,+0x8,+0x44,+0x2c,+0x3c,+0x48
```

## Cause

Current LLD has this logic in `lld/ELF/Arch/PPC64.cpp`:

```cpp
if (rel.sym->needsTocRestore()) {
  if ((rel.offset + 8 > sec.content().size() ||
       read32(ctx, loc + 4) != NOP) &&
      rel.sym->file != sec.file) {
    Err(ctx) << ... << " lacks nop, can't restore toc";
    continue;
  }
  write32(ctx, loc + 4, 0xe8410018); // ld %r2, 24(%r1)
}
```

For a same-object call, `rel.sym->file == sec.file`, so a non-NOP instruction is
accepted. The following `write32` still overwrites it.

The same-object compatibility case should not write a TOC restore over a
non-NOP instruction. It should also avoid writing past the input section.

## Related issues

- #98859 concerns cross-module tail calls and the missing-NOP diagnostic.
- #17728 concerns Clang failing to emit a required NOP.

Neither issue covers LLD accepting a same-object call and then replacing the
real instruction after it.

I am filing this publicly as a linker wrong-code bug. The constant-time example
shows a possible security consequence, but I have not identified affected
production software or a concrete exploit.

AI disclosure: I have used AI/LLM to format this report. 
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to