/***************************************************************
 * Copyright (c) 1998  Simon Kirby                             *
 ***************************************************************/

#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> 

typedef unsigned long dword;

#ifdef LINUX_CPBK
void *statmalloc(size_t size){
	void *p;
	size_t mallocsize;
	dword mem = 0;
	
	mem+= size;
#ifdef CorruptCheck
	mallocsize = size + (sizeof(dword)) + sizeof(dword);
#else
	mallocsize = size + (sizeof(dword));
#endif
	p = malloc(mallocsize);
	if (!p){
		fprintf(stderr,"malloc() of %u bytes failed: %s\n",size,strerror(errno));
		exit(-1);
	}
	*((dword *)p) = (dword)size;
#ifdef CorruptCheck
	*(byte *)((char *)p + size + sizeof(dword) + sizeof(byte) * 0) = 0xde;
	*(byte *)((char *)p + size + sizeof(dword) + sizeof(byte) * 1) = 0xad;
	*(byte *)((char *)p + size + sizeof(dword) + sizeof(byte) * 2) = 0xbe;
	*(byte *)((char *)p + size + sizeof(dword) + sizeof(byte) * 3) = 0xef;
#endif
	p = (void *)((dword *)p + 1);
#ifdef WipeMallocs
	memset(p,0xf0,size);
#endif
	return p;
}

void freemalloc(void *p){
	dword mem = 0;
	
	if (p){
		if (*((dword *)p - 1) == 0){
			fprintf(stderr,"ERROR: Attempt to free pointer twice.\n");
			*(int*)0=0;
			exit(-1);
		} else {
			if (*((dword *)p - 1) > 8192){
				fprintf(stderr,"ERROR: Corrupted free() buffer. (header)\n");
				*(int*)0=0;
				exit(-1);
			}
#ifdef CorruptCheck
			if ((*(byte *)((char *)p + (*((dword *)p - 1)) + sizeof(byte) * 0) != 0xde) ||
				 (*(byte *)((char *)p + (*((dword *)p - 1)) + sizeof(byte) * 1) != 0xad) ||
				 (*(byte *)((char *)p + (*((dword *)p - 1)) + sizeof(byte) * 2) != 0xbe) ||
				 (*(byte *)((char *)p + (*((dword *)p - 1)) + sizeof(byte) * 3) != 0xef)){
				fprintf(stderr,"ERROR: Corrupted free() buffer. (footer)\n");
				hexdump((char *)((dword *)p - 1),(*((dword *)p - 1))+8);
				*(int*)0=0;
				exit(-1);
			}
#endif
			mem-= *((dword *)p - 1);
#ifdef WipeFrees
			memset(p,0xfe,*((dword *)p - 1));
			*((dword *)p - 1) = 0;
#endif
			free((dword *)p - 1);
		}
	}
}
#else
void *statmalloc(size_t size)
{
	return (void *)malloc(size);
} /* statmalloc */

void freemalloc(char *string)
{
	free(string);
} /* freemalloc */
#endif


syntax highlighted by Code2HTML, v. 0.9.1