aboutsummaryrefslogtreecommitdiff
path: root/engines/sci/engine/memobj.cpp
blob: ef48270b4101cefd350517a67f51f7710ff37547 (plain)
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *
 */

#include "common/endian.h"

#include "sci/sci.h"
#include "sci/engine/memobj.h"
#include "sci/engine/intmap.h"
#include "sci/engine/seg_manager.h"
#include "sci/engine/state.h"
#include "sci/tools.h"

namespace Sci {

MemObject *MemObject::createMemObject(MemObjectType type) {
	MemObject *mem = 0;
	switch (type) {
	case MEM_OBJ_SCRIPT:
		mem = new Script();
		break;
	case MEM_OBJ_CLONES:
		mem = new CloneTable();
		break;
	case MEM_OBJ_LOCALS:
		mem = new LocalVariables();
		break;
	case MEM_OBJ_SYS_STRINGS:
		mem = new SystemStrings();
		break;
	case MEM_OBJ_STACK:
		mem = new DataStack();
		break;
	case MEM_OBJ_HUNK:
		mem = new HunkTable();
		break;
	case MEM_OBJ_STRING_FRAG:
		mem = new StringFrag();
		break;
	case MEM_OBJ_LISTS:
		mem = new ListTable();
		break;
	case MEM_OBJ_NODES:
		mem = new NodeTable();
		break;
	case MEM_OBJ_DYNMEM:
		mem = new DynMem();
		break;
	default:
		error("Unknown MemObject type %d", type);
		break;
	}

	assert(mem);
	mem->_type = type;
	return mem;
}

void Script::freeScript() {
	free(buf);
	buf = NULL;
	buf_size = 0;

	_objects.clear();

	delete obj_indices;
	obj_indices = 0;
	_codeBlocks.clear();
}

// memory operations

void Script::mcpyInOut(int dst, const void *src, size_t n) {
	if (buf) {
		assert(dst + n <= buf_size);
		memcpy(buf + dst, src, n);
	}
}

int16 Script::getHeap(uint16 offset) const {
	assert(offset + 1 < (int)buf_size);
	return READ_LE_UINT16(buf + offset);
//	return (buf[offset] | (buf[offset+1]) << 8);
}

void Script::incrementLockers() {
	lockers++;
}

void Script::decrementLockers() {
	if (lockers > 0)
		lockers--;
}

int Script::getLockers() const {
	return lockers;
}

void Script::setLockers(int lockers_) {
	lockers = lockers_;
}

void Script::setExportTableOffset(int offset) {
	if (offset) {
		export_table = (uint16 *)(buf + offset + 2);
		exports_nr = READ_LE_UINT16((byte *)(export_table - 1));
	} else {
		export_table = NULL;
		exports_nr = 0;
	}
}

void Script::setSynonymsOffset(int offset) {
	synonyms = buf + offset;
}

byte *Script::getSynonyms() const {
	return synonyms;
}

void Script::setSynonymsNr(int n) {
	synonyms_nr = n;
}

int Script::getSynonymsNr() const {
	return synonyms_nr;
}

byte *MemObject::dereference(reg_t pointer, int *size) {
	error("Error: Trying to dereference pointer %04x:%04x to inappropriate segment",
		          PRINT_REG(pointer));
	return NULL;
}

byte *Script::dereference(reg_t pointer, int *size) {
	if (pointer.offset > buf_size) {
		sciprintf("Error: Attempt to dereference invalid pointer %04x:%04x into script segment (script size=%d)\n",
				  PRINT_REG(pointer), (uint)buf_size);
		return NULL;
	}
	if (size)
		*size = buf_size - pointer.offset;
	return (byte *)(buf + pointer.offset);
}

byte *LocalVariables::dereference(reg_t pointer, int *size) {
	// FIXME: The following doesn't seem to be endian safe.
	// To fix this, we'd have to always treat the reg_t
	// values stored here as in the little endian format.
	int count = _locals.size() * sizeof(reg_t);
	byte *base = (byte *)&_locals[0];

	if (size)
		*size = count;

	return base + pointer.offset;
}

byte *DataStack::dereference(reg_t pointer, int *size) {
	int count = nr * sizeof(reg_t);
	byte *base = (byte *)entries;

	if (size)
		*size = count;

	return base + pointer.offset;
}

byte *DynMem::dereference(reg_t pointer, int *size) {
	int count = _size;
	byte *base = (byte *)_buf;

	if (size)
		*size = count;

	return base + pointer.offset;
}

byte *SystemStrings::dereference(reg_t pointer, int *size) {
	if (size)
		*size = strings[pointer.offset].max_size;
	if (pointer.offset < SYS_STRINGS_MAX && strings[pointer.offset].name)
		return (byte *)(strings[pointer.offset].value);

	// This occurs in KQ5CD when interacting with certain objects
	warning("Attempt to dereference invalid pointer %04x:%04x", PRINT_REG(pointer));
	return NULL;
}


//-------------------- script --------------------
reg_t Script::findCanonicAddress(SegManager *segmgr, reg_t addr) {
	addr.offset = 0;
	return addr;
}

void Script::freeAtAddress(SegManager *segmgr, reg_t addr) {
	/*
		sciprintf("[GC] Freeing script %04x:%04x\n", PRINT_REG(addr));
		if (locals_segment)
			sciprintf("[GC] Freeing locals %04x:0000\n", locals_segment);
	*/

	if (_markedAsDeleted)
		segmgr->deallocateScript(nr);
}

void Script::listAllDeallocatable(SegmentId segId, void *param, NoteCallback note) {
	(*note)(param, make_reg(segId, 0));
}

void Script::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
	Script *script = this;

