https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101439

            Bug ID: 101439
           Summary: std::atomic<__uint128_t>::load() crashes - possible
                    fix with mutable
           Product: gcc
           Version: 4.8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: doodspav at gmail dot com
  Target Milestone: ---

The following code will cause a segfault on x86 from g++4.8 up to g++11.1
(currently the latest non-trunk version on Godbolt):

```
#include <atomic>

struct S { long i, j; };
const std::atomic<S> x{ {0, 0} };

int f(const std::atomic<S>* p) {
    S y = *p;
    return y.i;
}

int main() {
    return f(&x);
}
```
(demonstrated here: https://godbolt.org/z/eWcTv5fdY for however long the link
remains alive)

Loading the value from `x` causes libatomic to use `lock cmpxchg16b` on
read-only memory, crashing the program (since `lock cmpxchg16b` always performs
a write). 

This has been reported in bug report 95722 (and touched upon in 70490), however
those treat it as a libatomic bug (which it technically is), whereas here I
seek to treat it as a libstdc++ bug.

A "simple" workaround for C++ that doesn't involve changing anything in
libatomic would be to mark all members in any 16 byte specialisation of
`std::atomic` as `mutable`, preventing the compiler from placing it in
read-only memory. This is what MSVC does in their implementation (as does
Boost.Atomic I think). This shouldn't break anything as far as I can tell.

This code (using `_Atomic`) also causes a segfault in C. I can't really think
of a similar fix there (maybe just act as if DR459 never happened?).

Reply via email to