Issue 237819
Summary [clang][Driver] Parallel -save-temps=obj builds can silently use another compilation's temporary files
Labels clang
Assignees
Reporter yqtian-se
    With `-save-temps=obj`, Clang names the `.i`, `.bc`, and `.s` temporary files
after the input file and takes only their directory from `-o`. Two parallel
compilations of the same source into different object files in one directory
therefore write the same temporary files.

If the compilations use different options, one compilation can read the
other's preprocessed source or bitcode and silently produce an object for the
wrong configuration.

### Reproduction

Save the following as `repro.sh` and run it with a Clang binary:

```sh
#!/bin/sh
set -u
CC=${1:?usage: repro.sh CLANG}
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cd "$tmp"

printf 'int mexp(void) { return M; }\n' > s.c
printf 'int mexp(void);\nint main(void) { return mexp(); }\n' > m.c

bad=0
for i in $(seq 1 20); do
  rm -rf o
  mkdir o
  "$CC" -O2 -save-temps=obj -DM=1 -c s.c -o o/a-s.o &
  "$CC" -O2 -save-temps=obj -DM=2 -c s.c -o o/b-s.o &
  wait

  "$CC" m.c o/a-s.o -o o/ta
  "$CC" m.c o/b-s.o -o o/tb
 ./o/ta; a=$?
  ./o/tb; b=$?
  [ "$a" = 1 ] && [ "$b" = 2 ] || bad=$((bad + 1))
done

echo "incorrect runs: $bad of 20"
```

```console
$ sh repro.sh /path/to/clang
incorrect runs: 20 of 20
```

Both commands write `o/s.i`, `o/s.bc`, and `o/s.s`. One or both resulting
objects can consequently return the value selected by the other command.
Repetition makes the race easy to observe, but the exact number of incorrect
runs is timing-dependent.

Reproduced on x86_64 Ubuntu 24.04 with LLVM main
`adad1a68aba2`. The reproducer failed in 20 of 20 runs. GCC 13
produced the expected objects in 50 of 50 runs in the corresponding check.

#### Expected behavior

The two compilations should use distinct temporary files and produce objects
that return 1 and 2 respectively. For `-c` and `-S`, where `-o` identifies the
output of this input, the temporary names could follow the output stem, as GCC
does. For example:

```text
-c -o o/a-s.o  ->  o/a-s.i, o/a-s.bc, o/a-s.s
-c -o o/b-s.o  ->  o/b-s.i, o/b-s.bc, o/b-s.s
```

#### Real-world instance

Debian's dsfmt package compiles `dSFMT.c` multiple times with different
`-DDSFMT_MEXP` values. With parallel compilation and `-save-temps=obj`, these
jobs collide in the same way and can silently produce objects for the wrong
period configuration.

### Analysis

`Driver::GetNamedOutputPath` derives each saved temporary's base name from the
input file. In `-save-temps=obj` mode it replaces the directory with the
directory of `-o`, but does not use the output's distinct stem. The resulting
paths are therefore identical for the two commands above.


_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to