mu-zero-HYPERLOOP / canzero

Control Panel of Mu-Zero Hyperloop Season 4
https://mu-zero.de
6 stars 0 forks source link

Unaligned memory accesses are undefined behavior #156

Closed kistenklaus closed 2 months ago

kistenklaus commented 4 months ago

So i actually also didn't know this about C, but given the example.

uint8_t x[8];
*((uint64_t*)x) = 0;

the write or read at the second line is actually undefined behavior, which depends on the target platform. I always assumed that unaligned accesses are just bad for performance and the compiler will have to include special instructions to handle alignment edge cases, but for the cortexm7 platform on the teensy 4.1 this actually crashes the application completely. (Pretty bad).

The easiest fix is probably to ensure the alignment of a couple of variables.

int x __attribute__ ((aligned (16))) = 0;

This includes a couple of points in our code:

Serialization

During serialization we write *((uint64_t*)data) = 0; this is undefined behavior if data is is not aligned on a 8byte boundary. Data is from canzero_frame. So it's probably a good idea to change the member alignement of uint8_t data[8];to

 __attribute__((aligned(alignof(uint64_t)))) uint8_t data[8]; 

Fragmentation

Get resp fragmentation buffers should also be aligned to the 8 byte boundaries

kistenklaus commented 3 months ago

Should be fixed as we don't have any issues, but might still arise from structured stream data not sure has to be tested

arrowtip commented 2 months ago

Not needed for fragmentation buffers. They are uint32_t and we never write to them as anything else.