From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 2181) id 130533857415; Mon, 9 May 2022 16:40:21 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 130533857415 MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset="utf-8" From: Jonathan Wakely To: gcc-cvs@gcc.gnu.org, libstdc++-cvs@gcc.gnu.org Subject: [gcc r9-10060] libstdc++: Fix undefined behaviour in std::string X-Act-Checkin: gcc X-Git-Author: Jonathan Wakely X-Git-Refname: refs/heads/releases/gcc-9 X-Git-Oldrev: 5ed333b0762d847ffb0096ba97e924188c766d69 X-Git-Newrev: 47c48fcfbec4d606cea7ea885323f453d8336604 Message-Id: <20220509164021.130533857415@sourceware.org> Date: Mon, 9 May 2022 16:40:21 +0000 (GMT) X-BeenThere: libstdc++-cvs@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Libstdc++-cvs mailing list List-Unsubscribe: , List-Archive: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 09 May 2022 16:40:21 -0000 https://gcc.gnu.org/g:47c48fcfbec4d606cea7ea885323f453d8336604 commit r9-10060-g47c48fcfbec4d606cea7ea885323f453d8336604 Author: Jonathan Wakely Date: Tue May 4 15:49:38 2021 +0100 libstdc++: Fix undefined behaviour in std::string This fixes a ubsan error when constructing a string with a null pointer: bits/basic_string.h:534:21: runtime error: applying non-zero offset 18446744073709551615 to null pointer The _M_construct function only cares whether the second pointer is non-null, so create a non-null value without undefined arithmetic. We can also pass the random_access_iterator_tag directly to the _M_construct function, to avoid going via the tag dispatching _M_construct_aux, because we know we have pointers not integers here. libstdc++-v3/ChangeLog: * include/bits/basic_string.h (basic_string(const CharT*, const A&)): Do not do arithmetic on null pointer. (cherry picked from commit 789c57bc5fe023fc6dc72ade4afcb0916ff788d3) Diff: --- libstdc++-v3/include/bits/basic_string.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/libstdc++-v3/include/bits/basic_string.h b/libstdc++-v3/include/bits/basic_string.h index 6c11135fa8c..5977b5cb7c0 100644 --- a/libstdc++-v3/include/bits/basic_string.h +++ b/libstdc++-v3/include/bits/basic_string.h @@ -528,7 +528,12 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11 #endif basic_string(const _CharT* __s, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) - { _M_construct(__s, __s ? __s + traits_type::length(__s) : __s+npos); } + { + const _CharT* __end = __s ? __s + traits_type::length(__s) + // We just need a non-null pointer here to get an exception: + : reinterpret_cast(__alignof__(_CharT)); + _M_construct(__s, __end, random_access_iterator_tag()); + } /** * @brief Construct string as multiple characters.