Skip to content

Commit da7be45

Browse files
committed
Avoid overflow during conversion from ms to ticks.
E.g. when having predivSync=255, a value of subSeconds=2^24 (still well below UINT32_MAX and thus using the 32bit computation branch) would be multiplied by 256 and result in an overflow during computation. In fact, 2^24 ms is about 4 hours 40 minutes.
1 parent ac3953d commit da7be45

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

Diff for: src/rtc.c

+4-7
Original file line numberDiff line numberDiff line change
@@ -947,14 +947,11 @@ void RTC_StartAlarm64(alarm_t name, uint8_t day, uint8_t hours, uint8_t minutes,
947947
if ((initMode == MODE_BINARY_ONLY) || (initMode == MODE_BINARY_MIX)) {
948948
/* We have an SubSecond alarm to set in RTC_BINARY_MIX or RTC_BINARY_ONLY mode */
949949
/* The subsecond in ms is converted in ticks unit 1 tick is 1000 / fqce_apre
950-
* It keeps the subsecond accuracy on 64 bits if needed
950+
* For the conversion, we keep the accuracy on 64 bits, since otherwise we might
951+
* have an overflow even though the conversion result still fits in 32 bits.
951952
*/
952-
if (subSeconds > (uint64_t)UINT32_MAX) {
953-
uint64_t tmp = (subSeconds * (uint64_t)(predivSync + 1)) / (uint64_t)1000;
954-
RTC_AlarmStructure.AlarmTime.SubSeconds = (uint32_t)UINT32_MAX - (uint32_t)tmp;
955-
} else {
956-
RTC_AlarmStructure.AlarmTime.SubSeconds = (uint32_t)((uint32_t)UINT32_MAX - (uint32_t)(subSeconds * (predivSync + 1)) / 1000);
957-
}
953+
uint64_t tmp = (subSeconds * (uint64_t)(predivSync + 1)) / (uint64_t)1000;
954+
RTC_AlarmStructure.AlarmTime.SubSeconds = (uint32_t)UINT32_MAX - (uint32_t)tmp;
958955
} else
959956
#endif /* RTC_ICSR_BIN */
960957
{

0 commit comments

Comments
 (0)