Skip to content

Instantly share code, notes, and snippets.

@gradbot
Last active March 20, 2020 03:29
Show Gist options
  • Save gradbot/e48a4f6790c136d13468521cc6bc2b37 to your computer and use it in GitHub Desktop.
Save gradbot/e48a4f6790c136d13468521cc6bc2b37 to your computer and use it in GitHub Desktop.
Overloads global new with random data for help with finding uninitialized data use.
#include <chrono>
struct XorShift128State
{
uint32_t a, b, c, d;
};
/* The state array must be initialized to not be all zero */
uint32_t xorshift128(XorShift128State *state)
{
/* Algorithm "xor128" from p. 5 of Marsaglia, "Xorshift RNGs" */
uint32_t t = state->d;
uint32_t const s = state->a;
state->d = state->c;
state->c = state->b;
state->b = s;
t ^= t << 11;
t ^= t >> 8;
return state->a = t ^ s ^ (s >> 19);
}
void* operator new(size_t size)
{
static size_t calls = 0;
static size_t total = 0;
static long long seed = std::chrono::steady_clock::now().time_since_epoch().count();
static XorShift128State xorState = { static_cast<uint32_t>(seed), static_cast<uint32_t>(seed >> 32), 0, 0 };
calls++;
total += size;
auto p = malloc(size);
const size_t words = size / 4;
for (size_t i = 0; i < words; i++)
{
static_cast<uint32_t*>(p)[i] = xorshift128(&xorState);
}
const size_t remainder = size % 4;
if (remainder > 0)
{
uint32_t value = xorshift128(&xorState);
for (size_t i = size - remainder; i < size; i++)
{
static_cast<uint8_t*>(p)[i] = static_cast<uint8_t>(value & 255);
value >>= 8;
}
}
return p;
}
void operator delete(void* p)
{
free(p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment