[PATCH] fix strict aliasing error on ubuntu 10.04
Uri Simchoni
uri at samba.org
Tue Jul 19 06:34:06 UTC 2016
I'm familiar with the following trick:
union sockaddr_any {
struct sockaddr addr;
struct sockaddr_in addr_in;
struct sockaddr_in6 addr_in6;
struct sockaddr_storage addr_storage;
};
int get_socket_port(int fd)
{
union sockaddr_any sa;
socklen_t length = sizeof(sa);
if (fd == -1) {
return -1;
}
if (getsockname(fd, &sa.addr, &length) < 0) {
return -1;
}
#if defined(HAVE_IPV6)
if (sa.addr_storage.ss_family == AF_INET6) {
return ntohs(sa.addr_in6.sin6_port);
}
#endif
if (sa.addr_storage.ss_family == AF_INET) {
return ntohs(sa.addr_in.sin_port);
}
return -1;
}
(I also don't think that issuing a warning is a compiler bug per-se,
because the code does break strict aliasing. Maybe there's a buggy
optimization somewhere, whose by-product is this warning, or maybe the
compiler simply isn't smart enough to understand that no possible
optimization would break anything here - that's OK, compilers are
allowed to be dumb and many of the C language rules were written by and
for lazy compiler writers).
On 07/19/2016 02:38 AM, Michael Adam wrote:
> Comments?
>
> On 2016-07-14 at 11:36 +0200, Michael Adam wrote:
>> Trying to fix the samba-o3 autobuild target on
>> the 104 test host. There are several errors of type
>> "dereferencing pointer breaks strict aliasing rules".
>> Mostly for socket related structures.
>>
>> For this one, there was already an attempt to fix it, but
>> it did not work out, apparently:
>>
>> 2a5183f49efc1d407ed36c457d8a953e1363eb42
>>
>> I only seem to get away with memcpy for this one.
>> If someone has a better patch, I'm all ears...
>>
>> Cheers - Michael
>
>> From dca904ad40df2db203c02d646c8d56b459bd364b Mon Sep 17 00:00:00 2001
>> From: Michael Adam <obnox at samba.org>
>> Date: Thu, 14 Jul 2016 10:54:06 +0200
>> Subject: [PATCH] lib:util: fix strict aliasing warning in get_socket_port()
>>
>> Only memcpy helped here ...
>>
>> Signed-off-by: Michael Adam <obnox at samba.org>
>> ---
>> lib/util/util_net.c | 10 ++++++----
>> 1 files changed, 6 insertions(+), 4 deletions(-)
>>
>> diff --git a/lib/util/util_net.c b/lib/util/util_net.c
>> index cb238ad..740c014 100644
>> --- a/lib/util/util_net.c
>> +++ b/lib/util/util_net.c
>> @@ -918,13 +918,15 @@ int get_socket_port(int fd)
>>
>> #if defined(HAVE_IPV6)
>> if (sa.ss_family == AF_INET6) {
>> - struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)&sa;
>> - return ntohs(sa_in6->sin6_port);
>> + struct sockaddr_in6 sa_in6;
>> + memcpy(&sa_in6, &sa, sizeof(sa_in6));
>> + return ntohs(sa_in6.sin6_port);
>> }
>> #endif
>> if (sa.ss_family == AF_INET) {
>> - struct sockaddr_in *sa_in = (struct sockaddr_in *)&sa;
>> - return ntohs(sa_in->sin_port);
>> + struct sockaddr_in sa_in;
>> + memcpy(&sa_in, &sa, sizeof(sa_in));
>> + return ntohs(sa_in.sin_port);
>> }
>> return -1;
>> }
>> --
>> 1.7.0.4
>>
>
>
>
More information about the samba-technical
mailing list