time-rs / time

The most used Rust library for date and time handling.
https://time-rs.github.io
Apache License 2.0
1.06k stars 261 forks source link

Arithmetic overflow occurs #621

Closed HeeillWang closed 10 months ago

HeeillWang commented 10 months ago

I executed fuzzing, and found arithmetic overflow bug on date.rs. Tested on 0.3.22 but would be reproduced on latest version.

Thread '<unnamed>' panicked at 'attempt to add with overflow'. time-0.3.22/src/date.rs:1018
impl Add<StdDuration> for Date {
    type Output = Self;

    fn add(self, duration: StdDuration) -> Self::Output {
        Self::from_julian_day(
            self.to_julian_day() + (duration.as_secs() / Second.per(Day) as u64) as i32,
        )
        .expect("overflow adding duration to date")
    }
}

Reproduce crash with :

let timeout : std::time::Duration = Duration::from_secs(18157382926370278155); // put some big number
let start_time  = OffsetDateTime::now_utc();
let final_time  = start_time + timeout;   // overflow!
jhpratt commented 10 months ago

This is deliberate, as indicated by the error message. The resulting value cannot be represented in the data format.

HeeillWang commented 10 months ago

@jhpratt This is not invoked via expect(). Note that panic message is printed by rustc, not expect(). The add operation self.to_julian_day() + (duration.as_secs() / Second.per(Day) as u64) as i32 makes the overflow.

Is it deliberate as well?

jhpratt commented 10 months ago

Ah, I understand what you're saying now. That wasn't immediately obvious to me.

I suspect that this may lead to a bug in release mode, as wrapping arithmetic would occur in that instance. I'll have to switch to using checked arithmetic instead if I can confirm this.

jhpratt commented 10 months ago

Fixed on main.