Skip to content

Commit afbc932

Browse files
nordic-krchcfriedt
authored andcommitted
lib: posix: clock: Prevent early overflows
Algorithm was converting uptime to nanoseconds which can easily lead to overflows. Changed algorithm to use milliseconds and nanoseconds for remainder only. Signed-off-by: Krzysztof Chruscinski <[email protected]>
1 parent a28aa01 commit afbc932

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

lib/posix/clock.c

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ static struct k_spinlock rt_clock_base_lock;
2727
*/
2828
int z_impl_clock_gettime(clockid_t clock_id, struct timespec *ts)
2929
{
30-
uint64_t elapsed_nsecs;
3130
struct timespec base;
3231
k_spinlock_key_t key;
3332

@@ -48,9 +47,13 @@ int z_impl_clock_gettime(clockid_t clock_id, struct timespec *ts)
4847
return -1;
4948
}
5049

51-
elapsed_nsecs = k_ticks_to_ns_floor64(k_uptime_ticks());
52-
ts->tv_sec = (int32_t) (elapsed_nsecs / NSEC_PER_SEC);
53-
ts->tv_nsec = (int32_t) (elapsed_nsecs % NSEC_PER_SEC);
50+
uint64_t ticks = k_uptime_ticks();
51+
uint64_t elapsed_secs = k_ticks_to_ms_floor64(ticks) / MSEC_PER_SEC;
52+
uint64_t nremainder = ticks - k_ms_to_ticks_floor64(MSEC_PER_SEC * elapsed_secs);
53+
54+
ts->tv_sec = (time_t) elapsed_secs;
55+
/* For ns 32 bit conversion can be used since its smaller than 1sec. */
56+
ts->tv_nsec = (int32_t) k_ticks_to_ns_floor32(nremainder);
5457

5558
ts->tv_sec += base.tv_sec;
5659
ts->tv_nsec += base.tv_nsec;

0 commit comments

Comments
 (0)