	if (addr.offset <= script->buf_size && addr.offset >= -SCRIPT_OBJECT_MAGIC_OFFSET && RAW_IS_OBJECT(script->buf + addr.offset)) {
		int idx = RAW_GET_CLASS_INDEX(script, addr);
		if (idx >= 0 && (uint)idx < script->_objects.size()) {
			// Note all local variables, if we have a local variable environment
			if (script->locals_segment)
				(*note)(param, make_reg(script->locals_segment, 0));

			Object &obj = script->_objects[idx];
			for (uint i = 0; i < obj._variables.size(); i++)
				(*note)(param, obj._variables[i]);
		} else {
			warning("Request for outgoing script-object reference at %04x:%04x yielded invalid index %d", PRINT_REG(addr), idx);
		}
	} else {
		/*		warning("Unexpected request for outgoing script-object references at %04x:%04x", PRINT_REG(addr));*/
		/* Happens e.g. when we're looking into strings */
	}
}


//-------------------- clones --------------------

template<typename T>
void Table<T>::listAllDeallocatable(SegmentId segId, void *param, NoteCallback note) {
	for (uint i = 0; i < _table.size(); i++)
		if (isValidEntry(i))
			(*note)(param, make_reg(segId, i));
}

void CloneTable::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
	CloneTable *clone_table = this;
	Clone *clone;

//	assert(addr.segment == _segId);

	if (!clone_table->isValidEntry(addr.offset)) {
		warning("Unexpected request for outgoing references from clone at %04x:%04x", PRINT_REG(addr));
//		BREAKPOINT();
		return;
	}

	clone = &(clone_table->_table[addr.offset]);

	// Emit all member variables (including references to the 'super' delegate)
	for (uint i = 0; i < clone->_variables.size(); i++)
		(*note)(param, clone->_variables[i]);

	// Note that this also includes the 'base' object, which is part of the script and therefore also emits the locals.
	(*note)(param, clone->pos);
	//sciprintf("[GC] Reporting clone-pos %04x:%04x\n", PRINT_REG(clone->pos));
}

void CloneTable::freeAtAddress(SegManager *segmgr, reg_t addr) {
	CloneTable *clone_table = this;
	Object *victim_obj;

//	assert(addr.segment == _segId);

	victim_obj = &(clone_table->_table[addr.offset]);

#ifdef GC_DEBUG
	if (!(victim_obj->flags & OBJECT_FLAG_FREED))
		sciprintf("[GC] Warning: Clone %04x:%04x not reachable and not freed (freeing now)\n", PRINT_REG(addr));
#ifdef GC_DEBUG_VERBOSE
	else
		sciprintf("[GC-DEBUG] Clone %04x:%04x: Freeing\n", PRINT_REG(addr));
#endif
#endif
	/*
		sciprintf("[GC] Clone %04x:%04x: Freeing\n", PRINT_REG(addr));
		sciprintf("[GC] Clone had pos %04x:%04x\n", PRINT_REG(victim_obj->pos));
	*/
	clone_table->freeEntry(addr.offset);
}


//-------------------- locals --------------------
reg_t LocalVariables::findCanonicAddress(SegManager *segmgr, reg_t addr) {
	// Reference the owning script
	SegmentId owner_seg = segmgr->segGet(script_id);

	assert(owner_seg >= 0);

	return make_reg(owner_seg, 0);
}

void LocalVariables::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
//	assert(addr.segment == _segId);

	for (uint i = 0; i < _locals.size(); i++)
		(*note)(param, _locals[i]);
}


//-------------------- stack --------------------
reg_t DataStack::findCanonicAddress(SegManager *segmgr, reg_t addr) {
	addr.offset = 0;
	return addr;
}

void DataStack::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
	fprintf(stderr, "Emitting %d stack entries\n", nr);
	for (int i = 0; i < nr; i++)
		(*note)(param, entries[i]);
	fprintf(stderr, "DONE");
}


//-------------------- lists --------------------
void ListTable::freeAtAddress(SegManager *segmgr, reg_t sub_addr) {
	freeEntry(sub_addr.offset);
}

void ListTable::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
	if (!isValidEntry(addr.offset)) {
		warning("Invalid list referenced for outgoing references: %04x:%04x", PRINT_REG(addr));
		return;
	}

	List *list = &(_table[addr.offset]);

	note(param, list->first);
	note(param, list->last);
	// We could probably get away with just one of them, but
	// let's be conservative here.
}


//-------------------- nodes --------------------
void NodeTable::freeAtAddress(SegManager *segmgr, reg_t sub_addr) {
	freeEntry(sub_addr.offset);
}

void NodeTable::listAllOutgoingReferences(EngineState *s, reg_t addr, void *param, NoteCallback note) {
	if (!isValidEntry(addr.offset)) {
		warning("Invalid node referenced for outgoing references: %04x:%04x", PRINT_REG(addr));
		return;
	}
	Node *node = &(_table[addr.offset]);

	// We need all four here. Can't just stick with 'pred' OR 'succ' because node operations allow us
	// to walk around from any given node
	note(param, node->pred);
	note(param, node->succ);
	note(param, node->key);
	note(param, node->value);
}


//-------------------- hunk --------------------

//-------------------- dynamic memory --------------------

reg_t DynMem::findCanonicAddress(SegManager *segmgr, reg_t addr) {
	addr.offset = 0;
	return addr;
}

void DynMem::listAllDeallocatable(SegmentId segId, void *param, NoteCallback note) {
	(*note)(param, make_reg(segId, 0));
}


} // End of namespace Sci