Commit bac4f798 authored by Guido Casati's avatar Guido Casati

Fix misalignment issues in TLVEncoder macros ENCODE_U16, ENCODE_U24

This commit resolves undefined behaviour runtime errors related
to misaligned memory access. E.g.

> openair3/NAS/COMMON/IES/FGSMobileIdentity.c:193:3:
> runtime error: store to misaligned address 0x608000021e2b for type 'uint16_t',
> which requires 2 byte alignment 0x608000021e2b: note: pointer points here 00 f1 ...

* ENCODE_U24: safely encode 24-bit values into a buffer
  by using memcpy to copy 3 bytes in network byte order (big-endian).
* ENCODE_U16: safely encodes a 16-bit value into a buffer, handling
  misalignment by memcpy 2 bytes to buffer in network byte order (big-endian).
parent 2ec8fefb
......@@ -28,13 +28,25 @@
*(uint8_t*)(buffer) = value; \
size += sizeof(uint8_t)
#define ENCODE_U16(buffer, value, size) \
*(uint16_t*)(buffer) = htons(value); \
size += sizeof(uint16_t)
#define ENCODE_U24(buffer, value, size) \
*(uint32_t*)(buffer) = htonl(value); \
size += sizeof(uint8_t) + sizeof(uint16_t)
/* Safely encodes a 16-bit value into a buffer, handling
misalignment by memcpy 2 bytes to buffer in network
byte order (big-endian). */
#define ENCODE_U16(buffer, value, size) \
do { \
uint16_t _val = htons(value); \
memcpy((buffer), &_val, sizeof(uint16_t)); \
size += sizeof(uint16_t); \
} while (0)
/* Safely encodes a 24-bit value into a buffer, handling
misalignment by using htonl and memcpy to copy 3 bytes
in network byte order (big-endian). */
#define ENCODE_U24(buffer, value, size) \
do { \
uint32_t _val = htonl(value); \
memcpy((buffer), ((uint8_t*)&_val) + 1, 3); \
size += sizeof(uint8_t) + sizeof(uint16_t); \
} while (0)
#define ENCODE_U32(buffer, value, size) \
{ \
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment