From 2501e86acda2905e50012f7e9fc1942517c1237d Mon Sep 17 00:00:00 2001 From: Jonas Devlieghere Date: Tue, 30 Jun 2020 12:40:25 -0700 Subject: [PATCH] [lldb/Scalar] Fix undefined behavior Fix UBSan error detected in TestDataFormatterObjCCF.py and TestDataFormatterObjCNSDate.py: Scalar.cpp:698:27: runtime error: -4.96303e+08 is outside the range of representable values of type 'unsigned long long'. --- lldb/source/Utility/Scalar.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lldb/source/Utility/Scalar.cpp b/lldb/source/Utility/Scalar.cpp index 610c935409ac..d275f6211e5c 100644 --- a/lldb/source/Utility/Scalar.cpp +++ b/lldb/source/Utility/Scalar.cpp @@ -736,7 +736,17 @@ long long Scalar::SLongLong(long long fail_value) const { } unsigned long long Scalar::ULongLong(unsigned long long fail_value) const { - return GetAsUnsigned(fail_value); + switch (m_type) { + case e_double: { + double d_val = m_float.convertToDouble(); + llvm::APInt rounded_double = + llvm::APIntOps::RoundDoubleToAPInt(d_val, sizeof(ulonglong_t) * 8); + return static_cast( + (rounded_double.zextOrTrunc(sizeof(ulonglong_t) * 8)).getZExtValue()); + } + default: + return GetAsUnsigned(fail_value); + } } llvm::APInt Scalar::SInt128(const llvm::APInt &fail_value) const {