libstdc++: Rewrite __moneypunct_cache::_M_cache [PR104966]
authorJonathan Wakely <jwakely@redhat.com>
Thu, 17 Mar 2022 13:33:07 +0000 (13:33 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Thu, 17 Mar 2022 17:51:53 +0000 (17:51 +0000)
commit38ce4489635f2d65de965af3ec5d5c4adf7762d9
treee38771420137523877f2ba635ff114e7faa913fe
parent1d47c0512a265d4bb3ab9e56259fd1e4f4d42c75
libstdc++: Rewrite __moneypunct_cache::_M_cache [PR104966]

GCC thinks the following can lead to a buffer overflow when __ns.size()
equals zero:

  const basic_string<_CharT>& __ns = __mp.negative_sign();
  _M_negative_sign_size = __ns.size();
  __negative_sign = new _CharT[_M_negative_sign_size];
  __ns.copy(__negative_sign, _M_negative_sign_size);

This happens because operator new might be replaced with something that
writes to this->_M_negative_sign_size and so the basic_string::copy call
could use a non-zero size to write to a zero-length buffer.

The solution suggested by Richi is to cache the size in a local variable
so that the compiler knows it won't be changed between the allocation
and the copy.

This commit goes further and rewrites the whole function to use RAII and
delay all modifications of *this until after all allocations have
succeeded. The RAII helper type caches the size and copies the string
and owns the memory until told to release it.

libstdc++-v3/ChangeLog:

PR middle-end/104966
* include/bits/locale_facets_nonio.tcc
(__moneypunct_cache::_M_cache): Replace try-catch with RAII and
make all string copies before any stores to *this.
libstdc++-v3/include/bits/locale_facets_nonio.tcc