From 821ae927144152a5122d602753907bd423aa06d0 Mon Sep 17 00:00:00 2001 From: Lei Zhang Date: Fri, 8 Jun 2018 23:47:01 +0000 Subject: Avoid undefined behavior in FX_atonum(). BUG=chromium:664730 Change-Id: Ie46221382ffed7a16366c484c249d2571c7be5c4 Reviewed-on: https://pdfium-review.googlesource.com/34696 Commit-Queue: Lei Zhang Reviewed-by: Tom Sepez --- core/fxcrt/fx_string.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/core/fxcrt/fx_string.cpp b/core/fxcrt/fx_string.cpp index 83d0e6d906..daf995560b 100644 --- a/core/fxcrt/fx_string.cpp +++ b/core/fxcrt/fx_string.cpp @@ -9,6 +9,7 @@ #include "core/fxcrt/fx_extension.h" #include "core/fxcrt/fx_string.h" +#include "third_party/base/compiler_specific.h" namespace { @@ -133,8 +134,14 @@ bool FX_atonum(const ByteStringView& strc, void* pData) { // Switch back to the int space so we can flip to a negative if we need. uint32_t uValue = integer.ValueOrDefault(0); int32_t value = static_cast(uValue); - if (bNegative) - value = -value; + if (bNegative) { + // |value| is usually positive, except in the corner case of "-2147483648", + // where |uValue| is 2147483648. When it gets casted to an int, |value| + // becomes -2147483648. For this case, avoid undefined behavior, because an + // integer cannot represent 2147483648. + static constexpr int kMinInt = std::numeric_limits::min(); + value = LIKELY(value != kMinInt) ? -value : kMinInt; + } int* pInt = static_cast(pData); *pInt = value; -- cgit v1.2.3