Re: [PATCH v3] posix-cpu-timers: Avoid undefined behaviour in timespec64_to_ns()

From: Arnd Bergmann
Date: Wed Mar 06 2019 - 05:39:13 EST


On Wed, Mar 6, 2019 at 9:41 AM Xiongfeng Wang <wangxiongfeng2@xxxxxxxxxx> wrote:
>
>
> diff --git a/kernel/time/posix-timers.c b/kernel/time/posix-timers.c
> index 0e84bb7..4b57566 100644
> --- a/kernel/time/posix-timers.c
> +++ b/kernel/time/posix-timers.c
> @@ -856,6 +856,10 @@ static int do_timer_settime(timer_t timer_id, int flags,
> if (!timespec64_valid(&new_spec64->it_interval) ||
> !timespec64_valid(&new_spec64->it_value))
> return -EINVAL;
> + if (new_spec64->it_interval.tv_sec > KTIME_SEC_MAX)
> + new_spec64->it_interval.tv_sec = KTIME_SEC_MAX;
> + if (new_spec64->it_value.tv_sec > KTIME_SEC_MAX)
> + new_spec64->it_value.tv_sec = KTIME_SEC_MAX;
>

I looked at the calculation we do later, and I think this can still overflow
if tv_nsec is too large. The largest timespec value we can support is

(struct timespec64) { .tv_sec = 9223372036, .tv_nsec = 854775807 }

Your patch caps the tv_sec value to 9223372036, but it does not
cap the tv_nsec. The easiest fix would be to always set tv_nsec
to 0 if tv_sec>=9223372036, or a more correct calculation would
have to limit tv_nsec if tv_sec==9223372036. I don't know if that
matters or not (it should not, unless we explicitly compare the
ktime_t for equality with KTIME_MAX later).

Arnd