[libcxx-commits] [libcxx] [libc++] Fix wraparound issue with -fsanitize=integer in string operator>> (PR #106263)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Tue Aug 27 11:17:16 PDT 2024


https://github.com/ldionne created https://github.com/llvm/llvm-project/pull/106263

Fixes #106261
rdar://133991190

>From 82371525c5b169b704e3bd3288f1eaab4945803c Mon Sep 17 00:00:00 2001
From: Louis Dionne <ldionne.2 at gmail.com>
Date: Tue, 27 Aug 2024 14:13:26 -0400
Subject: [PATCH] [libc++] Fix wraparound issue with -fsanitize=integer in
 string operator>>

Fixes #106261
rdar://133991190
---
 libcxx/include/istream | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/libcxx/include/istream b/libcxx/include/istream
index d2b577a9ad9efc..84cb0ac9d9f252 100644
--- a/libcxx/include/istream
+++ b/libcxx/include/istream
@@ -1211,12 +1211,12 @@ operator>>(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _
     try {
 #endif
       __str.clear();
-      streamsize __n = __is.width();
-      if (__n <= 0)
-        __n = __str.max_size();
-      if (__n <= 0)
-        __n = numeric_limits<streamsize>::max();
-      streamsize __c            = 0;
+      using _Size = typename basic_string<_CharT, _Traits, _Allocator>::size_type;
+      static_assert(numeric_limits<_Size>::max() >= numeric_limits<streamsize>::max(),
+                    "Stream width could be too large to be represented in the string's size_type");
+      streamsize const __width  = __is.width();
+      _Size const __n           = __width <= 0 ? __str.max_size() : static_cast<_Size>(__width);
+      _Size __c                 = 0;
       const ctype<_CharT>& __ct = std::use_facet<ctype<_CharT> >(__is.getloc());
       while (__c < __n) {
         typename _Traits::int_type __i = __is.rdbuf()->sgetc();



More information about the libcxx-commits mailing list