Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unaligned access condition and how to detect it using gcc?

I'm currently working on heap memory allocation schemes. I want to detect unaligned access's without actual hardware ( with using gcc ).

First, I use arm-none-eabi-gcc as a compiler and my working station is ubuntu 16.04. I tried to detect unaligned access with using this compiler.

I expect that following code is valid in terms of alignment.

int main ( int argc, char ** argv )
{
    int32_t volatile * const ptr = ( int32_t volatile * ) 0x20000000;
    *ptr = 3;
    *(ptr + 1 ) = 4;
    *(ptr + 2 ) = 5;
    *(ptr + 3 ) = 6;

    return 0;
}

But I expect that following code is not valid in terms of alignment.

int main ( int argc, char** argv )
{
    int32_t volatile * const ptr = ( int32_t volatile * ) 0x20000003;
    *ptr = 3;
    *(ptr + 1 ) = 4;
    *(ptr + 2 ) = 5;
    *(ptr + 3 ) = 6;

    return 0;
}

I convert these C codes to assembly using following lines respectively: arm-none-eabi-gcc -O0 -o main_0.s -S ../main.c, arm-none-eabi-gcc -O0 -o main_3.s -S ../main.c

When I compare the assembly codes, there is no difference between these assembly codes. Also GCC don't show any warning.

So, Why these assembly codes is same ? How can I generate unaligned access condition ? Is there any way to detect unaligned access condition with using GCC ?

Thanks

like image 270
user3104363 Avatar asked Feb 01 '26 13:02

user3104363


1 Answers

Since in ARM, the data address is always a register value (unless you're performing a PC relative load, and in the case of the PC the lower bits are special), there is nothing in the assembly to distinguish between one word load and another.

The 'problem' with unaligned accesses stems from the implementations of the architecture, and the interactions of the processor with it's memory interfaces. Even when an unaligned access is supported, it will be slower, so the processor can be configured to trap them at run time.

The code you provide will perform unaligned accesses, but this will run fine on many cores. This is assuming that the compiler isn't detecting undefined behaviour (which clearly it does not). I'm assuming that the pointer is actually initialised differently when you compile your example.

You can enable or disable the use of unaligned access features within libraries using the -munaligned-access switch see the Keil description here, but all that is doing is defining a macro, not enabling any run-time or compile time checks.

In general, alignment issues will show up at runtime just as much as at compile time - and in order to detect them at runtime you will need an instruction set simulator (with traps that can be enabled).

like image 127
Sean Houlihane Avatar answered Feb 04 '26 05:02

Sean Houlihane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!