time-rs / time

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

Arithmetic overflow occurs #621

Closed HeeillWang closed 1 year ago

HeeillWang commented 1 year 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 1 year ago

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

HeeillWang commented 1 year 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 1 year 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 1 year ago

Fixed on main.