From 17b8dd6476cf663517393fd866e888af2494bdb2 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Wed, 6 Dec 2023 08:59:01 -0800 Subject: [PATCH] Fix DurationToMilliseconds mult overflow PiperOrigin-RevId: 588443477 --- src/google/protobuf/util/time_util.cc | 6 ++++-- src/google/protobuf/util/time_util_test.cc | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc index e27b0d17b5..2d62eca903 100644 --- a/src/google/protobuf/util/time_util.cc +++ b/src/google/protobuf/util/time_util.cc @@ -311,11 +311,13 @@ int64_t TimeUtil::DurationToNanoseconds(const Duration& duration) { } int64_t TimeUtil::DurationToMicroseconds(const Duration& duration) { - return RoundTowardZero(DurationToNanoseconds(duration), kNanosPerMicrosecond); + return DurationToSeconds(duration) * kMicrosPerSecond + + RoundTowardZero(duration.nanos(), kNanosPerMicrosecond); } int64_t TimeUtil::DurationToMilliseconds(const Duration& duration) { - return RoundTowardZero(DurationToNanoseconds(duration), kNanosPerMillisecond); + return DurationToSeconds(duration) * kMillisPerSecond + + RoundTowardZero(duration.nanos(), kNanosPerMillisecond); } int64_t TimeUtil::DurationToSeconds(const Duration& duration) { diff --git a/src/google/protobuf/util/time_util_test.cc b/src/google/protobuf/util/time_util_test.cc index 0892eea85a..98a643ef80 100644 --- a/src/google/protobuf/util/time_util_test.cc +++ b/src/google/protobuf/util/time_util_test.cc @@ -145,6 +145,12 @@ TEST(TimeUtilTest, DurationIntegerConversion) { 1, TimeUtil::DurationToMilliseconds(TimeUtil::MillisecondsToDuration(1))); EXPECT_EQ(-1, TimeUtil::DurationToMilliseconds( TimeUtil::MillisecondsToDuration(-1))); + // Test overflow issue + EXPECT_EQ(315576000000000, TimeUtil::DurationToMilliseconds( + TimeUtil::SecondsToDuration(315576000000))); + // Test overflow issue + EXPECT_EQ(315576000000000000, TimeUtil::DurationToMicroseconds( + TimeUtil::SecondsToDuration(315576000000))); EXPECT_EQ(1, TimeUtil::DurationToSeconds(TimeUtil::SecondsToDuration(1))); EXPECT_EQ(-1, TimeUtil::DurationToSeconds(TimeUtil::SecondsToDuration(-1))); EXPECT_EQ(1, TimeUtil::DurationToMinutes(TimeUtil::MinutesToDuration(1)));