backendsupport.c 2.43 KB
Newer Older
clean's avatar
clean committed
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# include "system.h"
# include "comsupport.h"
# include "backendsupport.h"


/*
	Utilities
	=========
*/
# ifdef _WINDOWS_
# undef _WINDOWS_
# include <windows.h>
# define	Debugger()	DebugBreak();
# else
# define	Debugger()	{ * (int *) NULL = 0; }
# endif

void
AssertionFailed (char *conditionString, char *file, int line)
{
	FPrintF (StdError, "Error in backend: File %s, Line %d (%s)\n", file, line, conditionString);

	Debugger ();
} /* AssertionFailed */

/*
	Memory management
	=================
*/

static enum {kMemoryInitClear, kMemoryInitSet} gMemoryInit = kMemoryInitSet;

# define	kConvertBufferSize	(32 * 1024)

typedef struct convert_buffer ConvertBufferS, *ConvertBufferP;

struct convert_buffer
{
	ConvertBufferP	cb_next;
	char			cb_memory [kConvertBufferSize];
};

static void
InvalidateMemory (void *memory, size_t size)
{
	char	value, *p;
	int		i;

	switch (gMemoryInit)
	{
		case kMemoryInitClear:
			value	= 0;
			break;
		case kMemoryInitSet:
			value	= ~0;
			break;
		default:
			Assert (False);
			break;
	}

	p	= memory;
	for (i = 0; i < size; i++)
		*p++	= value;
} /* InvalidateMemory */

static ConvertBufferP	gFirstBuffer = NULL, gCurrentBuffer = NULL;
static char 			*gMemory;
static long gBytesLeft = 0;

static void
AllocConvertBuffer (void)
{
	ConvertBufferP	newBuffer;

	newBuffer	= (ConvertBufferP) malloc (sizeof (ConvertBufferS));

	if (newBuffer == NULL)
		FatalCompError ("backendsupport.c", "AllocConvertBuffer", "out of memory");

	if (gFirstBuffer == NULL)
		gCurrentBuffer	= gFirstBuffer				= newBuffer;
	else
		gCurrentBuffer	= gCurrentBuffer->cb_next	= newBuffer;

	gCurrentBuffer->cb_next	=	NULL;

	gBytesLeft	= kConvertBufferSize;
	gMemory		= gCurrentBuffer->cb_memory;

	InvalidateMemory (gMemory, kConvertBufferSize);

	if (gFirstBuffer == NULL)
		gFirstBuffer	= gCurrentBuffer;
} /* AllocConvertBuffer */

void
FreeConvertBuffers (void)
{
	ConvertBufferP	buffer;

	buffer	= gFirstBuffer;

	while (buffer != NULL)
	{
		ConvertBufferP	nextBuffer;

		nextBuffer	= buffer->cb_next;

		InvalidateMemory (buffer, sizeof (ConvertBufferS));
		free (buffer);

		buffer	= nextBuffer;
	}

	gFirstBuffer	= NULL;
	gCurrentBuffer	= NULL;
	gBytesLeft	= NULL;
} /* FreeConvertBuffers */

void *
ConvertAlloc (SizeT size)
{
	void	*memory;

	size	= (size+3) & ~3;

	if (size > gBytesLeft)
		AllocConvertBuffer ();

	Assert (size <= gBytesLeft);

	memory	= gMemory;	
	gBytesLeft	-= size;
	gMemory	+=	size;

	return ((void *) memory);
} /* ConvertAlloc */