Created
August 19, 2011 11:40
-
-
Save andrewg-felinemenace/1156628 to your computer and use it in GitHub Desktop.
Structure integrity example code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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