Skip to content

Commit 843c560

Browse files
committed
Avoid unaligned access in crypto i/o
1 parent 02e5308 commit 843c560

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

src/crypto/common.h

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,57 +10,73 @@
1010
#endif
1111

1212
#include <stdint.h>
13+
#include <string.h>
1314

1415
#include "compat/endian.h"
1516

1617
uint16_t static inline ReadLE16(const unsigned char* ptr)
1718
{
18-
return le16toh(*((uint16_t*)ptr));
19+
uint16_t x;
20+
memcpy((char*)&x, ptr, 2);
21+
return le16toh(x);
1922
}
2023

2124
uint32_t static inline ReadLE32(const unsigned char* ptr)
2225
{
23-
return le32toh(*((uint32_t*)ptr));
26+
uint32_t x;
27+
memcpy((char*)&x, ptr, 4);
28+
return le32toh(x);
2429
}
2530

2631
uint64_t static inline ReadLE64(const unsigned char* ptr)
2732
{
28-
return le64toh(*((uint64_t*)ptr));
33+
uint64_t x;
34+
memcpy((char*)&x, ptr, 8);
35+
return le64toh(x);
2936
}
3037

3138
void static inline WriteLE16(unsigned char* ptr, uint16_t x)
3239
{
33-
*((uint16_t*)ptr) = htole16(x);
40+
uint16_t v = htole16(x);
41+
memcpy(ptr, (char*)&v, 2);
3442
}
3543

3644
void static inline WriteLE32(unsigned char* ptr, uint32_t x)
3745
{
38-
*((uint32_t*)ptr) = htole32(x);
46+
uint32_t v = htole32(x);
47+
memcpy(ptr, (char*)&v, 4);
3948
}
4049

4150
void static inline WriteLE64(unsigned char* ptr, uint64_t x)
4251
{
43-
*((uint64_t*)ptr) = htole64(x);
52+
uint64_t v = htole64(x);
53+
memcpy(ptr, (char*)&v, 8);
4454
}
4555

4656
uint32_t static inline ReadBE32(const unsigned char* ptr)
4757
{
48-
return be32toh(*((uint32_t*)ptr));
58+
uint32_t x;
59+
memcpy((char*)&x, ptr, 4);
60+
return be32toh(x);
4961
}
5062

5163
uint64_t static inline ReadBE64(const unsigned char* ptr)
5264
{
53-
return be64toh(*((uint64_t*)ptr));
65+
uint64_t x;
66+
memcpy((char*)&x, ptr, 8);
67+
return be64toh(x);
5468
}
5569

5670
void static inline WriteBE32(unsigned char* ptr, uint32_t x)
5771
{
58-
*((uint32_t*)ptr) = htobe32(x);
72+
uint32_t v = htobe32(x);
73+
memcpy(ptr, (char*)&v, 4);
5974
}
6075

6176
void static inline WriteBE64(unsigned char* ptr, uint64_t x)
6277
{
63-
*((uint64_t*)ptr) = htobe64(x);
78+
uint64_t v = htobe64(x);
79+
memcpy(ptr, (char*)&v, 8);
6480
}
6581

6682
#endif // BITCOIN_CRYPTO_COMMON_H

0 commit comments

Comments
 (0)