51f0aa
Backport the check_mul_overflow_size_t function from this upstream commit:
51f0aa
51f0aa
commit 2e0bbbfbf95fc9e22692e93658a6fbdd2d4554da
51f0aa
Author: Dennis Wölfing <denniswoelfing@gmx.de>
51f0aa
Date:   Tue May 30 18:26:19 2017 -0300
51f0aa
51f0aa
    Add reallocarray function
51f0aa
51f0aa
diff --git a/malloc/malloc-internal.h b/malloc/malloc-internal.h
51f0aa
index b830d3f58fe74ca3..6ffa091ba3292901 100644
51f0aa
--- a/malloc/malloc-internal.h
51f0aa
+++ b/malloc/malloc-internal.h
51f0aa
@@ -28,5 +28,24 @@ void __malloc_fork_unlock_parent (void) internal_function attribute_hidden;
51f0aa
 /* Called in the child process after a fork.  */
51f0aa
 void __malloc_fork_unlock_child (void) internal_function attribute_hidden;
51f0aa
 
51f0aa
+/* Set *RESULT to LEFT * RIGHT.  Return true if the multiplication
51f0aa
+   overflowed.  */
51f0aa
+static inline bool
51f0aa
+check_mul_overflow_size_t (size_t left, size_t right, size_t *result)
51f0aa
+{
51f0aa
+#if __GNUC__ >= 5
51f0aa
+  return __builtin_mul_overflow (left, right, result);
51f0aa
+#else
51f0aa
+  /* size_t is unsigned so the behavior on overflow is defined.  */
51f0aa
+  *result = left * right;
51f0aa
+  size_t half_size_t = ((size_t) 1) << (8 * sizeof (size_t) / 2);
51f0aa
+  if (__glibc_unlikely ((left | right) >= half_size_t))
51f0aa
+    {
51f0aa
+      if (__glibc_unlikely (right != 0 && *result / right != left))
51f0aa
+        return true;
51f0aa
+    }
51f0aa
+  return false;
51f0aa
+#endif
51f0aa
+}
51f0aa
 
51f0aa
 #endif /* _MALLOC_PRIVATE_H */