It is quite common to pass pointers to struct sockaddr_in and similar socket structures to as struct sockaddr pointers, or to peak at a socket address through a struct sockaddr pointer to look at the sa_family member to determine the concrete socket address type. This breaks strict aliasing. Marek Polacek suggests to add the may_alias attribute to struct sockaddr.
This does not work as expected because it breaks forward declarations: struct sockaddr; struct sockaddr *f(); struct __attribute__((may_alias)) sockaddr {}; struct sockaddr *f() { return nullptr; } results in: t.cc: In function ‘sockaddr* f()’: t.cc:5:18: error: ambiguating new declaration of ‘sockaddr* f()’ struct sockaddr *f() ^ t.cc:2:18: note: old declaration ‘sockaddr* f()’ struct sockaddr *f(); ^
We cannot add the may_alias attribute with the current GCC behavior.
We can try to fix this with a version guard with __GNUC__ >= 7; the relevant test cases should now work. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71255.
Patch posted: PATCH] socket: Use may_alias on sockaddr structs (bug 19622) <https://inbox.sourceware.org/libc-alpha/87v83q6kc2.fsf@oldenburg.str.redhat.com/>
See also https://austingroupbugs.net/view.php?id=1641.
Why is it valid for there to be a previous forward declaration? I don't think it's permitted for applications to make their own declarations of these types.
Fixed for 2.40 via: commit 8d7b6b4cb27d4dec1dd5f7960298c1699275f962 Author: Florian Weimer <fweimer@redhat.com> Date: Sat May 18 09:33:19 2024 +0200 socket: Use may_alias on sockaddr structs (bug 19622) This supports common coding patterns. The GCC C front end before version 7 rejects the may_alias attribute on a struct definition if it was not present in a previous forward declaration, so this attribute can only be conditionally applied. This implements the spirit of the change in Austin Group issue 1641. Suggested-by: Marek Polacek <polacek@redhat.com> Suggested-by: Jakub Jelinek <jakub@redhat.com> Reviewed-by: Sam James <sam@gentoo.org> Reviewed-by: Carlos O'Donell <carlos@redhat.com>
*** Bug 30293 has been marked as a duplicate of this bug. ***