Aligning source and destination addresses in memcpy

I want to write memcpy code that does phased copy instead of byte by byte to increase speed. (Although I need to do a few bytes by bytes for the last or several bytes). Therefore, I want my source address and destination address to be aligned correctly. I saw the implementation of memcpy in glibc https://fossies.org/dox/glibc-2.22/string_2memcpy_8c_source.html it performs alignment only for the destination address. But even if the source address is not correctly aligned, this will lead to a bus error (check that alignment checking is enabled on my processor). I am not sure how to properly adjust the alignment of the source and destination. Because if I try to align the source code by copying a few bytes bytes, it will also change the destination address, so first the destination address, which was correctly aligned, may not be aligned correctly. So is there a way to align both ?. Please help me.

void  memcpy(void  *dst,  void  *src,int  size)
{
   if(size >= 8)
   {
     while(size/8) /* code will give sigbus error if src = 0x10003 and dst = 0x100000 */ 
     {
       *((double*)dst)++  =  *((double*)src)++; 
        size  =  size  -  8;
     }
   }

   while(size--)
   {
     *((char*)dst)++  =  *((char*)src)++;
   }
}
+4
source share
2 answers

... so first, the address of the recipient that was correctly aligned could be incorrectly aligned. So is there a way to align both?

memcpy, , , , ... (. )

GNU:

void * memcpy(void * dst, void const * src, size_t len)
{
    long * plDst = (long *) dst;
    long const * plSrc = (long const *) src;

    if (!(src & 0xFFFFFFFC) && !(dst & 0xFFFFFFFC))
    {
        while (len >= 4)
    {
            *plDst++ = *plSrc++;
            len -= 4;
        }
    }

    char * pcDst = (char *) plDst;
    char const * pcDst = (char const *) plSrc;

    while (len--)
    {
        *pcDst++ = *pcSrc++;
    }

    return (dst);
} 

GNU .

0

memcpy glibc, . , , , memcpy :

1) , . (src % 4 == dst % 4) , .

2) . (src % 4 != dst % 4). :

Load the new word
Split it into an upper half and lower half. 
Shift the upper half down
Shift the lower half up
Add the upper half the previous lower half. 
Store the combined copy to memory
Repeat

, , . Halfword-by-halfword , , , memcpy, , / halfword, .

0

Source: https://habr.com/ru/post/1627522/


All Articles