From 6d46346eb93d5032c08cf1e39023b5d57260a766 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Tue, 29 Aug 2017 12:21:29 -0400 Subject: Detect integer overflow/underflow --- libqpdf/QUtil.cc | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) (limited to 'libqpdf/QUtil.cc') diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index 10ca7d3b..32855bbf 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -81,11 +81,40 @@ QUtil::double_to_string(double num, int decimal_places) long long QUtil::string_to_ll(char const* str) { + errno = 0; #ifdef _MSC_VER - return _strtoi64(str, 0, 10); + long long result = _strtoi64(str, 0, 10); #else - return strtoll(str, 0, 10); + long long result = strtoll(str, 0, 10); #endif + if (errno == ERANGE) + { + throw std::runtime_error( + std::string("overflow/underflow converting ") + str + + " to 64-bit integer"); + } + return result; +} + +int +QUtil::string_to_int(char const* str) +{ + errno = 0; + long long_val = strtol(str, 0, 10); + if (errno == ERANGE) + { + throw std::runtime_error( + std::string("overflow/underflow converting ") + str + + " to long integer"); + } + int result = static_cast(long_val); + if (static_cast(result) != long_val) + { + throw std::runtime_error( + std::string("overflow/underflow converting ") + str + + " to integer"); + } + return result; } unsigned char* -- cgit v1.2.3-54-g00ecf