Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure assignment in Linux fails in ARM but succeeds in x86

I've noticed something really strange. say I've got the following structure defined

typedef struct
{
  uint32_t a;
  uint16_t b;
  uint32_t c;
} foo;

This structure is contained in a big buffer I receive from network.

The following code works in x86, but I receive SIGBUS on ARM.

extern void * buffer;
foo my_foo;
my_foo = (( foo * ) buffer)[0];

replacing the pointer dereferencing with memcpy solved the issue.

Searching about SIGBUS in ARM pointed me to the fact that this is related to memory alignment somwhow.

Can someone explain what's going on ?

like image 357
stdcall Avatar asked Jan 13 '23 06:01

stdcall


1 Answers

You said it yourself: there are memory alignment restrictions on your particular processor, and buffer is not aligned right to permit reading larger than a byte from it. The assignment is probably compiled into three moves of larger entities.

With memcpy(), there are no alignment restrictions, it has to be able to copy between any two addresses, so it does whatever is needed to implement that. Probably copying byte-by-byte until the addresses are aligned, that's a common pattern.

As an aside, I find it clearer to write your code without array indexing:

extern const void *buffer;
const foo my_foo = *(const foo *) buffer;
like image 105
unwind Avatar answered Jan 19 '23 12:01

unwind