1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 
24 #include "sci/engine/kernel.h"
25 #include "sci/engine/object.h"
26 #include "sci/engine/script.h"
27 #include "sci/engine/seg_manager.h"
28 #ifdef ENABLE_SCI32
29 #include "sci/engine/features.h"
30 #endif
31 
32 namespace Sci {
33 
34 extern bool relocateBlock(Common::Array<reg_t> &block, int block_location, SegmentId segment, int location, uint32 heapOffset);
35 
init(const Script & owner,reg_t obj_pos,bool initVariables)36 void Object::init(const Script &owner, reg_t obj_pos, bool initVariables) {
37 	const SciSpan<const byte> buf = owner.getSpan(0);
38 	const SciSpan<const byte> data = owner.getSpan(obj_pos.getOffset());
39 	_baseObj = data;
40 	_pos = obj_pos;
41 
42 	// Calling Object::init more than once will screw up _baseVars/_baseMethod
43 	// by duplicating data. This could be turned into a soft error by warning
44 	// instead and clearing arrays, but there does not currently seem to be any
45 	// reason for an object to be initialized multiple times
46 	if (_baseVars.size() || _baseMethod.size()) {
47 		error("Attempt to reinitialize already-initialized object %04x:%04x in script %u", PRINT_REG(obj_pos), owner.getScriptNumber());
48 	}
49 
50 	if (getSciVersion() <= SCI_VERSION_1_LATE) {
51 		const SciSpan<const byte> header = buf.subspan(obj_pos.getOffset() - kOffsetHeaderSize);
52 		_variables.resize(header.getUint16LEAt(kOffsetHeaderSelectorCounter));
53 
54 		// Non-class objects do not have a baseVars section
55 		const uint16 infoSelector = data.getUint16SEAt((_offset + 2) * sizeof(uint16));
56 		if (infoSelector & kInfoFlagClass) {
57 			_baseVars.reserve(_variables.size());
58 			uint baseVarsOffset = _variables.size() * sizeof(uint16);
59 			for (uint i = 0; i < _variables.size(); ++i) {
60 				_baseVars.push_back(data.getUint16SEAt(baseVarsOffset));
61 				baseVarsOffset += sizeof(uint16);
62 			}
63 		}
64 
65 		// method block structure:
66 		// uint16 count;
67 		// uint16 selectorNos[count];
68 		// uint16 zero;
69 		// uint16 codeOffsets[count];
70 
71 		const uint16 methodBlockOffset = header.getUint16LEAt(kOffsetHeaderFunctionArea) - 2;
72 		_methodCount = data.getUint16LEAt(methodBlockOffset);
73 		const uint32 methodBlockSize = _methodCount * 2 * sizeof(uint16) + /* zero-terminator after selector list */ sizeof(uint16);
74 
75 		SciSpan<const uint16> methodEntries = data.subspan<const uint16>(methodBlockOffset + /* count */ sizeof(uint16), methodBlockSize);
76 
77 		// If this happens, then there is either a corrupt script or this code
78 		// misunderstands the structure of the SCI0/1 method block
79 		if (methodEntries.getUint16SEAt(_methodCount) != 0) {
80 			warning("Object %04x:%04x in script %u has a value (0x%04x) in its zero-terminator field", PRINT_REG(obj_pos), owner.getScriptNumber(), methodEntries.getUint16SEAt(_methodCount));
81 		}
82 
83 		_baseMethod.reserve(_methodCount * 2);
84 		for (uint i = 0; i < _methodCount; ++i) {
85 			_baseMethod.push_back(methodEntries.getUint16SEAt(0));
86 			_baseMethod.push_back(methodEntries.getUint16SEAt(_methodCount + /* zero-terminator */ 1));
87 			++methodEntries;
88 		}
89 	} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
90 		_variables.resize(data.getUint16SEAt(2));
91 
92 		// Non-class objects do not have a baseVars section
93 		const uint16 infoSelector = data.getUint16SEAt((_offset + 2) * sizeof(uint16));
94 		if (infoSelector & kInfoFlagClass) {
95 			_baseVars.reserve(_variables.size());
96 			uint baseVarsOffset = data.getUint16SEAt(4);
97 			for (uint i = 0; i < _variables.size(); ++i) {
98 				_baseVars.push_back(buf.getUint16SEAt(baseVarsOffset));
99 				baseVarsOffset += sizeof(uint16);
100 			}
101 		}
102 
103 		// method block structure:
104 		// uint16 count;
105 		// struct {
106 		//   uint16 selectorNo;
107 		//   uint16 codeOffset;
108 		// } entries[count];
109 
110 		const uint16 methodBlockOffset = data.getUint16SEAt(6);
111 		_methodCount = buf.getUint16SEAt(methodBlockOffset);
112 
113 		// Each entry in _baseMethod is actually two values; the first field is
114 		// a selector number, and the second field is an offset to the method's
115 		// code in the script
116 		const uint32 methodBlockSize = _methodCount * 2 * sizeof(uint16);
117 		_baseMethod.reserve(_methodCount * 2);
118 
119 		SciSpan<const uint16> methodEntries = buf.subspan<const uint16>(methodBlockOffset + /* count */ sizeof(uint16), methodBlockSize);
120 		for (uint i = 0; i < _methodCount; ++i) {
121 			_baseMethod.push_back(methodEntries.getUint16SEAt(0));
122 			_baseMethod.push_back(methodEntries.getUint16SEAt(1));
123 			methodEntries += 2;
124 		}
125 #ifdef ENABLE_SCI32
126 	} else if (getSciVersion() == SCI_VERSION_3) {
127 		initSelectorsSci3(buf, initVariables);
128 #endif
129 	}
130 
131 	// Some objects, like the unnamed LarryTalker instance in LSL6hires script
132 	// 610, and the File class in Torin script 64993, have a `name` property
133 	// that is assigned dynamically by game scripts, overriding the static name
134 	// value that is normally created by the SC compiler. When this happens, the
135 	// value can be set to anything: in LSL6hires it becomes a Str object; in
136 	// Torin, it becomes a dynamically allocated string that is disposed before
137 	// the corresponding File instance is disposed.
138 	// To ensure `SegManager::getObjectName` works consistently and correctly,
139 	// without hacks to bypass unexpected/invalid types of dynamic `name` data,
140 	// the reg_t pointer to the original static name value for the object is
141 	// stored here, ensuring that it is constant and guaranteed to be either a
142 	// valid dereferenceable string or NULL_REG.
143 	if (getSciVersion() != SCI_VERSION_3) {
144 		const uint32 heapOffset = owner.getHeapOffset();
145 		const uint32 nameOffset = (obj_pos.getOffset() - heapOffset) + (_offset + 3) * sizeof(uint16);
146 		const uint32 relocOffset = owner.getRelocationOffset(nameOffset);
147 		if (relocOffset != kNoRelocation) {
148 			_name = make_reg(obj_pos.getSegment(), relocOffset + _baseObj.getUint16SEAt((_offset + 3) * sizeof(uint16)));
149 		}
150 #ifdef ENABLE_SCI32
151 	} else if (_propertyOffsetsSci3.size()) {
152 		const uint32 nameOffset = _propertyOffsetsSci3[0];
153 		const uint32 relocOffset = owner.getRelocationOffset(nameOffset);
154 		if (relocOffset != kNoRelocation) {
155 			_name = make_reg32(obj_pos.getSegment(), relocOffset + buf.getUint16SEAt(nameOffset));
156 		}
157 #endif
158 	}
159 
160 	if (initVariables) {
161 #ifdef ENABLE_SCI32
162 		if (getSciVersion() == SCI_VERSION_3) {
163 			_infoSelectorSci3 = make_reg(0, data.getUint16SEAt(10));
164 		} else {
165 #else
166 		{
167 #endif
168 			for (uint i = 0; i < _variables.size(); i++)
169 				_variables[i] = make_reg(0, data.getUint16SEAt(i * sizeof(uint16)));
170 		}
171 	}
172 }
173 
174 const Object *Object::getClass(SegManager *segMan) const {
175 	return isClass() ? this : segMan->getObject(getSuperClassSelector());
176 }
177 
178 int Object::locateVarSelector(SegManager *segMan, Selector slc) const {
179 	const Common::Array<uint16> *buf;
180 	uint varCount;
181 
182 #ifdef ENABLE_SCI32
183 	if (getSciVersion() == SCI_VERSION_3) {
184 		buf = &_baseVars;
185 		varCount = getVarCount();
186 	} else {
187 #else
188 	{
189 #endif
190 		const Object *obj = getClass(segMan);
191 		buf = &obj->_baseVars;
192 		varCount = obj->getVarCount();
193 	}
194 
195 	for (uint i = 0; i < varCount; i++)
196 		if ((*buf)[i] == slc) // Found it?
197 			return i; // report success
198 
199 	return -1; // Failed
200 }
201 
202 bool Object::relocateSci0Sci21(SegmentId segment, int location, uint32 heapOffset) {
203 	return relocateBlock(_variables, getPos().getOffset(), segment, location, heapOffset);
204 }
205 
206 #ifdef ENABLE_SCI32
207 bool Object::relocateSci3(SegmentId segment, uint32 location, int offset, uint32 scriptSize) {
208 	assert(offset >= 0 && (uint)offset < scriptSize);
209 
210 	for (uint i = 0; i < _variables.size(); ++i) {
211 		if (location == _propertyOffsetsSci3[i]) {
212 			_variables[i].setSegment(segment);
213 			_variables[i].incOffset(offset);
214 			return true;
215 		}
216 	}
217 
218 	return false;
219 }
220 #endif
221 
222 int Object::propertyOffsetToId(SegManager *segMan, int propertyOffset) const {
223 	int selectors = getVarCount();
224 
225 	if (propertyOffset < 0 || (propertyOffset >> 1) >= selectors) {
226 		error("Applied propertyOffsetToId to invalid property offset %x (property #%d not in [0..%d])",
227 		          propertyOffset, propertyOffset >> 1, selectors - 1);
228 		return -1;
229 	}
230 
231 	if (getSciVersion() < SCI_VERSION_1_1) {
232 		const SciSpan<const byte> selectoroffset = _baseObj.subspan(kOffsetSelectorSegment + selectors * 2);
233 		return selectoroffset.getUint16SEAt(propertyOffset);
234 	} else {
235 		const Object *obj = this;
236 		if (!isClass())
237 			obj = segMan->getObject(getSuperClassSelector());
238 
239 		return obj->_baseVars[propertyOffset >> 1];
240 	}
241 }
242 
243 void Object::initSpecies(SegManager *segMan, reg_t addr, bool applyScriptPatches) {
244 	uint16 speciesOffset = getSpeciesSelector().getOffset();
245 
246 	if (speciesOffset == 0xffff)		// -1
247 		setSpeciesSelector(NULL_REG);	// no species
248 	else {
249 		reg_t species = segMan->getClassAddress(speciesOffset, SCRIPT_GET_LOCK, addr.getSegment(), applyScriptPatches);
250 		setSpeciesSelector(species);
251 	}
252 }
253 
254 void Object::initSuperClass(SegManager *segMan, reg_t addr, bool applyScriptPatches) {
255 	uint16 superClassOffset = getSuperClassSelector().getOffset();
256 
257 	if (superClassOffset == 0xffff)			// -1
258 		setSuperClassSelector(NULL_REG);	// no superclass
259 	else {
260 		reg_t classAddress = segMan->getClassAddress(superClassOffset, SCRIPT_GET_LOCK, addr.getSegment(), applyScriptPatches);
261 		setSuperClassSelector(classAddress);
262 	}
263 }
264 
265 bool Object::initBaseObject(SegManager *segMan, reg_t addr, bool doInitSuperClass, bool applyScriptPatches) {
266 	const Object *baseObj = segMan->getObject(getSpeciesSelector());
267 
268 	if (baseObj) {
269 		uint originalVarCount = _variables.size();
270 
271 		if (_variables.size() != baseObj->getVarCount())
272 			_variables.resize(baseObj->getVarCount());
273 		// Copy base from species class, as we need its selector IDs
274 		_baseObj = baseObj->_baseObj;
275 		assert(_baseObj);
276 		if (doInitSuperClass)
277 			initSuperClass(segMan, addr, applyScriptPatches);
278 
279 		if (_variables.size() != originalVarCount) {
280 			// These objects are probably broken.
281 			// An example is 'witchCage' in script 200 in KQ5 (#3034714),
282 			// but also 'girl' in script 216 and 'door' in script 22.
283 			// In LSL3 a number of sound objects trigger this right away.
284 			// SQ4-floppy's bug #3037938 also seems related.
285 
286 			// The effect is that a number of its method selectors may be
287 			// treated as variable selectors, causing unpredictable effects.
288 			int objScript = segMan->getScript(_pos.getSegment())->getScriptNumber();
289 
290 			// We have to do a little bit of work to get the name of the object
291 			// before any relocations are done.
292 			reg_t nameReg = getNameSelector();
293 			const char *name;
294 			if (nameReg.isNull()) {
295 				name = "<no name>";
296 			} else {
297 				nameReg.setSegment(_pos.getSegment());
298 				name = segMan->derefString(nameReg);
299 				if (!name)
300 					name = "<invalid name>";
301 			}
302 
303 			debugC(kDebugLevelVM, "Object %04x:%04x (name %s, script %d) "
304 			        "varnum doesn't match baseObj's: obj %d, base %d",
305 			        PRINT_REG(_pos), name, objScript,
306 			        originalVarCount, baseObj->getVarCount());
307 
308 #if 0
309 			// We enumerate the methods selectors which could be hidden here
310 			if (getSciVersion() <= SCI_VERSION_2_1) {
311 				const SegmentRef objRef = segMan->dereference(baseObj->_pos);
312 				assert(objRef.isRaw);
313 				uint segBound = objRef.maxSize/2 - baseObj->getVarCount();
314 				const byte* buf = (const byte *)baseObj->_baseVars;
315 				if (!buf) {
316 					// While loading this may happen due to objects being loaded
317 					// out of order, and we can't proceed then, unfortunately.
318 					segBound = 0;
319 				}
320 				for (uint i = baseObj->getVarCount();
321 				         i < originalVarCount && i < segBound; ++i) {
322 					uint16 slc = READ_SCI11ENDIAN_UINT16(buf + 2*i);
323 					// Skip any numbers which happen to be varselectors too
324 					bool found = false;
325 					for (uint j = 0; j < baseObj->getVarCount() && !found; ++j)
326 						found = READ_SCI11ENDIAN_UINT16(buf + 2*j) == slc;
327 					if (found) continue;
328 					// Skip any selectors which aren't method selectors,
329 					// so couldn't be mistaken for varselectors
330 					if (lookupSelector(segMan, _pos, slc, 0, 0) != kSelectorMethod) continue;
331 					warning("    Possibly affected selector: %02x (%s)", slc,
332 					        g_sci->getKernel()->getSelectorName(slc).c_str());
333 				}
334 			}
335 #endif
336 		}
337 
338 		return true;
339 	}
340 
341 	return false;
342 }
343 
344 #ifdef ENABLE_SCI32
345 bool Object::mustSetViewVisible(int index, const bool fromPropertyOp) const {
346 	if (getSciVersion() == SCI_VERSION_3) {
347 		// In SCI3, visible flag lookups are based on selectors
348 
349 		if (!fromPropertyOp) {
350 			// varindexes must be converted to selectors
351 			index = getVarSelector(index);
352 		}
353 
354 		if (index == -1) {
355 			error("Selector %d is invalid for object %04x:%04x", index, PRINT_REG(_pos));
356 		}
357 
358 		return _mustSetViewVisible[index >> 5];
359 	} else {
360 		// In SCI2, visible flag lookups are based on varindexes
361 
362 		if (fromPropertyOp) {
363 			// property offsets must be converted to varindexes
364 			assert((index % 2) == 0);
365 			index >>= 1;
366 		}
367 
368 		int minIndex, maxIndex;
369 		if (g_sci->_features->usesAlternateSelectors()) {
370 			minIndex = 24;
371 			maxIndex = 43;
372 		} else {
373 			minIndex = 26;
374 			maxIndex = 44;
375 		}
376 
377 		return index >= minIndex && index <= maxIndex;
378 	}
379 }
380 
381 void Object::initSelectorsSci3(const SciSpan<const byte> &buf, const bool initVariables) {
382 	enum {
383 		kExtraGroups = 3,
384 		kGroupSize   = 32
385 	};
386 
387 	const SciSpan<const byte> groupInfo = _baseObj.subspan(16);
388 	const SciSpan<const byte> selectorBase = groupInfo.subspan(kExtraGroups * kGroupSize * sizeof(uint16));
389 
390 	int numGroups = g_sci->getKernel()->getSelectorNamesSize() / kGroupSize;
391 	if (g_sci->getKernel()->getSelectorNamesSize() % kGroupSize)
392 		++numGroups;
393 
394 	_mustSetViewVisible.resize(numGroups);
395 
396 	int numMethods = 0;
397 	int numProperties = 0;
398 
399 	// Selectors are divided into groups of 32, of which the first
400 	// two selectors are always reserved (because their storage
401 	// space is used by the typeMask).
402 	// We don't know beforehand how many methods and properties
403 	// there are, so we count them first.
404 	for (int groupNr = 0; groupNr < numGroups; ++groupNr) {
405 		byte groupLocation = groupInfo[groupNr];
406 		const SciSpan<const byte> seeker = selectorBase.subspan(groupLocation * kGroupSize * sizeof(uint16));
407 
408 		if (groupLocation != 0)	{
409 			// This object actually has selectors belonging to this group
410 			int typeMask = seeker.getUint32SEAt(0);
411 
412 			_mustSetViewVisible[groupNr] = (typeMask & 1);
413 
414 			for (int bit = 2; bit < kGroupSize; ++bit) {
415 				int value = seeker.getUint16SEAt(bit * sizeof(uint16));
416 				if (typeMask & (1 << bit)) { // Property
417 					++numProperties;
418 				} else if (value != 0xffff) { // Method
419 					++numMethods;
420 				} else {
421 					// Undefined selector
422 				}
423 			}
424 		} else
425 			_mustSetViewVisible[groupNr] = false;
426 	}
427 
428 	_methodCount = numMethods;
429 	_variables.resize(numProperties);
430 	_baseVars.resize(numProperties);
431 	_propertyOffsetsSci3.resize(numProperties);
432 
433 	// Go through the whole thing again to get the property values
434 	// and method pointers
435 	int propertyCounter = 0;
436 	for (int groupNr = 0; groupNr < numGroups; ++groupNr) {
437 		byte groupLocation = groupInfo[groupNr];
438 		const SciSpan<const byte> seeker = selectorBase.subspan(groupLocation * kGroupSize * sizeof(uint16));
439 
440 		if (groupLocation != 0)	{
441 			// This object actually has selectors belonging to this group
442 			int typeMask = seeker.getUint32SEAt(0);
443 			int groupBaseId = groupNr * kGroupSize;
444 
445 			for (int bit = 2; bit < kGroupSize; ++bit) {
446 				int value = seeker.getUint16SEAt(bit * sizeof(uint16));
447 				if (typeMask & (1 << bit)) { // Property
448 					_baseVars[propertyCounter] = groupBaseId + bit;
449 					if (initVariables) {
450 						_variables[propertyCounter] = make_reg(0, value);
451 					}
452 					uint32 propertyOffset = (seeker + bit * sizeof(uint16)) - buf;
453 					_propertyOffsetsSci3[propertyCounter] = propertyOffset;
454 					++propertyCounter;
455 				} else if (value != 0xffff) { // Method
456 					_baseMethod.push_back(groupBaseId + bit);
457 					const uint32 offset = value + buf.getUint32SEAt(0);
458 					assert(offset <= kOffsetMask);
459 					_baseMethod.push_back(offset);
460 				} else {
461 					// Undefined selector
462 				}
463 			}
464 		}
465 	}
466 
467 	if (initVariables) {
468 		_speciesSelectorSci3 = make_reg(0, _baseObj.getUint16SEAt(4));
469 		_superClassPosSci3 = make_reg(0, _baseObj.getUint16SEAt(8));
470 	}
471 }
472 #endif
473 
474 } // End of namespace Sci
475