<thread>
: Avoid overflow in _To_absolute_time()
#5237
+1
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #5234.
We were carefully forming
decltype(_Now + _Rel_time) _Abs_time
, the common type of the given_Rel_time
(which could be coarse or fine) andchrono::steady_clock::now()
(which is nanoseconds).In this bug scenario,
_Rel_time
and therefore the common type are picoseconds.The problem was that we weren't careful about our
_Forever
constant. We were using(chrono::steady_clock::time_point::max)()
, but then converting it to the common type (implicitly in the subtraction_Forever - _Rel_time
, and in the assignment_Abs_time = _Forever
). When the common type is finer-grained, this attempts to multiply the stored value, but it's already the maximum, so we overflow.The fix is to use the common type for
_Forever
. This stores the maximum rep with the proper period of the common type, so we won't attempt to multiply it further. (When_Rel_time
is coarse, the common type is nanoseconds, so there's no change. When_Rel_time
is fine, this means that_Forever
is effectively "earlier", becauseINT64_MAX
picoseconds from the epoch happens earlier thanINT64_MAX
nanoseconds. This is exactly what we want, since we're performing our overflow check and clamping with the common type that we're about to return.)