]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix unsafe comma operators in <random> [PR122062]
authorJonathan Wakely <jwakely@redhat.com>
Thu, 25 Sep 2025 16:23:28 +0000 (17:23 +0100)
committerJonathan Wakely <redi@gcc.gnu.org>
Fri, 26 Sep 2025 10:01:08 +0000 (11:01 +0100)
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>
libstdc++-v3/include/bits/random.tcc
libstdc++-v3/testsuite/26_numerics/random/piecewise_linear_distribution/cons/122062.cc [new file with mode: 0644]

index f4b9778e468e12cb1350942264b403a5679e9240..b4273f058b443df3ccabc19be11d630c76eebbf8 100644 (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);
diff --git a/libstdc++-v3/testsuite/26_numerics/random/piecewise_linear_distribution/cons/122062.cc b/libstdc++-v3/testsuite/26_numerics/random/piecewise_linear_distribution/cons/122062.cc
new file mode 100644 (file)
index 0000000..0f0caa7
--- /dev/null
@@ -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());
+}