Re: [RFC] Documentation about unaligned memory access

From: Luciano Rocha
Date: Sat Nov 24 2007 - 12:22:54 EST


On Sat, Nov 24, 2007 at 05:19:31PM +0100, Pierre Ossman wrote:
> On Sat, 24 Nov 2007 15:50:52 +0000
> Luciano Rocha <strange@xxxxxxxxxxxxx> wrote:
>
> >
> > Dumb memcpy (while (len--) { *d++ = *s++ }) will have alignment problems
> > in any case. Intelligent ones, like the one provided in glibc, first copy
> > bytes till output is aligned (C file) *or* size is a multiple (i686 asm file)
> > of word size, and then it copies word-by-word.
> >
> > Linux's x86_64 memcpy does the opposite, copies 64bit words, and then
> > copies the last bytes.
> >
> > So, in effect, as long as no packed structures are used, memcpy should
> > be safer on *int, etc., than *char, as the compiler ensures
> > word-alignment.
> >
>
> It most certainly does not. gcc will assume that an int* has int alignment. memcpy() is a builtin, which gcc can translate to pretty much anything. And C specifies that a pointer to foo, will point to a real object of type foo, so gcc can't be blamed for the unsafe typecasts. I have tested this the hard way, so this is not just speculation.

Yes, on *int and other assumed aligned pointers, gcc uses its internal
version.

However, my point is that those pointers, unless speaking of packed
structures, can safely be assumed aligned, while char*/void* can't.

> In other words, memcpy() does _not_ save you from alignment issues. If you cast from char* or void* to something else, you better be damn sure the alignment is correct because gcc will assume it is.

Nothing does, even memcpy doesn't check alignment of the source, or
alignment at all in some assembly implementations (only word-copy,
without checking if at word-boundary).

--
lfr
0/0

Attachment: pgp00000.pgp
Description: PGP signature