本文介绍了为什么GCC会为ARM Cortex-A9产生非法的未对齐访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:ARM Cortex-A9
GCC版本:4.9.2

Target: ARM Cortex-A9
GCC Version: 4.9.2

大家好,

我对GCC产生内核有问题,该内核会由于未对齐的访问而导致数据中止.我隔离出了一段显示问题的代码.我不知道如何使GCC正确处理此问题.帮助将不胜感激!

I have a problem with GCC producing core that causes data aborts because of unaligned accesses. I isolated a piece of code that shows the problem. I don't know how to make GCC to handle this correctly. Help would be appreciated!

struct B
{
    char c1;
    char c2;
    char c3;
    char c4;
};

struct A
{
    char c;
    struct B b;
    char c2;
};

int main(int argc, char** argv)
{
    struct A a;
    a.c2 = 42;    // Works fine
    a.b.c1 = 42   // Works fine, too
    struct B b;
    b = a.b;      // Crashes because of unaligned access
    return 0;
}

内存布局如下:

a           struct A    48  S:0x3FFFFFE0    R/W
  c         char        8   S:0x3FFFFFE0    R/W
  b         struct B    32  S:0x3FFFFFE1    R/W
    c1      char        8   S:0x3FFFFFE1    R/W
    c2      char        8   S:0x3FFFFFE2    R/W
    c3      char        8   S:0x3FFFFFE3    R/W
    c4      char        8   S:0x3FFFFFE4    R/W
  c2        char        8   S:0x3FFFFFE5    R/W

现在可以使用前两个分配命令,例如

Now for the first two assignments commands like

a.c2 = 42;     : STRB     r3,[r11,#-7]       with r11 = 0x3FFFFFEC

被生产出来并且它们工作正常.

are produced and they work fine.

但是,对于最后一次分配,

However, for the last assignment,

b = a.b;       : LDR      r0,[r2,#0]         with r2 = 0x3FFFFFE1

产生

,由于访问未对齐,导致数据中止.GCC不会发出任何警告或其他任何警告.

is produced what results in a data abort because of unaligned access.GCC issues no warnings or anything about that.

有人知道如何解决这个问题吗?

Does anyone know how to fix that?

顺便说一句,在我的项目中,所有struct声明中的对齐属性都不是一个选项.

Btw., alignment attributes in all struct declarations is not an option in my project.

推荐答案

如果使用-mno-unaligned-access,则会得到正确的结果.

If you use -mno-unaligned-access you get the correct result.

令我惊讶的是,它默认情况下没有执行此操作,因为在手臂上进行未对齐的内存访问常常是错误的.

It was a surprise to me that it didn't do this by default as it's so oftenly wrong to do unaligned memory access on arm.

这篇关于为什么GCC会为ARM Cortex-A9产生非法的未对齐访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 08:22