Skip to contentSkip to conversation

FYI: Re: ugly way to avoiding gcc strict-aliasing warning?

DISCUSSION Paweł Sikora 1 participant 1 message Jan 18, 2012 MD RAID

lore
Share & tools
lore
#0 lore raw
Quoted 9 lines · Paweł Sikora

Hi,

recently i've seen a tricky commit in the mdadm git repository:
http://neil.brown.name/git?p=mdadm;a=commit;h=90fa1a292929ff8a6c7357254b6f616608ec01b5

imho, this is a tricky way to avoid gcc-4.7 diagnostics machinery but it still violates aliasing rules. am i right?

thanks in advance for any comments.

#ifndef AVOID_WARNING
*(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = SWAP (ctx->total[0] <<
3);
#else
ptr = (md5_uint32 *) &ctx->buffer[bytes + pad + 4];
*ptr = SWAP (ctx->total[0] << 3);
#endif

Both code-snippets are indeed exactly the same. In recent GCC (>= 4.5), if you ever read from ctx->buffer[] with an effective type other than md5_uint32 after writing to it using that type you can get miscompilations (reading via an effective type of char is ok, which happens to be the type of ctx->buffer).

In older GCC the above can result in miscompiles even if you happen to follow that restriction (thus, later GCC got more permissive in this area). A portable and safe way of doing the above is

md5_uint32 tem = SWAP (ctx->total[0] << 3);
memcpy (&ctx->buffer[bytes + pad + 4], &tem, sizeof (md5_uint32));

GCC will inline that memcpy.

Richard.

Signature · 4 lines
Richard Guenther <[email protected]>
SUSE / SUSE Labs
SUSE LINUX Products GmbH - Nuernberg - AG Nuernberg - HRB 16746
GF: Jeff Hawn, Jennifer Guild, Felix Imendörffer