libstdc++: Fix unsafe comma operators in <random> [PR122062]

This fixes a 'for' loop in std::piecewise_linear_distribution that
increments two iterators with a comma operator between them, making it
vulnerable to evil overloads of the comma operator.

It also changes a 'for' loop used by some other distributions, even
though those are only used with std::vector<double>::iterator and so
won't find any overloaded commas.

libstdc++-v3/ChangeLog:

	PR libstdc++/122062
	* include/bits/random.tcc (__detail::__normalize): Use void cast
	for operands of comma operator.
	(piecewise_linear_distribution): Likewise.
	* testsuite/26_numerics/random/piecewise_linear_distribution/cons/122062.cc:
	New test.

Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
Reviewed-by: Hewill Kang <hewillk@gmail.com>
This commit is contained in:
Jonathan Wakely
2025-09-25 17:23:28 +01:00
committed by Jonathan Wakely
parent 947b22d9d0
commit 11ce485bcf
2 changed files with 18 additions and 2 deletions

View File

@@ -83,7 +83,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
__normalize(_InputIterator __first, _InputIterator __last,
_OutputIterator __result, const _Tp& __factor)
{
for (; __first != __last; ++__first, ++__result)
for (; __first != __last; ++__first, (void) ++__result)
*__result = *__first / __factor;
return __result;
}
@@ -3201,7 +3201,7 @@ namespace __detail
_InputIteratorW __wbegin)
: _M_int(), _M_den(), _M_cp(), _M_m()
{
for (; __bbegin != __bend; ++__bbegin, ++__wbegin)
for (; __bbegin != __bend; ++__bbegin, (void) ++__wbegin)
{
_M_int.push_back(*__bbegin);
_M_den.push_back(*__wbegin);

View File

@@ -0,0 +1,16 @@
// { dg-do compile { target c++11 } }
// PR libstdc++/122062
// piecewise_linear_distribution(firstB, lastB, firstW) invokes comma operator
#include <random>
#include <testsuite_iterators.h>
void
test_pr122062()
{
double b[1]{};
double w[1]{};
__gnu_test::random_access_container<double> B(b), W(w);
std::piecewise_linear_distribution<double> p(B.begin(), B.end(), W.begin());
}