Skip to content

Instantly share code, notes, and snippets.

@andrewg-felinemenace
Created August 19, 2011 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewg-felinemenace/1156628 to your computer and use it in GitHub Desktop.
Save andrewg-felinemenace/1156628 to your computer and use it in GitHub Desktop.
Structure integrity example code
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
u_int32_t wordhash(u_int32_t a)
{
a = (a+0x7ed55d16) + (a<<12);
a = (a^0xc761c23c) ^ (a>>19);
a = (a+0x165667b1) + (a<<5);
a = (a+0xd3a2646c) ^ (a<<9);
a = (a+0xfd7046c5) + (a<<3);
a = (a^0xb55a4f09) ^ (a>>16);
return a;
}
struct _heap {
void *a;
void *b;
int c;
char d;
void *e;
};
union heap {
struct _heap heap;
u_int32_t ints[(sizeof(struct _heap) / sizeof(u_int32_t)) + 1];
};
u_int32_t hash(union heap *heap)
{
u_int32_t ret;
int i;
ret = (u_int32_t)(heap); // initialize with mem addr
for(i = 0; i < sizeof(struct _heap) / sizeof(u_int32_t); i++) {
ret ^= wordhash(ret - heap->ints[i]);
}
return ret;
}
void sethash(union heap *heap)
{
heap->ints[sizeof(struct _heap) / sizeof(u_int32_t)] = hash(heap);
}
void checkhash(union heap *heap)
{
u_int32_t expected;
u_int32_t got;
expected = hash(heap);
got = heap->ints[sizeof(struct _heap) / sizeof(u_int32_t)];
if(got != expected) {
printf("heap corruption present :( got %08x, expected %08x\n", got, expected);
exit(EXIT_FAILURE);
}
}
int main(int argc, char **argv)
{
union heap *h;
printf("Allocating heap structure\n");
h = calloc(sizeof(union heap), 1);
printf("Setting hash\n");
sethash(h);
printf(" %p %p %d %c %p (should be all 0's)\n", h->heap.a, h->heap.b, h->heap.c, h->heap.d, h->heap.e);
printf(" checksum: %08x\n", h->ints[sizeof(struct _heap) / sizeof(u_int32_t)]);
printf("Checking hash\n");
checkhash(h);
printf(" Check passed. Corrupting h->heap.a\n");
h->heap.a += 1;
printf("Checking hash (should error)\n");
checkhash(h);
printf("Corruption detection failed\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment