mmap memory alignment in ARM

1.1k Views Asked by At

I'm working on a project that's being ported to ARM7 (was originally on x86). It runs on QNX. We've had a few memory alignment issues (SIGBUS error crashes) due to reading/writing with misaligned pointers. I've been fixing most alignment issues simply by replacing the pointer casting and assignment with a memcpy, but this issue I can't solve like that.

There's a memory pool shared between processes that's initialized like this:

int m_nSharedMemory = shm_open(EVENT_LIST_NAME, O_RDWR | O_CREAT, 0777);
ftruncate(m_nSharedMemory, nSize)
unsigned char* m_pMemory = (unsigned char*) mmap(0, nSize, PROT_READ | PROT_WRITE, MAP_SHARED, m_nSharedMemory, 0); 

The memory is supposed to be used like this: there's a Header at the beginning of the address space and there's an Event array afterwards. Thus, nSize = sizeof(Header) + MAX_EVENTS * sizeof(Event).

m_pHeader = (Header*)m_pMemory;
m_pEvents = (Event*)(m_pMemory + sizeof(Header));

Both Header and Event are structs with primitive types. As far as I know, this memory is not aligned, so doing m_pEvents[0].m_SomeField == 3 or m_pHeader->m_SomeField = 1 could potentially trigger a SIGBUS error. This kind of instructions are everywhere, so replacing each one with memcpy would be a real pain, I'm hoping I can get away with something else.

I've found posix_memalign which I believe could replace either shm_open or mmap, not sure which yet, but this doesn't seem to solve the issue either. For one, I still get the warning. Even ignoring the warning, I could make sure memory is aligned to sizeof(Header), but m_pEvents wouldn't be aligned.

Is there any way to prevent a SIGBUS error without making major modifications to this scheme? Right now the compiler is complaining because "cast from 'unsigned char*' to 'Header*' increases required alignment of target type" (there's a similar warning for Event), but the program is not crashing, which I really can't explain.

So, two questions: 1) Why doesn't it crash? 2) How do I make sure it never will, ideally by ensuring that memory is aligned and supressing the warning

0

There are 0 best solutions below