使用memcpy进行未对齐访问

时间:2015-11-12 16:36:58

标签: c arm memcpy

我正在使用netif结构(类似于http://www.nongnu.org/lwip/structnetif.html),我得到了一个与对齐有关的问题。我注意到每个int都在一个乘数为4的地址上开始(例如0x20010db0)。但是,让我们来看看以下内容:

struct netif {

...

u8_t    hwaddr_len (at address 0x20010db8)

u8_t[8] hwaddr (at address 0x20010db9)

u8_t    mtu (at address 0x20010dc1)

...

}

根据我的理解,hwaddr_len在4个字节上对齐,hwaddr在1个字节上“对齐”(因为它是u8_t,这在4个字节(32位)上没有对齐)并且mtu在1上是“对齐”字节。之后,结构的所有其他成员再次对齐4个字节。所以,我认为这应该是好的,即使hwaddr没有在4字节多路复用器上对齐,但是当我尝试从“src”到hwaddr执行memcpy时,我得到了一个unalign访问错误。

我正在编译arm gcc编译器。有人知道它失败的原因吗?

Ps:我对ARM对齐问题知之甚少,如果我的问题看似显而易见,那就很抱歉。

编辑:

编译器版本: gcc-arm-none-eabi-4_9-2015q3

失败的部分:

lpwif_get_slla(struct lpwif *lpwif, void *lla, unsigned char lla_len)
{
WpanDeviceP dev = lpwif->dev->wpan;
unsigned char len = 0;

if (lla_len >= 8) {
    if (lpwif->eui[0] == 0xff) {
        /* Fetch WPAN Device's Long Address. */
        uint64_t addr64;
        memset(&addr64, 0xff, sizeof(addr64));
        WpanGet(dev, WpanPibAttr_macExtendedAddress, &addr64, 8);

        /* Always return address in network-byte order */
        lpwif->eui[0] = (addr64 >> 56) & 0xff;
        lpwif->eui[1] = (addr64 >> 48) & 0xff;
        lpwif->eui[2] = (addr64 >> 40) & 0xff;
        lpwif->eui[3] = (addr64 >> 32) & 0xff;
        lpwif->eui[4] = (addr64 >> 24) & 0xff;
        lpwif->eui[5] = (addr64 >> 16) & 0xff;
        lpwif->eui[6] = (addr64 >>  8) & 0xff;
        lpwif->eui[7] = (addr64 >>  0) & 0xff;
    }
    if (lpwif->eui[0] == 0xff) return 0; /* Device has no EUI-64 address. */
    if (lla) memcpy(lla, lpwif->eui, 8);
}

此方法由`lpwif_get_slla(& state-> lpwif,netif-> hwaddr,8)调用;

拆卸:

   if (lpwif->eui[0] == 0xff) return 0; /* Device has no EUI-64 address. */

 10098ac:   6bfb        ldr r3, [r7, #60]   ; 0x3c
 10098ae:   f893 3024   ldrb.w  r3, [r3, #36]   ; 0x24
 10098b2:   2bff        cmp r3, #255    ; 0xff
 10098b4:   d101        bne.n   10098ba <lpwif_get_slla+0x10e>
 10098b6:   2300        movs    r3, #0
 10098b8:   e07f        b.n 10099ba <lpwif_get_slla+0x20e>

   if (lla) memcpy(lla, lpwif->eui, 8);

 10098ba:   6bbb        ldr r3, [r7, #56]   ; 0x38
 10098bc:   2b00        cmp r3, #0
 10098be:   d006        beq.n   10098ce <lpwif_get_slla+0x122>
 10098c0:   6bfb        ldr r3, [r7, #60]   ; 0x3c
 10098c2:   3324        adds    r3, #36 ; 0x24
 10098c4:   6bb8        ldr r0, [r7, #56]   ; 0x38
 10098c6:   4619        mov r1, r3
 10098c8:   2208        movs    r2, #8
 10098ca:   4b3f        ldr r3, [pc, #252]  ; (10099c8 <lpwif_get_slla+0x21c>)
 10098cc:   4798        blx r3

    return 8;

 10098ce:   2308        movs    r3, #8
 10098d0:   e073        b.n 10099ba <lpwif_get_slla+0x20e>

1 个答案:

答案 0 :(得分:0)

尝试使用简单的for循环替换memcpy。假设它是内存对齐的,编译器可能会对它进行优化。