[libc] Fix UBSan error after D147171
authorAlex Brachet <abrachet@google.com>
Fri, 31 Mar 2023 15:18:35 +0000 (15:18 +0000)
committerAlex Brachet <abrachet@google.com>
Fri, 31 Mar 2023 15:18:35 +0000 (15:18 +0000)
Differential Revision: https://reviews.llvm.org/D147258

libc/src/__support/CMakeLists.txt
libc/src/__support/str_to_integer.h

index 30bbf3a..51230c6 100644 (file)
@@ -72,6 +72,7 @@ add_header_library(
     .str_to_num_result
     libc.src.errno.errno
     libc.src.__support.CPP.limits
+    libc.src.__support.CPP.type_traits
     libc.src.__support.common
 )
 
index 965ac11..b7af39d 100644 (file)
@@ -10,6 +10,7 @@
 #define LIBC_SRC_SUPPORT_STR_TO_INTEGER_H
 
 #include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/type_traits.h"
 #include "src/__support/common.h"
 #include "src/__support/ctype_utils.h"
 #include "src/__support/str_to_num_result.h"
@@ -142,7 +143,9 @@ LIBC_INLINE StrToNumResult<T> strtointeger(const char *__restrict src,
       return {cpp::numeric_limits<T>::min(), str_len, error_val};
   }
 
-  return {is_positive ? static_cast<T>(result) : -static_cast<T>(result),
+  return {is_positive
+              ? static_cast<T>(result)
+              : static_cast<T>(-static_cast<cpp::make_unsigned_t<T>>(result)),
           str_len, error_val};
 }