File: statmalloc.c

package info (click to toggle)
cpbk 2.0-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 248 kB
  • ctags: 168
  • sloc: ansic: 2,193; makefile: 114; sh: 35
file content (89 lines) | stat: -rw-r--r-- 2,289 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/***************************************************************
 * 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