This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: -Wstrict-aliasing in 2.95/6?
Martin v. Loewis wrote:
> Yes. It would not have caught the original example __constant_memcpy,
> because this function expects void*, and converts those to int, for
> efficient copying.
Someone said `memcpy' in general doesn't have aliasing problems, and in
fact `memcpy' is often the _only_ safe way to access the bit pattern of
one type as another. (The union suggestion is apparently specific
to a quirk of GCC's implementation).
So it's Linux' implementation of __constant_memcpy that has an aliasing
bug? I guess that one can be fixed if there's a fix.
> What example of the Linux kernel would have been detected by that
> rule?
Dave Miller gave this:
>Actually, I've changed my mind, having to get rid of all such types of
>casts inside the networking etc. is just an abomination. There is no
>reason anyone should have to use unions to teach the compiler about
>what they're actually touching, if someone casts the thing they (the
>programmer) know what they are doing, the compiler shouldn't assume
>anything.
>
>I'm not saying this should be the normal mode of operation, but some
>mechanism needs to exist so that such code can be made valid _without_
>resorting to ugly unions. Consider our TCP hashing comparison code
>in the kernel has gems like this:
>
>#define TCP_IPV4_MATCH(__sk, __cookie, __saddr, __daddr, __ports, __dif)\
> (((*((__u64 *)&((__sk)->daddr)))== (__cookie)) && \
> ((*((__u32 *)&((__sk)->dport)))== (__ports)) && \
> (!((__sk)->bound_dev_if) || ((__sk)->bound_dev_if == (__dif))))
>
>Sorry, I'm not using a union for this, it's totally a performance hack
>and I'm not going to uglify the socket structure with silly unions.
>And actually in this case, there is no reason the compiler cannot see
>what I am up to. Do powerful optimizations override common sense?
Apparently this occurs a lot in the kernel. The uglification of unions
may be necessary eventually, _if_ -fstrict-aliasing is a worthwhile
optimisation in the kernel. Frankly unions in that example won't be
ugly at all with anonymous unions. [Does GCC-2.95 have anonymous unions?]
But apparently just finding where to add the unions will be too
difficult without a decent warning.
I'm not surprised: bugs due to type-non-aliasing are very subtle and
vary from one compile to the next.
> Also, you should treat char* very much like void*: ISO C allows to
> access any object through a char*.
That one falls out naturally: dereferencing char * can alias anything.
> The danger of such a rule is that people assume their code is safe
> when they don't get warnings, when it is not.
I disagree in general. Sure people are pleased when the code produces
no warnings. Some things are just too difficult to warn about, yet the
warnings for the common cases are still helpful. (E.g. `if (x = 1)' is
caught but not `if ((x = 1))' even though the latter _might_ be a typo).
-- Jamie