Compare commits

..

3 Commits

Author SHA1 Message Date
26b44e651d
Change safe_{sub,add,mul} so they perform the operation only once
All checks were successful
continuous-integration/drone/push Build is passing
2022-12-06 15:47:59 +01:00
b338126854
Heap: Use safe_mul in kcalloc() 2022-12-06 15:44:21 +01:00
e91c04b1d1
luna: Introduce safe arithmetic operations, which return an error if an operation would overflow 2022-12-06 15:40:18 +01:00
2 changed files with 46 additions and 2 deletions

View File

@ -5,6 +5,7 @@
#include "memory/KernelVM.h"
#include "memory/MemoryManager.h"
#include <luna/Alignment.h>
#include <luna/SafeArithmetic.h>
#include <luna/String.h>
#include <luna/SystemError.h>
@ -332,8 +333,7 @@ Result<void*> krealloc(void* ptr, usize size)
Result<void*> kcalloc(usize nmemb, usize size)
{
// FIXME: Check for overflows.
const usize realsize = nmemb * size;
const usize realsize = TRY(safe_mul(nmemb, size));
void* const ptr = TRY(kmalloc(realsize));
return memset(ptr, 0, realsize);
}

View File

@ -0,0 +1,44 @@
#pragma once
#include <luna/Result.h>
template <typename T> constexpr bool add_will_overflow(T a, T b)
{
return __builtin_add_overflow_p(a, b, (T)0);
}
template <typename T> constexpr bool sub_will_overflow(T a, T b)
{
return __builtin_sub_overflow_p(a, b, (T)0);
}
template <typename T> constexpr bool mul_will_overflow(T a, T b)
{
return __builtin_mul_overflow_p(a, b, (T)0);
}
template <typename T> Result<T> safe_add(T a, T b)
{
T result;
if (__builtin_add_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}
template <typename T> Result<T> safe_sub(T a, T b)
{
T result;
if (__builtin_sub_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}
template <typename T> Result<T> safe_mul(T a, T b)
{
T result;
if (__builtin_mul_overflow(a, b, &result)) return err(EOVERFLOW);
return result;
}