Skip to content

Commit

Permalink
libc: Fix absolute_timespec_from_timespec overflow.
Browse files Browse the repository at this point in the history
A legacy library has uncovered an overflow in this newly introduced function.
absolute_timespec_from_timespec blindly adds a relative timespec to the current
timespec, ignoring the possibility of tv_sec overflowing.

This was produced by calling pthread_cond_timedwait_relative_np with a filled
(to maximum values) timespec to create a faux 'infinite timeout'.

This is fixed by clamping the value as high as we can determine is safe.
  • Loading branch information
MWisBest authored and andi34 committed Sep 17, 2016
1 parent a8fbd76 commit 1a60b4c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
13 changes: 13 additions & 0 deletions libc/bionic/bionic_time_conversions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,23 @@ void timeval_from_timespec(timeval& tv, const timespec& ts) {

void absolute_timespec_from_timespec(timespec& abs_ts, const timespec& ts, clockid_t clock) {
clock_gettime(clock, &abs_ts);
time_t tmp_tv_sec = abs_ts.tv_sec;
abs_ts.tv_sec += ts.tv_sec;
abs_ts.tv_nsec += ts.tv_nsec;
if (abs_ts.tv_nsec >= NS_PER_S) {
abs_ts.tv_nsec -= NS_PER_S;
abs_ts.tv_sec++;
}
// With a large relative timespec we might overflow.
// Because time_t is arbitrary, we should be fancy handling this.
if (abs_ts.tv_sec < tmp_tv_sec) {
if (sizeof(time_t) == sizeof(int32_t)) {
abs_ts.tv_sec = INT32_MAX;
} else if (sizeof(time_t) == sizeof(int64_t)) {
abs_ts.tv_sec = INT64_MAX;
} else {
// Just take the largest of the two initial values and hope for the best.
abs_ts.tv_sec = MAX(tmp_tv_sec, ts.tv_sec);
}
}
}
1 change: 1 addition & 0 deletions libc/private/bionic_time_conversions.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include <errno.h>
#include <time.h>
#include <sys/cdefs.h>
#include <sys/param.h>

#include "private/bionic_constants.h"

Expand Down

0 comments on commit 1a60b4c

Please sign in to comment.