File: managed_object_pool.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (347 lines) | stat: -rw-r--r-- 9,788 bytes parent folder | download | duplicates (2)
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
/* 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include "common/std/vector.h"
#include "ags/engine/ac/dynobj/managed_object_pool.h"
#include "ags/shared/debugging/out.h"
#include "ags/shared/util/string_utils.h"               // fputstring, etc
#include "ags/shared/script/cc_common.h"
#include "ags/shared/script/cc_internal.h"
#include "ags/shared/util/stream.h"
#include "ags/globals.h"

namespace AGS3 {

using namespace AGS::Shared;

const auto OBJECT_CACHE_MAGIC_NUMBER = 0xa30b;
const auto SERIALIZE_BUFFER_SIZE = 10240;
const auto GARBAGE_COLLECTION_INTERVAL = 1024;
const auto RESERVED_SIZE = 2048;

int ManagedObjectPool::Remove(ManagedObject &o, bool force) {
	const bool can_remove = o.callback->Dispose(o.addr, force) != 0;
	if (!(can_remove || force))
		return 0;

	available_ids.push(o.handle);
	handleByAddress.erase(o.addr);
	ManagedObjectLog("Line %d Disposed managed object handle=%d", currentline, o.handle);
	o = ManagedObject();
	return 1;
}

int32_t ManagedObjectPool::AddRef(int32_t handle) {
	if (handle < 1 || (size_t)handle >= objects.size())
		return 0;

	auto &o = objects[handle];
	if (!o.isUsed())
		return 0;
	o.refCount++;
	ManagedObjectLog("Line %d AddRef: handle=%d new refcount=%d", _G(currentline), o.handle, o.refCount);
	return o.refCount;
}

int ManagedObjectPool::CheckDispose(int32_t handle) {
	if (handle < 1 || (size_t)handle >= objects.size())
		return 1;

	auto &o = objects[handle];
	if (!o.isUsed()) {
		return 1;
	}
	if (o.refCount >= 1) {
		return 0;
	}
	return Remove(o);
}

int32_t ManagedObjectPool::SubRef(int32_t handle) {
	if (handle < 1 || (size_t)handle >= objects.size()) {
		return 0;
	}
	auto &o = objects[handle];
	if (!o.isUsed()) {
		return 0;
	}

	o.refCount--;
	const auto newRefCount = o.refCount;
	const auto canBeDisposed = (o.addr != disableDisposeForObject);
	if (canBeDisposed && o.refCount <= 0) {
		Remove(o);
	}
	// object could be removed at this point, don't use any values.
	ManagedObjectLog("Line %d SubRef: handle=%d new refcount=%d canBeDisposed=%d", _G(currentline), handle, newRefCount, canBeDisposed);
	return newRefCount;
}

int32_t ManagedObjectPool::AddressToHandle(void *addr) {
	if (addr == nullptr) {
		return 0;
	}
	auto it = handleByAddress.find(addr);
	if (it == handleByAddress.end()) {
		return 0;
	}
	return it->_value;
}

// this function is called often (whenever a pointer is used)
void *ManagedObjectPool::HandleToAddress(int32_t handle) {
	if (handle < 1 || (size_t)handle >= objects.size()) {
		return nullptr;
	}
	auto &o = objects[handle];
	if (!o.isUsed()) {
		return nullptr;
	}
	return o.addr;
}

// this function is called often (whenever a pointer is used)
ScriptValueType ManagedObjectPool::HandleToAddressAndManager(int32_t handle, void *&object, IScriptObject *&manager) {
	if ((handle < 1 || (size_t)handle >= objects.size()) || !objects[handle].isUsed()) {
		object = nullptr;
		manager = nullptr;
		return kScValUndefined;
	}
	auto &o = objects[handle];
	object = (void *)(o.addr); // WARNING: This strips the const from the char* pointer.
	manager = o.callback;
	return o.obj_type;
}

int ManagedObjectPool::RemoveObject(void *address) {
	if (address == nullptr) {
		return 0;
	}
	auto it = handleByAddress.find(address);
	if (it == handleByAddress.end()) {
		return 0;
	}

	auto &o = objects[it->_value];
	return Remove(o, true);
}

void ManagedObjectPool::RunGarbageCollectionIfAppropriate() {
	if (objectCreationCounter <= GARBAGE_COLLECTION_INTERVAL) {
		return;
	}
	RunGarbageCollection();
	objectCreationCounter = 0;
}

void ManagedObjectPool::RunGarbageCollection() {
	for (int i = 1; i < nextHandle; i++) {
		auto &o = objects[i];
		if (!o.isUsed()) {
			continue;
		}
		if (o.refCount < 1) {
			Remove(o);
		}
	}
	ManagedObjectLog("Ran garbage collection");
}

int ManagedObjectPool::Add(int handle, void *address, IScriptObject *callback, ScriptValueType obj_type)
{
    auto &o = objects[handle];
    assert(!o.isUsed());

    o = ManagedObject(obj_type, handle, address, callback);

    handleByAddress.insert({address, handle});
    ManagedObjectLog("Allocated managed object type=%s, handle=%d, addr=%08X", callback->GetType(), handle, address);
    return handle;
}

int ManagedObjectPool::AddObject(void *address, IScriptObject *callback, ScriptValueType obj_type) {
	int32_t handle;

	if (!available_ids.empty()) {
		handle = available_ids.front();
		available_ids.pop();
	} else {
		handle = nextHandle++;
		if ((size_t)handle >= objects.size()) {
			objects.resize(handle + 1024, ManagedObject());
		}
	}

	objectCreationCounter++;
	return Add(handle, address, callback, obj_type);
}

int ManagedObjectPool::AddUnserializedObject(void *address, IScriptObject *callback, ScriptValueType obj_type, int handle) {
	if (handle < 1) {
		cc_error("Attempt to assign invalid handle: %d", handle);
		return 0;
	}
	if ((size_t)handle >= objects.size()) {
		objects.resize(handle + 1024, ManagedObject());
	}

	return Add(handle, address, callback, obj_type);
}

void ManagedObjectPool::WriteToDisk(Stream *out) {

	// use this opportunity to clean up any non-referenced pointers
	RunGarbageCollection();

	std::vector<uint8_t> serializeBuffer;
	serializeBuffer.resize(SERIALIZE_BUFFER_SIZE);

	out->WriteInt32(OBJECT_CACHE_MAGIC_NUMBER);
	out->WriteInt32(2);  // version

	int size = 0;
	for (int i = 1; i < nextHandle; i++) {
		auto const &o = objects[i];
		if (o.isUsed()) {
			size += 1;
		}
	}
	out->WriteInt32(size);

	for (int i = 1; i < nextHandle; i++) {
		auto const &o = objects[i];
		if (!o.isUsed()) {
			continue;
		}

		// handle
		out->WriteInt32(o.handle);
		// write the type of the object
		StrUtil::WriteCStr(o.callback->GetType(), out);
		// now write the object data
		int bytesWritten = o.callback->Serialize(o.addr, &serializeBuffer.front(), serializeBuffer.size());
		if ((bytesWritten < 0) && ((size_t)(-bytesWritten) > serializeBuffer.size())) {
			// buffer not big enough, re-allocate with requested size
			serializeBuffer.resize(-bytesWritten);
			bytesWritten = o.callback->Serialize(o.addr, &serializeBuffer.front(), serializeBuffer.size());
		}
		assert(bytesWritten >= 0);
		out->WriteInt32(bytesWritten);
		out->Write(&serializeBuffer.front(), bytesWritten);
		out->WriteInt32(o.refCount);

		ManagedObjectLog("Wrote handle = %d", o.handle);
	}
}

int ManagedObjectPool::ReadFromDisk(Stream *in, ICCObjectCollectionReader *reader) {
	if (in->ReadInt32() != OBJECT_CACHE_MAGIC_NUMBER) {
		cc_error("Data was not written by ccSeralize");
		return -1;
	}

	char typeNameBuffer[200];
	std::vector<char> serializeBuffer;
	serializeBuffer.resize(SERIALIZE_BUFFER_SIZE);

	auto version = in->ReadInt32();

	switch (version) {
	case 1: {
		// IMPORTANT: numObjs is "nextHandleId", which is why we iterate from 1 to numObjs-1
		int numObjs = in->ReadInt32();
		for (int i = 1; i < numObjs; i++) {
			StrUtil::ReadCStr(typeNameBuffer, in, sizeof(typeNameBuffer));
			if (typeNameBuffer[0] != 0) {
				size_t numBytes = in->ReadInt32();
				if (numBytes > serializeBuffer.size()) {
					serializeBuffer.resize(numBytes);
				}
				in->Read(&serializeBuffer.front(), numBytes);
				// Delegate work to ICCObjectReader
				reader->Unserialize(i, typeNameBuffer, &serializeBuffer.front(), numBytes);
				objects[i].refCount = in->ReadInt32();
				ManagedObjectLog("Read handle = %d", objects[i].handle);
			}
		}
	}
	break;
	case 2: {
		// This is actually number of objects written.
		int objectsSize = in->ReadInt32();
		for (int i = 0; i < objectsSize; i++) {
			auto handle = in->ReadInt32();
			assert(handle >= 1);
			StrUtil::ReadCStr(typeNameBuffer, in, sizeof(typeNameBuffer));
			assert(typeNameBuffer[0] != 0);
			size_t numBytes = in->ReadInt32();
			if (numBytes > serializeBuffer.size()) {
				serializeBuffer.resize(numBytes);
			}
			in->Read(&serializeBuffer.front(), numBytes);
			// Delegate work to ICCObjectReader
			reader->Unserialize(handle, typeNameBuffer, &serializeBuffer.front(), numBytes);
			objects[handle].refCount = in->ReadInt32();
			ManagedObjectLog("Read handle = %d", objects[i].handle);
		}
	}
	break;
	default:
		cc_error("Invalid data version: %d", version);
		return -1;
	}

	// re-adjust next handles. (in case saved in random order)
	available_ids = std::queue<int32_t>();
	nextHandle = 1;

	for (const auto &o : objects) {
		if (o.isUsed()) {
			nextHandle = o.handle + 1;
		}
	}
	for (int i = 1; i < nextHandle; i++) {
		if (!objects[i].isUsed()) {
			available_ids.push(i);
		}
	}

	return 0;
}

// de-allocate all objects
void ManagedObjectPool::reset() {
	for (int i = 1; i < nextHandle; i++) {
		auto &o = objects[i];
		if (!o.isUsed()) {
			continue;
		}
		Remove(o, true);
	}
	available_ids = std::queue<int32_t>();
	nextHandle = 1;
}

ManagedObjectPool::ManagedObjectPool() : objectCreationCounter(0), nextHandle(1), available_ids(), objects(RESERVED_SIZE, ManagedObject()), handleByAddress() {
	handleByAddress.reserve(RESERVED_SIZE);
}

} // namespace AGS3