Commit 463bddf5 authored by Chad Versace's avatar Chad Versace

core: Add arithmetic functions that detect overflow

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: default avatarChad Versace <chad.versace@intel.com>
Tested-by: Emil Velikov <emil.l.velikov@gmail.com> (msvc/wgl)
Reviewed-by: Emil Velikov's avatarEmil Velikov <emil.l.velikov@gmail.com>
parent 5e8b6ed5
......@@ -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)
{
......
......@@ -26,6 +26,7 @@
#pragma once
#include <stddef.h>
#include "c99_compat.h"
#define container_of(ptr, type, member) ({ \
const __typeof__(((type *)0)->member ) *__mptr = (ptr); \
......@@ -49,6 +50,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);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment