[waffle] [PATCH 07/17] core: Add arithmetic functions that detect overflow
Chad Versace
chad.versace at intel.com
Sun Jan 4 14:03:00 PST 2015
Define the function below. All act on size_t inputs.
wcore_add_size
wcore_iadd_size : in-place addition
wcore_mul_size
wcore_imul_size : in-place multiplication
Future patches will use the functions to safely calculate the 'size'
value given to malloc.
Signed-off-by: Chad Versace <chad.versace at intel.com>
---
src/waffle/core/wcore_util.c | 22 ++++++++++++++++++++++
src/waffle/core/wcore_util.h | 26 ++++++++++++++++++++++++++
2 files changed, 48 insertions(+)
diff --git a/src/waffle/core/wcore_util.c b/src/waffle/core/wcore_util.c
index deee1bf..fe4ac30 100644
--- a/src/waffle/core/wcore_util.c
+++ b/src/waffle/core/wcore_util.c
@@ -28,6 +28,28 @@
#include "wcore_error.h"
#include "wcore_util.h"
+bool
+wcore_add_size(size_t *res, size_t x, size_t y)
+{
+ if (x > SIZE_MAX - y) {
+ return false;
+ }
+
+ *res = x + y;
+ return true;
+}
+
+bool
+wcore_mul_size(size_t *res, size_t x, size_t y)
+{
+ if (x > SIZE_MAX / y) {
+ return false;
+ }
+
+ *res = x * y;
+ return true;
+}
+
void*
wcore_malloc(size_t size)
{
diff --git a/src/waffle/core/wcore_util.h b/src/waffle/core/wcore_util.h
index d2aaa27..acb46ce 100644
--- a/src/waffle/core/wcore_util.h
+++ b/src/waffle/core/wcore_util.h
@@ -49,6 +49,32 @@
return 0; \
}
+/// @brief Addition that detects arithmetic overflow.
+///
+/// If the addition would result in overflow, then return false and do not
+/// update @a res.
+bool
+wcore_add_size(size_t *res, size_t x, size_t y);
+
+/// @brief In-place variant of wcore_add_size().
+static inline bool
+wcore_iadd_size(size_t *x, size_t y) {
+ return wcore_add_size(x, *x, y);
+}
+
+/// @brief Multiplication that detects arithmetic overflow.
+///
+/// If the multiplication would result in overflow, then return false and do
+/// not update @a res.
+bool
+wcore_mul_size(size_t *res, size_t x, size_t y);
+
+/// @brief In-place variant of wcore_mul_size().
+static inline bool
+wcore_imul_size(size_t *x, size_t y) {
+ return wcore_mul_size(x, *x, y);
+}
+
/// @brief Wrapper around malloc() that emits error if allocation fails.
void*
wcore_malloc(size_t size);
--
2.2.0
More information about the waffle
mailing list