Skip to content

Commit f86e8a6

Browse files
carlescufinashif
authored andcommitted
random: rand32_timer: Avoid alignment faults by using memcpy
The previous implementation assumed that the dst pointer was always aligned to a 4-byte boundary in platforms that require alignment for storage of 32-bit integers. Since this is required for certain platforms (eg. Arm Cortex-M0), use memcpy() instead, which always takes alignment into account. Fixes #33969. Signed-off-by: Carles Cufi <[email protected]>
1 parent 286d9c2 commit f86e8a6

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

subsys/random/rand32_timer.c

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,20 +62,16 @@ uint32_t z_impl_sys_rand32_get(void)
6262

6363
void z_impl_sys_rand_get(void *dst, size_t outlen)
6464
{
65-
uint32_t len = 0;
66-
uint32_t blocksize = 4;
65+
uint8_t *udst = dst;
66+
uint32_t blocksize;
6767
uint32_t ret;
68-
uint32_t *udst = (uint32_t *)dst;
6968

70-
while (len < outlen) {
69+
while (outlen) {
7170
ret = sys_rand32_get();
72-
if ((outlen-len) < sizeof(ret)) {
73-
blocksize = len;
74-
(void)memcpy(udst, &ret, blocksize);
75-
} else {
76-
(*udst++) = ret;
77-
}
78-
len += blocksize;
71+
blocksize = MIN(outlen, sizeof(ret));
72+
(void)memcpy((void *)udst, &ret, blocksize);
73+
udst += blocksize;
74+
outlen -= blocksize;
7975
}
8076
}
8177
#endif /* __GNUC__ */

0 commit comments

Comments
 (0)