Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [PATCH] Fix a bunch of Coverity-reported defects



On Thu, Oct 26, 2023 at 5:37 AM Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
>
> A batch of the warnings that I ignored were assignments of one field
> of a union to another field of the same union, e.g., a casted long
> onto a double, etc., which elicited "overlapping copy" warnings.  I'm
> fairly confident we'd have seen things crashing by now if this wasn't
> safe, but I mention it in case someone knows why it might be a
> problem.

This can indeed cause problems. The conditions under which it happens
are subtle. Here's an example: https://godbolt.org/z/EvxTzM1hn.

    inline int foo(int* x, float* y) {
        *x = 1;
        *y = 2;
        return *x;
    }

    // Returns either 1 or 0x40000000 depending on the
    // absence or presence of -fno-strict-aliasing.
    int bar() {
        union {
            int x;
            float y;
        } z;
        return foo(&z.x, &z.y);
    }

    // The same as bar() but with the call to foo()
    // manually inlined. Return 0x40000000 with and
    // without -fno-strict-aliasing.
    int baz() {
        union {
            int x;
            float y;
        } z;
        // The following code is equivalent to
        // return foo(&z.x, &z.y).
        int* x = &z.x;
        float* y = &z.y;
        *x = 1;
        *y = 2;
        return *x;
    }

When compiled with `gcc -std=c99 -O2`:

  bar:
          mov     eax, 1
          ret
  baz:
          mov     eax, 0x40000000
          ret

When compiled with `gcc -std=c99 -O2 -fno-strict-aliasing`:

  bar:
          mov     eax, 0x40000000
          ret
  baz:
          mov     eax, 0x40000000
          ret

A simple workaround is to compile with -fno-strict-aliasing. This can
result in slower code but I don't think it's likely to be noticable.

Roman.




Messages sorted by: Reverse Date, Date, Thread, Author