aboutsummaryrefslogtreecommitdiff
path: root/engines/sci/engine
diff options
context:
space:
mode:
Diffstat (limited to 'engines/sci/engine')
-rw-r--r--engines/sci/engine/features.cpp2
-rw-r--r--engines/sci/engine/kernel.cpp24
-rw-r--r--engines/sci/engine/kernel.h4
-rw-r--r--engines/sci/engine/kparse.cpp6
-rw-r--r--engines/sci/engine/kvideo.cpp14
-rw-r--r--engines/sci/engine/message.cpp74
-rw-r--r--engines/sci/engine/object.cpp65
-rw-r--r--engines/sci/engine/object.h73
-rw-r--r--engines/sci/engine/savegame.cpp27
-rw-r--r--engines/sci/engine/script.cpp533
-rw-r--r--engines/sci/engine/script.h49
-rw-r--r--engines/sci/engine/script_patches.cpp34
-rw-r--r--engines/sci/engine/script_patches.h10
-rw-r--r--engines/sci/engine/scriptdebug.cpp140
-rw-r--r--engines/sci/engine/seg_manager.cpp8
-rw-r--r--engines/sci/engine/workarounds.cpp2
16 files changed, 536 insertions, 529 deletions
diff --git a/engines/sci/engine/features.cpp b/engines/sci/engine/features.cpp
index e37a1651ef..40d380195d 100644
--- a/engines/sci/engine/features.cpp
+++ b/engines/sci/engine/features.cpp
@@ -448,7 +448,7 @@ SciVersion GameFeatures::detectMessageFunctionType() {
// Only v2 Message resources use the kGetMessage kernel function.
// v3-v5 use the kMessage kernel function.
- if (READ_SCI11ENDIAN_UINT32(res->data) / 1000 == 2)
+ if (res->getUint32SEAt(0) / 1000 == 2)
_messageFunctionType = SCI_VERSION_1_LATE;
else
_messageFunctionType = SCI_VERSION_1_1;
diff --git a/engines/sci/engine/kernel.cpp b/engines/sci/engine/kernel.cpp
index c7732c6b15..d029923d96 100644
--- a/engines/sci/engine/kernel.cpp
+++ b/engines/sci/engine/kernel.cpp
@@ -149,13 +149,13 @@ void Kernel::loadSelectorNames() {
return;
}
- int count = (isBE ? READ_BE_UINT16(r->data) : READ_LE_UINT16(r->data)) + 1; // Counter is slightly off
+ int count = (isBE ? r->getUint16BEAt(0) : r->getUint16LEAt(0)) + 1; // Counter is slightly off
for (int i = 0; i < count; i++) {
- int offset = isBE ? READ_BE_UINT16(r->data + 2 + i * 2) : READ_LE_UINT16(r->data + 2 + i * 2);
- int len = isBE ? READ_BE_UINT16(r->data + offset) : READ_LE_UINT16(r->data + offset);
+ int offset = isBE ? r->getUint16BEAt(2 + i * 2) : r->getUint16LEAt(2 + i * 2);
+ int len = isBE ? r->getUint16BEAt(offset) : r->getUint16LEAt(offset);
- Common::String tmp((const char *)r->data + offset + 2, len);
+ Common::String tmp = r->getStringAt(offset + 2, len);
_selectorNames.push_back(tmp);
//debug("%s", tmp.c_str());
@@ -940,33 +940,27 @@ void Kernel::loadKernelNames(GameFeatures *features) {
}
Common::String Kernel::lookupText(reg_t address, int index) {
- char *seeker;
- Resource *textres;
-
if (address.getSegment())
return _segMan->getString(address);
- int textlen;
- int _index = index;
- textres = _resMan->findResource(ResourceId(kResourceTypeText, address.getOffset()), 0);
+ Resource *textres = _resMan->findResource(ResourceId(kResourceTypeText, address.getOffset()), false);
if (!textres) {
error("text.%03d not found", address.getOffset());
- return NULL; /* Will probably segfault */
}
- textlen = textres->size;
- seeker = (char *) textres->data;
+ int textlen = textres->size();
+ const char *seeker = (const char *)textres->getUnsafeDataAt(0);
+ int _index = index;
while (index--)
- while ((textlen--) && (*seeker++))
+ while (textlen-- && *seeker++)
;
if (textlen)
return seeker;
error("Index %d out of bounds in text.%03d", _index, address.getOffset());
- return NULL;
}
// TODO: script_adjust_opcode_formats should probably be part of the
diff --git a/engines/sci/engine/kernel.h b/engines/sci/engine/kernel.h
index 335fec06ad..51f4b5dbcb 100644
--- a/engines/sci/engine/kernel.h
+++ b/engines/sci/engine/kernel.h
@@ -171,8 +171,8 @@ public:
// Script dissection/dumping functions
void dissectScript(int scriptNumber, Vocabulary *vocab);
- void dumpScriptObject(char *data, int seeker, int objsize);
- void dumpScriptClass(char *data, int seeker, int objsize);
+ void dumpScriptObject(const SciSpan<const byte> &script, SciSpan<const byte> object);
+ void dumpScriptClass(const SciSpan<const byte> &script, SciSpan<const byte> clazz);
SelectorCache _selectorCache; /**< Shortcut list for important selectors. */
typedef Common::Array<KernelFunction> KernelFunctionArray;
diff --git a/engines/sci/engine/kparse.cpp b/engines/sci/engine/kparse.cpp
index f85f33e3e8..d3bf2d72e9 100644
--- a/engines/sci/engine/kparse.cpp
+++ b/engines/sci/engine/kparse.cpp
@@ -188,7 +188,7 @@ reg_t kSetSynonyms(EngineState *s, int argc, reg_t *argv) {
numSynonyms = s->_segMan->getScript(seg)->getSynonymsNr();
if (numSynonyms) {
- const byte *synonyms = s->_segMan->getScript(seg)->getSynonyms();
+ const SciSpan<const byte> &synonyms = s->_segMan->getScript(seg)->getSynonyms();
if (synonyms) {
debugC(kDebugLevelParser, "Setting %d synonyms for script.%d",
@@ -202,8 +202,8 @@ reg_t kSetSynonyms(EngineState *s, int argc, reg_t *argv) {
} else
for (int i = 0; i < numSynonyms; i++) {
synonym_t tmp;
- tmp.replaceant = READ_LE_UINT16(synonyms + i * 4);
- tmp.replacement = READ_LE_UINT16(synonyms + i * 4 + 2);
+ tmp.replaceant = synonyms.getUint16LEAt(i * 4);
+ tmp.replacement = synonyms.getUint16LEAt(i * 4 + 2);
voc->addSynonym(tmp);
}
} else
diff --git a/engines/sci/engine/kvideo.cpp b/engines/sci/engine/kvideo.cpp
index 11378d7647..3d689f2b42 100644
--- a/engines/sci/engine/kvideo.cpp
+++ b/engines/sci/engine/kvideo.cpp
@@ -27,8 +27,10 @@
#include "sci/graphics/cursor.h"
#include "sci/graphics/palette.h"
#include "sci/graphics/screen.h"
+#include "sci/util.h"
#include "common/events.h"
#include "common/keyboard.h"
+#include "common/span.h"
#include "common/str.h"
#include "common/system.h"
#include "common/textconsole.h"
@@ -53,19 +55,21 @@ void playVideo(Video::VideoDecoder *videoDecoder, VideoState videoState) {
videoDecoder->start();
- byte *scaleBuffer = 0;
+ Common::SpanOwner<SciSpan<byte> > scaleBuffer;
byte bytesPerPixel = videoDecoder->getPixelFormat().bytesPerPixel;
uint16 width = videoDecoder->getWidth();
uint16 height = videoDecoder->getHeight();
uint16 pitch = videoDecoder->getWidth() * bytesPerPixel;
uint16 screenWidth = g_sci->_gfxScreen->getDisplayWidth();
uint16 screenHeight = g_sci->_gfxScreen->getDisplayHeight();
+ uint32 numPixels;
if (screenWidth == 640 && width <= 320 && height <= 240) {
width *= 2;
height *= 2;
pitch *= 2;
- scaleBuffer = new byte[width * height * bytesPerPixel];
+ numPixels = width * height * bytesPerPixel;
+ scaleBuffer->allocate(numPixels, videoState.fileName + " scale buffer");
}
uint16 x = (screenWidth - width) / 2;
@@ -84,9 +88,10 @@ void playVideo(Video::VideoDecoder *videoDecoder, VideoState videoState) {
if (frame) {
if (scaleBuffer) {
+ const SciSpan<const byte> input((const byte *)frame->getPixels(), frame->w * frame->h * bytesPerPixel);
// TODO: Probably should do aspect ratio correction in KQ6
- g_sci->_gfxScreen->scale2x((const byte *)frame->getPixels(), scaleBuffer, videoDecoder->getWidth(), videoDecoder->getHeight(), bytesPerPixel);
- g_system->copyRectToScreen(scaleBuffer, pitch, x, y, width, height);
+ g_sci->_gfxScreen->scale2x(input, *scaleBuffer, videoDecoder->getWidth(), videoDecoder->getHeight(), bytesPerPixel);
+ g_system->copyRectToScreen(scaleBuffer->getUnsafeDataAt(0, pitch * height), pitch, x, y, width, height);
} else {
g_system->copyRectToScreen(frame->getPixels(), frame->pitch, x, y, width, height);
}
@@ -111,7 +116,6 @@ void playVideo(Video::VideoDecoder *videoDecoder, VideoState videoState) {
g_system->delayMillis(10);
}
- delete[] scaleBuffer;
delete videoDecoder;
}
diff --git a/engines/sci/engine/message.cpp b/engines/sci/engine/message.cpp
index 5e07ead5d7..c30ad3aee4 100644
--- a/engines/sci/engine/message.cpp
+++ b/engines/sci/engine/message.cpp
@@ -39,13 +39,13 @@ struct MessageRecord {
class MessageReader {
public:
bool init() {
- if (_headerSize > _size)
+ if (_headerSize > _data.size())
return false;
// Read message count from last word in header
- _messageCount = READ_SCI11ENDIAN_UINT16(_data + _headerSize - 2);
+ _messageCount = _data.getUint16SEAt(_headerSize - 2);
- if (_messageCount * _recordSize + _headerSize > _size)
+ if (_messageCount * _recordSize + _headerSize > _data.size())
return false;
return true;
@@ -56,11 +56,10 @@ public:
virtual ~MessageReader() { }
protected:
- MessageReader(const byte *data, uint size, uint headerSize, uint recordSize)
- : _data(data), _size(size), _headerSize(headerSize), _recordSize(recordSize), _messageCount(0) { }
+ MessageReader(const SciSpan<const byte> &data, uint headerSize, uint recordSize)
+ : _data(data), _headerSize(headerSize), _recordSize(recordSize), _messageCount(0) { }
- const byte *_data;
- const uint _size;
+ const SciSpan<const byte> _data;
const uint _headerSize;
const uint _recordSize;
uint _messageCount;
@@ -68,22 +67,22 @@ protected:
class MessageReaderV2 : public MessageReader {
public:
- MessageReaderV2(byte *data, uint size) : MessageReader(data, size, 6, 4) { }
+ MessageReaderV2(const SciSpan<const byte> &data) : MessageReader(data, 6, 4) { }
bool findRecord(const MessageTuple &tuple, MessageRecord &record) {
- const byte *recordPtr = _data + _headerSize;
+ SciSpan<const byte> recordPtr = _data.subspan(_headerSize);
for (uint i = 0; i < _messageCount; i++) {
if ((recordPtr[0] == tuple.noun) && (recordPtr[1] == tuple.verb)) {
record.tuple = tuple;
record.refTuple = MessageTuple();
record.talker = 0;
- const uint16 stringOffset = READ_LE_UINT16(recordPtr + 2);
- const uint32 maxSize = _size - stringOffset;
- record.string = (const char *)_data + stringOffset;
+ const uint16 stringOffset = recordPtr.getUint16LEAt(2);
+ const uint32 maxSize = _data.size() - stringOffset;
+ record.string = (const char *)_data.getUnsafeDataAt(stringOffset, maxSize);
record.length = Common::strnlen(record.string, maxSize);
if (record.length == maxSize) {
- warning("Message %s appears truncated at %ld", tuple.toString().c_str(), recordPtr - _data);
+ warning("Message %s from %s appears truncated at %ld", tuple.toString().c_str(), _data.name().c_str(), recordPtr - _data);
}
return true;
}
@@ -96,23 +95,22 @@ public:
class MessageReaderV3 : public MessageReader {
public:
- MessageReaderV3(byte *data, uint size) : MessageReader(data, size, 8, 10) { }
+ MessageReaderV3(const SciSpan<const byte> &data) : MessageReader(data, 8, 10) { }
bool findRecord(const MessageTuple &tuple, MessageRecord &record) {
- const byte *recordPtr = _data + _headerSize;
-
+ SciSpan<const byte> recordPtr = _data.subspan(_headerSize);
for (uint i = 0; i < _messageCount; i++) {
if ((recordPtr[0] == tuple.noun) && (recordPtr[1] == tuple.verb)
&& (recordPtr[2] == tuple.cond) && (recordPtr[3] == tuple.seq)) {
record.tuple = tuple;
record.refTuple = MessageTuple();
record.talker = recordPtr[4];
- const uint16 stringOffset = READ_LE_UINT16(recordPtr + 5);
- const uint32 maxSize = _size - stringOffset;
- record.string = (const char *)_data + stringOffset;
+ const uint16 stringOffset = recordPtr.getUint16LEAt(5);
+ const uint32 maxSize = _data.size() - stringOffset;
+ record.string = (const char *)_data.getUnsafeDataAt(stringOffset, maxSize);
record.length = Common::strnlen(record.string, maxSize);
if (record.length == maxSize) {
- warning("Message %s appears truncated at %ld", tuple.toString().c_str(), recordPtr - _data);
+ warning("Message %s from %s appears truncated at %ld", tuple.toString().c_str(), _data.name().c_str(), recordPtr - _data);
}
return true;
}
@@ -125,23 +123,22 @@ public:
class MessageReaderV4 : public MessageReader {
public:
- MessageReaderV4(byte *data, uint size) : MessageReader(data, size, 10, 11) { }
+ MessageReaderV4(const SciSpan<const byte> &data) : MessageReader(data, 10, 11) { }
bool findRecord(const MessageTuple &tuple, MessageRecord &record) {
- const byte *recordPtr = _data + _headerSize;
-
+ SciSpan<const byte> recordPtr = _data.subspan(_headerSize);
for (uint i = 0; i < _messageCount; i++) {
if ((recordPtr[0] == tuple.noun) && (recordPtr[1] == tuple.verb)
&& (recordPtr[2] == tuple.cond) && (recordPtr[3] == tuple.seq)) {
record.tuple = tuple;
record.refTuple = MessageTuple(recordPtr[7], recordPtr[8], recordPtr[9]);
record.talker = recordPtr[4];
- const uint16 stringOffset = READ_SCI11ENDIAN_UINT16(recordPtr + 5);
- const uint32 maxSize = _size - stringOffset;
- record.string = (const char *)_data + stringOffset;
+ const uint16 stringOffset = recordPtr.getUint16SEAt(5);
+ const uint32 maxSize = _data.size() - stringOffset;
+ record.string = (const char *)_data.getUnsafeDataAt(stringOffset, maxSize);
record.length = Common::strnlen(record.string, maxSize);
if (record.length == maxSize) {
- warning("Message %s appears truncated at %ld", tuple.toString().c_str(), recordPtr - _data);
+ warning("Message %s from %s appears truncated at %ld", tuple.toString().c_str(), _data.name().c_str(), recordPtr - _data);
}
return true;
}
@@ -157,23 +154,22 @@ public:
// the talker and the string...
class MessageReaderV4_MacSCI32 : public MessageReader {
public:
- MessageReaderV4_MacSCI32(byte *data, uint size) : MessageReader(data, size, 10, 12) { }
+ MessageReaderV4_MacSCI32(const SciSpan<const byte> &data) : MessageReader(data, 10, 12) { }
bool findRecord(const MessageTuple &tuple, MessageRecord &record) {
- const byte *recordPtr = _data + _headerSize;
-
+ SciSpan<const byte> recordPtr = _data.subspan(_headerSize);
for (uint i = 0; i < _messageCount; i++) {
if ((recordPtr[0] == tuple.noun) && (recordPtr[1] == tuple.verb)
&& (recordPtr[2] == tuple.cond) && (recordPtr[3] == tuple.seq)) {
record.tuple = tuple;
record.refTuple = MessageTuple(recordPtr[8], recordPtr[9], recordPtr[10]);
record.talker = recordPtr[4];
- const uint16 stringOffset = READ_BE_UINT16(recordPtr + 6);
- const uint32 maxSize = _size - stringOffset;
- record.string = (const char *)_data + stringOffset;
+ const uint16 stringOffset = recordPtr.getUint16BEAt(6);
+ const uint32 maxSize = _data.size() - stringOffset;
+ record.string = (const char *)_data.getUnsafeDataAt(stringOffset, maxSize);
record.length = Common::strnlen(record.string, maxSize);
if (record.length == maxSize) {
- warning("Message %s appears truncated at %ld", tuple.toString().c_str(), recordPtr - _data);
+ warning("Message %s from %s appears truncated at %ld", tuple.toString().c_str(), _data.name().c_str(), recordPtr - _data);
}
return true;
}
@@ -194,24 +190,24 @@ bool MessageState::getRecord(CursorStack &stack, bool recurse, MessageRecord &re
}
MessageReader *reader;
- int version = READ_SCI11ENDIAN_UINT32(res->data) / 1000;
+ int version = res->getUint32SEAt(0) / 1000;
switch (version) {
case 2:
- reader = new MessageReaderV2(res->data, res->size);
+ reader = new MessageReaderV2(*res);
break;
case 3:
- reader = new MessageReaderV3(res->data, res->size);
+ reader = new MessageReaderV3(*res);
break;
case 4:
#ifdef ENABLE_SCI32
case 5: // v5 seems to be compatible with v4
// SCI32 Mac is different than SCI32 DOS/Win here
if (g_sci->getPlatform() == Common::kPlatformMacintosh && getSciVersion() >= SCI_VERSION_2_1_EARLY)
- reader = new MessageReaderV4_MacSCI32(res->data, res->size);
+ reader = new MessageReaderV4_MacSCI32(*res);
else
#endif
- reader = new MessageReaderV4(res->data, res->size);
+ reader = new MessageReaderV4(*res);
break;
default:
error("Message: unsupported resource version %d", version);
diff --git a/engines/sci/engine/object.cpp b/engines/sci/engine/object.cpp
index 0566d6955f..2a6c96664b 100644
--- a/engines/sci/engine/object.cpp
+++ b/engines/sci/engine/object.cpp
@@ -51,24 +51,25 @@ static bool relocateBlock(Common::Array<reg_t> &block, int block_location, Segme
return true;
}
-void Object::init(byte *buf, reg_t obj_pos, bool initVariables) {
- byte *data = buf + obj_pos.getOffset();
+void Object::init(const SciSpan<const byte> &buf, reg_t obj_pos, bool initVariables) {
+ const SciSpan<const byte> data = buf.subspan(obj_pos.getOffset());
_baseObj = data;
_pos = obj_pos;
if (getSciVersion() <= SCI_VERSION_1_LATE) {
- _variables.resize(READ_LE_UINT16(data + kOffsetSelectorCounter));
- _baseVars = (const uint16 *)(_baseObj + _variables.size() * 2);
- _methodCount = READ_LE_UINT16(data + READ_LE_UINT16(data + kOffsetFunctionArea) - 2);
+ const SciSpan<const byte> header = buf.subspan(obj_pos.getOffset() - kOffsetHeaderSize);
+ _variables.resize(header.getUint16LEAt(kOffsetHeaderSelectorCounter));
+ _baseVars = _baseObj.subspan<const uint16>(_variables.size() * sizeof(uint16));
+ _methodCount = data.getUint16LEAt(header.getUint16LEAt(kOffsetHeaderFunctionArea) - 2);
for (int i = 0; i < _methodCount * 2 + 2; ++i) {
- _baseMethod.push_back(READ_SCI11ENDIAN_UINT16(data + READ_LE_UINT16(data + kOffsetFunctionArea) + i * 2));
+ _baseMethod.push_back(data.getUint16SEAt(header.getUint16LEAt(kOffsetHeaderFunctionArea) + i * 2));
}
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- _variables.resize(READ_SCI11ENDIAN_UINT16(data + 2));
- _baseVars = (const uint16 *)(buf + READ_SCI11ENDIAN_UINT16(data + 4));
- _methodCount = READ_SCI11ENDIAN_UINT16(buf + READ_SCI11ENDIAN_UINT16(data + 6));
+ _variables.resize(data.getUint16SEAt(2));
+ _baseVars = buf.subspan<const uint16>(data.getUint16SEAt(4), _variables.size() * sizeof(uint16));
+ _methodCount = buf.getUint16SEAt(data.getUint16SEAt(6));
for (int i = 0; i < _methodCount * 2 + 3; ++i) {
- _baseMethod.push_back(READ_SCI11ENDIAN_UINT16(buf + READ_SCI11ENDIAN_UINT16(data + 6) + i * 2));
+ _baseMethod.push_back(buf.getUint16SEAt(data.getUint16SEAt(6) + i * 2));
}
} else if (getSciVersion() == SCI_VERSION_3) {
initSelectorsSci3(buf);
@@ -77,9 +78,9 @@ void Object::init(byte *buf, reg_t obj_pos, bool initVariables) {
if (initVariables) {
if (getSciVersion() <= SCI_VERSION_2_1_LATE) {
for (uint i = 0; i < _variables.size(); i++)
- _variables[i] = make_reg(0, READ_SCI11ENDIAN_UINT16(data + (i * 2)));
+ _variables[i] = make_reg(0, data.getUint16SEAt(i * 2));
} else {
- _infoSelectorSci3 = make_reg(0, READ_SCI11ENDIAN_UINT16(_baseObj + 10));
+ _infoSelectorSci3 = make_reg(0, _baseObj.getUint16SEAt(10));
}
}
}
@@ -89,20 +90,20 @@ const Object *Object::getClass(SegManager *segMan) const {
}
int Object::locateVarSelector(SegManager *segMan, Selector slc) const {
- const byte *buf = 0;
+ SciSpan<const byte> buf;
uint varnum = 0;
if (getSciVersion() <= SCI_VERSION_2_1_LATE) {
const Object *obj = getClass(segMan);
varnum = getSciVersion() <= SCI_VERSION_1_LATE ? getVarCount() : obj->getVariable(1).toUint16();
- buf = (const byte *)obj->_baseVars;
+ buf = obj->_baseVars.subspan<const byte>(0);
} else if (getSciVersion() == SCI_VERSION_3) {
varnum = _variables.size();
- buf = (const byte *)_baseVars;
+ buf = _baseVars.subspan<const byte>(0);
}
for (uint i = 0; i < varnum; i++)
- if (READ_SCI11ENDIAN_UINT16(buf + (i << 1)) == slc) // Found it?
+ if (buf.getUint16SEAt(i << 1) == slc) // Found it?
return i; // report success
return -1; // Failed
@@ -136,14 +137,14 @@ int Object::propertyOffsetToId(SegManager *segMan, int propertyOffset) const {
}
if (getSciVersion() < SCI_VERSION_1_1) {
- const byte *selectoroffset = ((const byte *)(_baseObj)) + kOffsetSelectorSegment + selectors * 2;
- return READ_SCI11ENDIAN_UINT16(selectoroffset + propertyOffset);
+ const SciSpan<const byte> selectoroffset = _baseObj.subspan(kOffsetSelectorSegment + selectors * 2);
+ return selectoroffset.getUint16SEAt(propertyOffset);
} else {
const Object *obj = this;
if (!isClass())
obj = segMan->getObject(getSuperClassSelector());
- return READ_SCI11ENDIAN_UINT16((const byte *)obj->_baseVars + propertyOffset);
+ return obj->_baseVars.subspan<const byte>(0).getUint16SEAt(propertyOffset);
}
}
@@ -246,9 +247,9 @@ bool Object::initBaseObject(SegManager *segMan, reg_t addr, bool doInitSuperClas
const int EXTRA_GROUPS = 3;
-void Object::initSelectorsSci3(const byte *buf) {
- const byte *groupInfo = _baseObj + 16;
- const byte *selectorBase = groupInfo + EXTRA_GROUPS * 32 * 2;
+void Object::initSelectorsSci3(const SciSpan<const byte> &buf) {
+ const SciSpan<const byte> groupInfo = _baseObj.subspan(16);
+ const SciSpan<const byte> selectorBase = groupInfo.subspan(EXTRA_GROUPS * 32 * 2);
int groups = g_sci->getKernel()->getSelectorNamesSize()/32;
int methods, properties;
@@ -266,16 +267,16 @@ void Object::initSelectorsSci3(const byte *buf) {
// there are, so we count them first.
for (int groupNr = 0; groupNr < groups; ++groupNr) {
byte groupLocation = groupInfo[groupNr];
- const byte *seeker = selectorBase + groupLocation * 32 * 2;
+ const SciSpan<const byte> seeker = selectorBase.subspan(groupLocation * 32 * 2);
if (groupLocation != 0) {
// This object actually has selectors belonging to this group
- int typeMask = READ_SCI11ENDIAN_UINT32(seeker);
+ int typeMask = seeker.getUint32SEAt(0);
_mustSetViewVisible[groupNr] = (typeMask & 1);
for (int bit = 2; bit < 32; ++bit) {
- int value = READ_SCI11ENDIAN_UINT16(seeker + bit * 2);
+ int value = seeker.getUint16SEAt(bit * 2);
if (typeMask & (1 << bit)) { // Property
++properties;
} else if (value != 0xffff) { // Method
@@ -300,15 +301,15 @@ void Object::initSelectorsSci3(const byte *buf) {
// and method pointers
for (int groupNr = 0; groupNr < groups; ++groupNr) {
byte groupLocation = groupInfo[groupNr];
- const byte *seeker = selectorBase + groupLocation * 32 * 2;
+ const SciSpan<const byte> seeker = selectorBase.subspan(groupLocation * 32 * 2);
if (groupLocation != 0) {
// This object actually has selectors belonging to this group
- int typeMask = READ_SCI11ENDIAN_UINT32(seeker);
+ int typeMask = seeker.getUint32SEAt(0);
int groupBaseId = groupNr * 32;
for (int bit = 2; bit < 32; ++bit) {
- int value = READ_SCI11ENDIAN_UINT16(seeker + bit * 2);
+ int value = seeker.getUint16SEAt(bit * 2);
if (typeMask & (1 << bit)) { // Property
// FIXME: We really shouldn't be doing endianness
@@ -325,7 +326,7 @@ void Object::initSelectorsSci3(const byte *buf) {
++propertyCounter;
} else if (value != 0xffff) { // Method
_baseMethod.push_back(groupBaseId + bit);
- _baseMethod.push_back(value + READ_SCI11ENDIAN_UINT32(buf));
+ _baseMethod.push_back(value + buf.getUint32SEAt(0));
// methodOffsets[methodCounter] = (seeker + bit * 2) - buf;
++methodCounter;
} else {
@@ -336,10 +337,10 @@ void Object::initSelectorsSci3(const byte *buf) {
}
}
- _speciesSelectorSci3 = make_reg(0, READ_SCI11ENDIAN_UINT16(_baseObj + 4));
- _superClassPosSci3 = make_reg(0, READ_SCI11ENDIAN_UINT16(_baseObj + 8));
+ _speciesSelectorSci3 = make_reg(0, _baseObj.getUint16SEAt(4));
+ _superClassPosSci3 = make_reg(0, _baseObj.getUint16SEAt(8));
- _baseVars = propertyIds;
+ _baseVars = SciSpan<const uint16>(propertyIds, properties);
_methodCount = methods;
_propertyOffsetsSci3 = propertyOffsets;
//_methodOffsetsSci3 = methodOffsets;
diff --git a/engines/sci/engine/object.h b/engines/sci/engine/object.h
index 74a908a810..61f942c04a 100644
--- a/engines/sci/engine/object.h
+++ b/engines/sci/engine/object.h
@@ -59,9 +59,11 @@ enum infoSelectorFlags {
};
enum ObjectOffsets {
- kOffsetLocalVariables = -6,
- kOffsetFunctionArea = -4,
- kOffsetSelectorCounter = -2,
+ kOffsetHeaderSize = 6,
+ kOffsetHeaderLocalVariables = 0,
+ kOffsetHeaderFunctionArea = 2,
+ kOffsetHeaderSelectorCounter = 4,
+
kOffsetSelectorSegment = 0,
kOffsetInfoSelectorSci0 = 4,
kOffsetNamePointerSci0 = 6,
@@ -74,21 +76,48 @@ public:
Object() {
_offset = getSciVersion() < SCI_VERSION_1_1 ? 0 : 5;
_flags = 0;
- _baseObj = 0;
- _baseVars = 0;
+ _baseObj.clear();
+ _baseVars.clear();
_methodCount = 0;
- _propertyOffsetsSci3 = 0;
+ _propertyOffsetsSci3 = nullptr;
}
~Object() {
if (getSciVersion() == SCI_VERSION_3) {
- // FIXME: memory leak! Commented out because of reported heap
- // corruption by MSVC (e.g. in LSL7, when it starts)
- //free(_baseVars);
- //_baseVars = 0;
- //free(_propertyOffsetsSci3);
- //_propertyOffsetsSci3 = 0;
+ // TODO: This is super gross
+ free(const_cast<uint16 *>(_baseVars.data()));
+ _baseVars.clear();
+ free(_propertyOffsetsSci3);
+ _propertyOffsetsSci3 = nullptr;
+ }
+ }
+
+ Object &operator=(const Object &other) {
+ _baseObj = other._baseObj;
+ _baseMethod = other._baseMethod;
+ _variables = other._variables;
+ _methodCount = other._methodCount;
+ _flags = other._flags;
+ _offset = other._offset;
+ _pos = other._pos;
+
+ if (getSciVersion() == SCI_VERSION_3) {
+ uint16 *baseVars = (uint16 *)malloc(other._baseVars.byteSize());
+ other._baseVars.unsafeCopyDataTo(baseVars);
+ _baseVars = SciSpan<const uint16>(baseVars, other._baseVars.size());
+
+ _propertyOffsetsSci3 = (uint32 *)malloc(sizeof(uint32) * _variables.size());
+ memcpy(_propertyOffsetsSci3, other._propertyOffsetsSci3, sizeof(uint32) * _variables.size());
+
+ _superClassPosSci3 = other._superClassPosSci3;
+ _speciesSelectorSci3 = other._speciesSelectorSci3;
+ _infoSelectorSci3 = other._infoSelectorSci3;
+ _mustSetViewVisible = other._mustSetViewVisible;
+ } else {
+ _baseVars = other._baseVars;
}
+
+ return *this;
}
reg_t getSpeciesSelector() const {
@@ -181,7 +210,7 @@ public:
if (getSciVersion() < SCI_VERSION_3)
return _variables[4];
else // SCI3
- return make_reg(0, READ_SCI11ENDIAN_UINT16(_baseObj + 6));
+ return make_reg(0, _baseObj.getUint16SEAt(6));
}
void setClassScriptSelector(reg_t value) {
@@ -192,7 +221,7 @@ public:
error("setClassScriptSelector called for SCI3");
}
- Selector getVarSelector(uint16 i) const { return READ_SCI11ENDIAN_UINT16(_baseVars + i); }
+ Selector getVarSelector(uint16 i) const { return _baseVars.getUint16SEAt(i); }
reg_t getFunction(uint16 i) const {
uint16 offset = (getSciVersion() < SCI_VERSION_1_1) ? _methodCount + 1 + i : i * 2 + 2;
@@ -236,7 +265,7 @@ public:
uint getVarCount() const { return _variables.size(); }
- void init(byte *buf, reg_t obj_pos, bool initVariables = true);
+ void init(const SciSpan<const byte> &buf, reg_t obj_pos, bool initVariables = true);
reg_t getVariable(uint var) const { return _variables[var]; }
reg_t &getVariableRef(uint var) { return _variables[var]; }
@@ -247,9 +276,9 @@ public:
void saveLoadWithSerializer(Common::Serializer &ser);
void cloneFromObject(const Object *obj) {
- _baseObj = obj ? obj->_baseObj : NULL;
+ _baseObj = obj ? obj->_baseObj : SciSpan<const byte>();
_baseMethod = obj ? obj->_baseMethod : Common::Array<uint16>();
- _baseVars = obj ? obj->_baseVars : NULL;
+ _baseVars = obj ? obj->_baseVars : SciSpan<const uint16>();
}
bool relocateSci0Sci21(SegmentId segment, int location, size_t scriptSize);
@@ -260,17 +289,17 @@ public:
void initSpecies(SegManager *segMan, reg_t addr);
void initSuperClass(SegManager *segMan, reg_t addr);
bool initBaseObject(SegManager *segMan, reg_t addr, bool doInitSuperClass = true);
- void syncBaseObject(const byte *ptr) { _baseObj = ptr; }
+ void syncBaseObject(const SciSpan<const byte> &ptr) { _baseObj = ptr; }
bool mustSetViewVisibleSci3(int selector) const { return _mustSetViewVisible[selector/32]; }
private:
- void initSelectorsSci3(const byte *buf);
+ void initSelectorsSci3(const SciSpan<const byte> &buf);
- const byte *_baseObj; /**< base + object offset within base */
- const uint16 *_baseVars; /**< Pointer to the varselector area for this object */
+ SciSpan<const byte> _baseObj; /**< base + object offset within base */
+ SciSpan<const uint16> _baseVars; /**< Pointer to the varselector area for this object */
Common::Array<uint16> _baseMethod; /**< Pointer to the method selector area for this object */
- uint32 *_propertyOffsetsSci3; /**< This is used to enable relocation of property valuesa in SCI3 */
+ uint32 *_propertyOffsetsSci3; /**< This is used to enable relocation of property values in SCI3 */
Common::Array<reg_t> _variables;
uint16 _methodCount;
diff --git a/engines/sci/engine/savegame.cpp b/engines/sci/engine/savegame.cpp
index a3a690be59..f05fdc5cb9 100644
--- a/engines/sci/engine/savegame.cpp
+++ b/engines/sci/engine/savegame.cpp
@@ -255,7 +255,7 @@ void SegManager::saveLoadWithSerializer(Common::Serializer &s) {
ObjMap objects = scr->getObjectMap();
for (ObjMap::iterator it = objects.begin(); it != objects.end(); ++it)
- it->_value.syncBaseObject(scr->getBuf(it->_value.getPos().getOffset()));
+ it->_value.syncBaseObject(SciSpan<const byte>(scr->getBuf(it->_value.getPos().getOffset()), scr->getBufSize() - it->_value.getPos().getOffset()));
}
@@ -437,37 +437,38 @@ void HunkTable::saveLoadWithSerializer(Common::Serializer &s) {
void Script::syncStringHeap(Common::Serializer &s) {
if (getSciVersion() < SCI_VERSION_1_1) {
// Sync all of the SCI_OBJ_STRINGS blocks
- byte *buf = _buf;
+ SciSpan<byte> buf = (SciSpan<byte> &)*_buf;
bool oldScriptHeader = (getSciVersion() == SCI_VERSION_0_EARLY);
if (oldScriptHeader)
buf += 2;
- do {
- int blockType = READ_LE_UINT16(buf);
+ for (;;) {
+ int blockType = buf.getUint16LEAt(0);
int blockSize;
if (blockType == 0)
break;
- blockSize = READ_LE_UINT16(buf + 2);
+ blockSize = buf.getUint16LEAt(2);
assert(blockSize > 0);
if (blockType == SCI_OBJ_STRINGS)
- s.syncBytes(buf, blockSize);
+ s.syncBytes(buf.getUnsafeDataAt(0, blockSize), blockSize);
buf += blockSize;
- } while (1);
+ }
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE){
// Strings in SCI1.1 come after the object instances
- byte *buf = _heapStart + 4 + READ_SCI11ENDIAN_UINT16(_heapStart + 2) * 2;
+ SciSpan<byte> buf = _heap.subspan<byte>(4 + _heap.getUint16SEAt(2) * 2);
// Skip all of the objects
- while (READ_SCI11ENDIAN_UINT16(buf) == SCRIPT_OBJECT_MAGIC_NUMBER)
- buf += READ_SCI11ENDIAN_UINT16(buf + 2) * 2;
+ while (buf.getUint16SEAt(0) == SCRIPT_OBJECT_MAGIC_NUMBER)
+ buf += buf.getUint16SEAt(2) * 2;
// Now, sync everything till the end of the buffer
- s.syncBytes(buf, _heapSize - (buf - _heapStart));
+ const int length = _heap.size() - (buf - _heap);
+ s.syncBytes(buf.getUnsafeDataAt(0, length), length);
} else if (getSciVersion() == SCI_VERSION_3) {
warning("TODO: syncStringHeap(): Implement SCI3 variant");
}
@@ -1062,7 +1063,7 @@ bool gamestate_save(EngineState *s, Common::WriteStream *fh, const Common::Strin
meta.saveTime = ((curTime.tm_hour & 0xFF) << 16) | (((curTime.tm_min) & 0xFF) << 8) | ((curTime.tm_sec) & 0xFF);
Resource *script0 = g_sci->getResMan()->findResource(ResourceId(kResourceTypeScript, 0), false);
- meta.script0Size = script0->size;
+ meta.script0Size = script0->size();
meta.gameObjectOffset = g_sci->getGameObject().getOffset();
// Checking here again
@@ -1199,7 +1200,7 @@ void gamestate_restore(EngineState *s, Common::SeekableReadStream *fh) {
if (meta.gameObjectOffset > 0 && meta.script0Size > 0) {
Resource *script0 = g_sci->getResMan()->findResource(ResourceId(kResourceTypeScript, 0), false);
- if (script0->size != meta.script0Size || g_sci->getGameObject().getOffset() != meta.gameObjectOffset) {
+ if (script0->size() != meta.script0Size || g_sci->getGameObject().getOffset() != meta.gameObjectOffset) {
showScummVMDialog("This saved game was created with a different version of the game, unable to load it");
s->r_acc = TRUE_REG; // signal failure
diff --git a/engines/sci/engine/script.cpp b/engines/sci/engine/script.cpp
index 8a973bd217..f790b411cf 100644
--- a/engines/sci/engine/script.cpp
+++ b/engines/sci/engine/script.cpp
@@ -33,8 +33,13 @@
namespace Sci {
+const char *sciObjectTypeNames[] = {
+ "terminator", "object", "code", "synonyms", "said", "strings", "class",
+ "exports", "pointers", "preload text", "local vars"
+};
+
Script::Script()
- : SegmentObj(SEG_TYPE_SCRIPT), _buf(NULL) {
+ : SegmentObj(SEG_TYPE_SCRIPT), _buf() {
freeScript();
}
@@ -45,16 +50,12 @@ Script::~Script() {
void Script::freeScript() {
_nr = 0;
- free(_buf);
- _buf = NULL;
- _bufSize = 0;
- _scriptSize = 0;
- _heapStart = NULL;
- _heapSize = 0;
-
- _exportTable = NULL;
+ _buf.clear();
+ _script.clear();
+ _heap.clear();
+ _exports.clear();
_numExports = 0;
- _synonyms = NULL;
+ _synonyms.clear();
_numSynonyms = 0;
_localsOffset = 0;
@@ -80,15 +81,16 @@ enum {
void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptPatcher) {
freeScript();
- Resource *script = resMan->findResource(ResourceId(kResourceTypeScript, script_nr), 0);
+ Resource *script = resMan->findResource(ResourceId(kResourceTypeScript, script_nr), false);
if (!script)
error("Script %d not found", script_nr);
_nr = script_nr;
- _bufSize = _scriptSize = script->size;
+ uint32 scriptSize = script->size();
+ uint32 bufSize = scriptSize;
if (getSciVersion() == SCI_VERSION_0_EARLY) {
- _bufSize += READ_LE_UINT16(script->data) * 2;
+ bufSize += script->getUint16LEAt(0) * 2;
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
// In SCI1.1 - SCI2.1, the heap was in a separate space from the script. We append
// it to the end of the script, and adjust addressing accordingly.
@@ -97,18 +99,17 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
// worked for SCI11, SCI2 and SCI21 games. SCI3 games use a different
// script format, and theoretically they can exceed the 64KB boundary
// using relocation.
- Resource *heap = resMan->findResource(ResourceId(kResourceTypeHeap, script_nr), 0);
- _bufSize += heap->size;
- _heapSize = heap->size;
+ Resource *heap = resMan->findResource(ResourceId(kResourceTypeHeap, script_nr), false);
+ bufSize += heap->size();
// Ensure that the start of the heap resource can be word-aligned.
- if (script->size & 2) {
- _bufSize++;
- _scriptSize++;
+ if (script->size() & 2) {
+ ++bufSize;
+ ++scriptSize;
}
// As mentioned above, the script and the heap together should not exceed 64KB
- if (script->size + heap->size > 65535)
+ if (script->size() + heap->size() > 65535)
error("Script and heap sizes combined exceed 64K. This means a fundamental "
"design bug was made regarding SCI1.1 and newer games.\n"
"Please report this error to the ScummVM team");
@@ -125,13 +126,13 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
// RAMA: 70
//
// TODO: Remove this once such a mechanism is in place
- if (script->size > 65535)
- warning("TODO: SCI script %d is over 64KB - it's %d bytes long. This can't "
- "be fully handled at the moment", script_nr, script->size);
+ if (script->size() > 65535)
+ warning("TODO: SCI script %d is over 64KB - it's %lu bytes long. This can't "
+ "be fully handled at the moment", script_nr, script->size());
}
uint extraLocalsWorkaround = 0;
- if (g_sci->getGameId() == GID_FANMADE && _nr == 1 && script->size == 11140) {
+ if (g_sci->getGameId() == GID_FANMADE && _nr == 1 && script->size() == 11140) {
// WORKAROUND: Script 1 in Ocean Battle doesn't have enough locals to
// fit the string showing how many shots are left (a nasty script bug,
// corrupting heap memory). We add 10 more locals so that it has enough
@@ -139,60 +140,71 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
// #3059871.
extraLocalsWorkaround = 10;
}
- _bufSize += extraLocalsWorkaround * 2;
+ bufSize += extraLocalsWorkaround * 2;
- _buf = (byte *)malloc(_bufSize);
- assert(_buf);
-
- assert(_bufSize >= script->size);
- memcpy(_buf, script->data, script->size);
+ SciSpan<byte> outBuffer = _buf->allocate(bufSize, script->name() + " buffer");
+ script->copyDataTo(outBuffer);
+ // The word-aligned script size is used here because other parts of the code
+ // currently rely on finding the start of the heap by reading the script
+ // size
+ _script = _buf->subspan(0, scriptSize, script->name());
if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- Resource *heap = resMan->findResource(ResourceId(kResourceTypeHeap, _nr), 0);
- assert(heap != 0);
-
- _heapStart = _buf + _scriptSize;
+ Resource *heap = resMan->findResource(ResourceId(kResourceTypeHeap, _nr), false);
+ assert(heap);
- assert(_bufSize - _scriptSize >= heap->size);
- memcpy(_heapStart, heap->data, heap->size);
+ SciSpan<byte> outHeap = outBuffer.subspan(scriptSize, heap->size(), heap->name(), 0);
+ heap->copyDataTo(outHeap);
+ _heap = outHeap;
}
// Check scripts (+ possibly SCI 1.1 heap) for matching signatures and patch those, if found
- scriptPatcher->processScript(_nr, _buf, _bufSize);
+ scriptPatcher->processScript(_nr, outBuffer);
if (getSciVersion() <= SCI_VERSION_1_LATE) {
- _exportTable = (const uint16 *)findBlockSCI0(SCI_OBJ_EXPORTS);
- if (_exportTable) {
- _numExports = READ_SCI11ENDIAN_UINT16(_exportTable + 1);
- _exportTable += 3; // skip header plus 2 bytes (_exportTable is a uint16 pointer)
+ SciSpan<const uint16> exportTable = findBlockSCI0(SCI_OBJ_EXPORTS).subspan<const uint16>(0);
+ if (exportTable) {
+ // The export table is after the block header (4 bytes / 2 uint16s)
+ // and the number of exports (2 bytes / 1 uint16).
+ // The exports span does not need to be explicitly sized since the
+ // maximum size was already determined by findBlockSCI0
+ _exports = exportTable.subspan(3);
+ _numExports = exportTable.getUint16SEAt(2);
}
- _synonyms = findBlockSCI0(SCI_OBJ_SYNONYMS);
- if (_synonyms) {
- _numSynonyms = READ_SCI11ENDIAN_UINT16(_synonyms + 2) / 4;
- _synonyms += 4; // skip header
+
+ SciSpan<const byte> synonymTable = findBlockSCI0(SCI_OBJ_SYNONYMS);
+ if (synonymTable) {
+ // the synonyms table is after the block header (4 bytes),
+ // and each synonym entry is 4 bytes
+ _synonyms = synonymTable.subspan(4);
+ _numSynonyms = _synonyms.size() / 4;
}
- const byte* localsBlock = findBlockSCI0(SCI_OBJ_LOCALVARS);
- if (localsBlock) {
- _localsOffset = localsBlock - _buf + 4;
- _localsCount = (READ_LE_UINT16(_buf + _localsOffset - 2) - 4) >> 1; // half block size
+
+ SciSpan<const byte> localsTable = findBlockSCI0(SCI_OBJ_LOCALVARS);
+ if (localsTable) {
+ // skip header (4 bytes)
+ _localsOffset = localsTable - *_buf + 4;
+ _localsCount = (_buf->getUint16LEAt(_localsOffset - 2) - 4) >> 1; // half block size
}
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- _numExports = READ_SCI11ENDIAN_UINT16(_buf + kSci11NumExportsOffset);
+ _numExports = _buf->getUint16SEAt(kSci11NumExportsOffset);
if (_numExports) {
- _exportTable = (const uint16 *)(_buf + kSci11ExportTableOffset);
+ _exports = _buf->subspan<const uint16>(kSci11ExportTableOffset, _numExports * sizeof(uint16));
}
- _localsOffset = _scriptSize + 4;
- _localsCount = READ_SCI11ENDIAN_UINT16(_buf + _localsOffset - 2);
+ _localsOffset = _script.size() + 4;
+ _localsCount = _buf->getUint16SEAt(_localsOffset - 2);
} else if (getSciVersion() == SCI_VERSION_3) {
- _localsCount = READ_LE_UINT16(_buf + 12);
- _exportTable = (const uint16 *)(_buf + 22);
- _numExports = READ_LE_UINT16(_buf + 20);
- // SCI3 local variables always start dword-aligned
- if (_numExports % 2)
- _localsOffset = 22 + _numExports * 2;
- else
- _localsOffset = 24 + _numExports * 2;
+ _localsCount = _buf->getUint16LEAt(12);
+ _numExports = _buf->getUint16LEAt(20);
+ if (_numExports) {
+ _exports = _buf->subspan<const uint16>(22, _numExports * sizeof(uint16));
+ // SCI3 local variables always start dword-aligned
+ if (_numExports % 2)
+ _localsOffset = 22 + _numExports * 2;
+ else
+ _localsOffset = 24 + _numExports * 2;
+ }
}
// WORKAROUND: Increase locals, if needed (check above)
@@ -203,7 +215,7 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
// Old script block. There won't be a localvar block in this case.
// Instead, the script starts with a 16 bit int specifying the
// number of locals we need; these are then allocated and zeroed.
- _localsCount = READ_LE_UINT16(_buf);
+ _localsCount = _buf->getUint16LEAt(0);
_localsOffset = -_localsCount * 2; // Make sure it's invalid
} else {
// SCI0 late and newer
@@ -211,8 +223,8 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
if (!_localsCount)
_localsOffset = 0;
- if (_localsOffset + _localsCount * 2 + 1 >= (int)_bufSize) {
- error("Locals extend beyond end of script: offset %04x, count %d vs size %d", _localsOffset, _localsCount, (int)_bufSize);
+ if (_localsOffset + _localsCount * 2 + 1 >= (int)_buf->size()) {
+ error("Locals extend beyond end of script: offset %04x, count %d vs size %d", _localsOffset, _localsCount, (int)_buf->size());
//_localsCount = (_bufSize - _localsOffset) >> 1;
}
}
@@ -223,11 +235,9 @@ void Script::load(int script_nr, ResourceManager *resMan, ScriptPatcher *scriptP
void Script::identifyOffsets() {
offsetLookupArrayEntry arrayEntry;
- const byte *scriptDataPtr = NULL;
- const byte *stringStartPtr = NULL;
- const byte *stringDataPtr = NULL;
- uint32 scriptDataLeft = 0;
- uint32 stringDataLeft = 0;
+ SciSpan<const byte> scriptDataPtr;
+ SciSpan<const byte> stringStartPtr;
+ SciSpan<const byte> stringDataPtr;
byte stringDataByte = 0;
uint16 typeObject_id = 0;
uint16 typeString_id = 0;
@@ -244,38 +254,34 @@ void Script::identifyOffsets() {
if (getSciVersion() < SCI_VERSION_1_1) {
// SCI0 + SCI1
- scriptDataPtr = _buf;
- scriptDataLeft = _bufSize;
+ scriptDataPtr = *_buf;
// Go through all blocks
if (getSciVersion() == SCI_VERSION_0_EARLY) {
- if (scriptDataLeft < 2)
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script %d", _nr);
- scriptDataPtr += 2;
- scriptDataLeft -= 2;
+ scriptDataPtr += 2;
}
- do {
- if (scriptDataLeft < 2)
+ for (;;) {
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script %d", _nr);
- blockType = READ_LE_UINT16(scriptDataPtr);
- scriptDataPtr += 2;
- scriptDataLeft -= 2;
+ blockType = scriptDataPtr.getUint16LEAt(0);
+ scriptDataPtr += 2;
if (blockType == 0) // end of blocks detected
break;
- if (scriptDataLeft < 2)
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script %d", _nr);
- blockSize = READ_LE_UINT16(scriptDataPtr);
+ blockSize = scriptDataPtr.getUint16LEAt(0);
if (blockSize < 4)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
- blockSize -= 4; // block size includes block-type UINT16 and block-size UINT16
- scriptDataPtr += 2;
- scriptDataLeft -= 2;
+ blockSize -= 4; // block size includes block-type UINT16 and block-size UINT16
+ scriptDataPtr += 2;
- if (scriptDataLeft < blockSize)
+ if (scriptDataPtr.size() < blockSize)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
switch (blockType) {
@@ -284,7 +290,7 @@ void Script::identifyOffsets() {
typeObject_id++;
arrayEntry.type = SCI_SCR_OFFSET_TYPE_OBJECT;
arrayEntry.id = typeObject_id;
- arrayEntry.offset = scriptDataPtr - _buf + 8; // Calculate offset inside script data (VM uses +8)
+ arrayEntry.offset = scriptDataPtr - *_buf + 8; // Calculate offset inside script data (VM uses +8)
arrayEntry.stringSize = 0;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupObjectCount++;
@@ -292,18 +298,17 @@ void Script::identifyOffsets() {
case SCI_OBJ_STRINGS:
// string block detected, we now grab all NUL terminated strings out of this block
- stringDataPtr = scriptDataPtr;
- stringDataLeft = blockSize;
+ stringDataPtr = scriptDataPtr.subspan(0, blockSize);
arrayEntry.type = SCI_SCR_OFFSET_TYPE_STRING;
- do {
- if (stringDataLeft < 1) // no more bytes left
+ for (;;) {
+ if (stringDataPtr.size() < 1) // no more bytes left
break;
stringStartPtr = stringDataPtr;
- if (stringDataLeft == 1) {
+ if (stringDataPtr.size() == 1) {
// only 1 byte left and that byte is a [00], in that case we also exit
stringDataByte = *stringStartPtr;
if (stringDataByte == 0x00)
@@ -311,46 +316,44 @@ void Script::identifyOffsets() {
}
// now look for terminating [NUL]
- do {
+ for (;;) {
stringDataByte = *stringDataPtr;
stringDataPtr++;
- stringDataLeft--;
if (!stringDataByte) // NUL found, exit this loop
break;
- if (stringDataLeft < 1) {
+ if (stringDataPtr.size() < 1) {
// no more bytes left
warning("Script::identifyOffsets(): string without terminating NUL in script %d", _nr);
break;
}
- } while (1);
+ }
if (stringDataByte)
break;
typeString_id++;
arrayEntry.id = typeString_id;
- arrayEntry.offset = stringStartPtr - _buf; // Calculate offset inside script data
+ arrayEntry.offset = stringStartPtr - *_buf; // Calculate offset inside script data
arrayEntry.stringSize = stringDataPtr - stringStartPtr;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupStringCount++;
- } while (1);
+ }
break;
case SCI_OBJ_SAID:
// said block detected, we now try to find every single said "string" inside this block
// said strings are terminated with a 0xFF, the string itself may contain words (2 bytes), where
// the second byte of a word may also be a 0xFF.
- stringDataPtr = scriptDataPtr;
- stringDataLeft = blockSize;
+ stringDataPtr = scriptDataPtr.subspan(0, blockSize);
arrayEntry.type = SCI_SCR_OFFSET_TYPE_SAID;
- do {
- if (stringDataLeft < 1) // no more bytes left
+ for (;;) {
+ if (stringDataPtr.size() < 1) // no more bytes left
break;
stringStartPtr = stringDataPtr;
- if (stringDataLeft == 1) {
+ if (stringDataPtr.size() == 1) {
// only 1 byte left and that byte is a [00], in that case we also exit
// happens in some scripts, for example Conquests of Camelot, script 997
// may have been a bug in the compiler or just an intentional filler byte
@@ -360,30 +363,28 @@ void Script::identifyOffsets() {
}
// now look for terminating 0xFF
- do {
+ for (;;) {
stringDataByte = *stringDataPtr;
stringDataPtr++;
- stringDataLeft--;
if (stringDataByte == 0xFF) // Terminator found, exit this loop
break;
- if (stringDataLeft < 1) // no more bytes left
+ if (stringDataPtr.size() < 1) // no more bytes left
error("Script::identifyOffsets(): said-string without terminator in script %d", _nr);
if (stringDataByte < 0xF0) {
// Part of a word, skip second byte
stringDataPtr++;
- stringDataLeft--;
- if (stringDataLeft < 1) // no more bytes left
+ if (stringDataPtr.size() < 1) // no more bytes left
error("Script::identifyOffsets(): said-string without terminator in script %d", _nr);
}
- } while (1);
+ }
typeSaid_id++;
arrayEntry.id = typeSaid_id;
- arrayEntry.offset = stringStartPtr - _buf; // Calculate offset inside script data
+ arrayEntry.offset = stringStartPtr - *_buf; // Calculate offset inside script data
arrayEntry.stringSize = 0;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupSaidCount++;
- } while (1);
+ }
break;
default:
@@ -391,48 +392,44 @@ void Script::identifyOffsets() {
}
scriptDataPtr += blockSize;
- scriptDataLeft -= blockSize;
- } while (1);
+ }
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
// Strings in SCI1.1 up to SCI2 come after the object instances
- scriptDataPtr = _heapStart;
- scriptDataLeft = _heapSize;
+ scriptDataPtr = _heap;
enum {
- kExportSize = 2,
- kPropertySize = 2,
- kNumMethodsSize = 2,
+ kExportSize = sizeof(uint16),
+ kPropertySize = sizeof(uint16),
+ kNumMethodsSize = sizeof(uint16),
kPropDictEntrySize = 2,
kMethDictEntrySize = 4
};
- const byte *hunkPtr = _buf + kSci11ExportTableOffset + _numExports * kExportSize;
+ SciSpan<const byte> hunkPtr = _buf->subspan(kSci11ExportTableOffset + _numExports * kExportSize);
- if (scriptDataLeft < 4)
+ if (scriptDataPtr.size() < 4)
error("Script::identifyOffsets(): unexpected end of script in script %d", _nr);
- uint16 endOfStringOffset = READ_SCI11ENDIAN_UINT16(scriptDataPtr);
- uint16 objectStartOffset = READ_SCI11ENDIAN_UINT16(scriptDataPtr + 2) * 2 + 4;
+ uint16 endOfStringOffset = scriptDataPtr.getUint16SEAt(0);
+ uint16 objectStartOffset = scriptDataPtr.getUint16SEAt(2) * 2 + 4;
- if (scriptDataLeft < objectStartOffset)
+ if (scriptDataPtr.size() < objectStartOffset)
error("Script::identifyOffsets(): object start is beyond heap size in script %d", _nr);
- if (scriptDataLeft < endOfStringOffset)
+ if (scriptDataPtr.size() < endOfStringOffset)
error("Script::identifyOffsets(): end of string is beyond heap size in script %d", _nr);
- const byte *endOfStringPtr = scriptDataPtr + endOfStringOffset;
+ SciSpan<const byte> endOfStringPtr = scriptDataPtr.subspan(endOfStringOffset);
scriptDataPtr += objectStartOffset;
- scriptDataLeft -= objectStartOffset;
// go through all objects
- do {
- if (scriptDataLeft < 2)
+ for (;;) {
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script %d", _nr);
- blockType = READ_SCI11ENDIAN_UINT16(scriptDataPtr);
+ blockType = scriptDataPtr.getUint16SEAt(0);
scriptDataPtr += 2;
- scriptDataLeft -= 2;
if (blockType != SCRIPT_OBJECT_MAGIC_NUMBER)
break;
@@ -440,77 +437,73 @@ void Script::identifyOffsets() {
typeObject_id++;
arrayEntry.type = SCI_SCR_OFFSET_TYPE_OBJECT;
arrayEntry.id = typeObject_id;
- arrayEntry.offset = scriptDataPtr - _buf - 2; // the VM uses a pointer to the Magic-Number
+ arrayEntry.offset = scriptDataPtr - *_buf - 2; // the VM uses a pointer to the Magic-Number
arrayEntry.stringSize = 0;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupObjectCount++;
- if (scriptDataLeft < 2)
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script in script %d", _nr);
- const uint16 numProperties = READ_SCI11ENDIAN_UINT16(scriptDataPtr);
+ const uint16 numProperties = scriptDataPtr.getUint16SEAt(0);
blockSize = numProperties * kPropertySize;
if (blockSize < 4)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
scriptDataPtr += 2;
- scriptDataLeft -= 2;
- const uint16 scriptNum = READ_SCI11ENDIAN_UINT16(scriptDataPtr + 6);
+ const uint16 scriptNum = scriptDataPtr.getUint16SEAt(6);
if (scriptNum != 0xFFFF) {
hunkPtr += numProperties * kPropDictEntrySize;
}
- const uint16 numMethods = READ_SCI11ENDIAN_UINT16(hunkPtr);
+ const uint16 numMethods = hunkPtr.getUint16SEAt(0);
hunkPtr += kNumMethodsSize + numMethods * kMethDictEntrySize;
blockSize -= 4; // blocksize contains UINT16 type and UINT16 size
- if (scriptDataLeft < blockSize)
+ if (scriptDataPtr.size() < blockSize)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
scriptDataPtr += blockSize;
- scriptDataLeft -= blockSize;
- } while (1);
+ }
- _codeOffset = hunkPtr - _buf;
+ _codeOffset = hunkPtr - *_buf;
// now scriptDataPtr points to right at the start of the strings
if (scriptDataPtr > endOfStringPtr)
error("Script::identifyOffsets(): string block / end-of-string block mismatch in script %d", _nr);
- stringDataPtr = scriptDataPtr;
- stringDataLeft = endOfStringPtr - scriptDataPtr; // Calculate byte count within string-block
+ stringDataPtr = scriptDataPtr.subspan(0, endOfStringPtr - scriptDataPtr);
arrayEntry.type = SCI_SCR_OFFSET_TYPE_STRING;
- do {
- if (stringDataLeft < 1) // no more bytes left
+ for (;;) {
+ if (stringDataPtr.size() < 1) // no more bytes left
break;
stringStartPtr = stringDataPtr;
// now look for terminating [NUL]
- do {
+ for (;;) {
stringDataByte = *stringDataPtr;
stringDataPtr++;
- stringDataLeft--;
if (!stringDataByte) // NUL found, exit this loop
break;
- if (stringDataLeft < 1) {
+ if (stringDataPtr.size() < 1) {
// no more bytes left
warning("Script::identifyOffsets(): string without terminating NUL in script %d", _nr);
break;
}
- } while (1);
+ }
if (stringDataByte)
break;
typeString_id++;
arrayEntry.id = typeString_id;
- arrayEntry.offset = stringStartPtr - _buf; // Calculate offset inside script data
+ arrayEntry.offset = stringStartPtr - *_buf; // Calculate offset inside script data
arrayEntry.stringSize = stringDataPtr - stringStartPtr;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupStringCount++;
- } while (1);
+ }
} else if (getSciVersion() == SCI_VERSION_3) {
// SCI3
@@ -518,25 +511,23 @@ void Script::identifyOffsets() {
uint32 sci3RelocationOffset = 0;
uint32 sci3BoundaryOffset = 0;
- if (_bufSize < 22)
+ if (_buf->size() < 22)
error("Script::identifyOffsets(): script %d smaller than expected SCI3-header", _nr);
- sci3StringOffset = READ_LE_UINT32(_buf + 4);
- sci3RelocationOffset = READ_LE_UINT32(_buf + 8);
+ sci3StringOffset = _buf->getUint32LEAt(4);
+ sci3RelocationOffset = _buf->getUint32LEAt(8);
- if (sci3RelocationOffset > _bufSize)
+ if (sci3RelocationOffset > _buf->size())
error("Script::identifyOffsets(): relocation offset is beyond end of script %d", _nr);
// First we get all the objects
scriptDataPtr = getSci3ObjectsPointer();
- scriptDataLeft = _bufSize - (scriptDataPtr - _buf);
- do {
- if (scriptDataLeft < 2)
+ for (;;) {
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script %d", _nr);
- blockType = READ_SCI11ENDIAN_UINT16(scriptDataPtr);
- scriptDataPtr += 2;
- scriptDataLeft -= 2;
+ blockType = scriptDataPtr.getUint16SEAt(0);
+ scriptDataPtr += 2;
if (blockType != SCRIPT_OBJECT_MAGIC_NUMBER)
break;
@@ -544,48 +535,45 @@ void Script::identifyOffsets() {
typeObject_id++;
arrayEntry.type = SCI_SCR_OFFSET_TYPE_OBJECT;
arrayEntry.id = typeObject_id;
- arrayEntry.offset = scriptDataPtr - _buf - 2; // the VM uses a pointer to the Magic-Number
+ arrayEntry.offset = scriptDataPtr - *_buf - 2; // the VM uses a pointer to the Magic-Number
arrayEntry.stringSize = 0;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupObjectCount++;
- if (scriptDataLeft < 2)
+ if (scriptDataPtr.size() < 2)
error("Script::identifyOffsets(): unexpected end of script in script %d", _nr);
- blockSize = READ_SCI11ENDIAN_UINT16(scriptDataPtr);
+ blockSize = scriptDataPtr.getUint16SEAt(0);
if (blockSize < 4)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
scriptDataPtr += 2;
- scriptDataLeft -= 2;
blockSize -= 4; // blocksize contains UINT16 type and UINT16 size
- if (scriptDataLeft < blockSize)
+ if (scriptDataPtr.size() < blockSize)
error("Script::identifyOffsets(): invalid block size in script %d", _nr);
scriptDataPtr += blockSize;
- scriptDataLeft -= blockSize;
- } while (1);
+ }
// And now we get all the strings
if (sci3StringOffset > 0) {
// string offset set, we expect strings
- if (sci3StringOffset > _bufSize)
+ if (sci3StringOffset > _buf->size())
error("Script::identifyOffsets(): string offset is beyond end of script %d", _nr);
if (sci3RelocationOffset < sci3StringOffset)
error("Script::identifyOffsets(): string offset points beyond relocation offset in script %d", _nr);
- stringDataPtr = _buf + sci3StringOffset;
- stringDataLeft = sci3RelocationOffset - sci3StringOffset;
+ stringDataPtr = _buf->subspan(sci3StringOffset, sci3RelocationOffset - sci3StringOffset);
arrayEntry.type = SCI_SCR_OFFSET_TYPE_STRING;
- do {
- if (stringDataLeft < 1) // no more bytes left
+ for (;;) {
+ if (stringDataPtr.size() < 1) // no more bytes left
break;
stringStartPtr = stringDataPtr;
- if (stringDataLeft == 1) {
+ if (stringDataPtr.size() == 1) {
// only 1 byte left and that byte is a [00], in that case we also exit
stringDataByte = *stringStartPtr;
if (stringDataByte == 0x00)
@@ -593,60 +581,57 @@ void Script::identifyOffsets() {
}
// now look for terminating [NUL]
- do {
+ for (;;) {
stringDataByte = *stringDataPtr;
stringDataPtr++;
- stringDataLeft--;
if (!stringDataByte) // NUL found, exit this loop
break;
- if (stringDataLeft < 1) {
+ if (stringDataPtr.size() < 1) {
// no more bytes left
warning("Script::identifyOffsets(): string without terminating NUL in script %d", _nr);
break;
}
- } while (1);
+ }
if (stringDataByte)
break;
typeString_id++;
arrayEntry.id = typeString_id;
- arrayEntry.offset = stringStartPtr - _buf; // Calculate offset inside script data
+ arrayEntry.offset = stringStartPtr - *_buf; // Calculate offset inside script data
arrayEntry.stringSize = stringDataPtr - stringStartPtr;
_offsetLookupArray.push_back(arrayEntry);
_offsetLookupStringCount++;
// SCI3 seems to have aligned all string on DWORD boundaries
- sci3BoundaryOffset = stringDataPtr - _buf; // Calculate current offset inside script data
+ sci3BoundaryOffset = stringDataPtr - *_buf; // Calculate current offset inside script data
sci3BoundaryOffset = sci3BoundaryOffset & 3; // Check boundary offset
if (sci3BoundaryOffset) {
// lower 2 bits are set? Then we have to adjust the offset
sci3BoundaryOffset = 4 - sci3BoundaryOffset;
- if (stringDataLeft < sci3BoundaryOffset)
+ if (stringDataPtr.size() < sci3BoundaryOffset)
error("Script::identifyOffsets(): SCI3 string boundary adjustment goes beyond end of string block in script %d", _nr);
- stringDataLeft -= sci3BoundaryOffset;
stringDataPtr += sci3BoundaryOffset;
}
- } while (1);
+ }
}
- return;
}
}
-const byte *Script::getSci3ObjectsPointer() {
- const byte *ptr = 0;
+SciSpan<const byte> Script::getSci3ObjectsPointer() {
+ SciSpan<const byte> ptr;
// SCI3 local variables always start dword-aligned
if (_numExports % 2)
- ptr = _buf + 22 + _numExports * 2;
+ ptr = _buf->subspan(22 + _numExports * sizeof(uint16));
else
- ptr = _buf + 24 + _numExports * 2;
+ ptr = _buf->subspan(24 + _numExports * sizeof(uint16));
// SCI3 object structures always start dword-aligned
if (_localsCount % 2)
- ptr += 2 + _localsCount * 2;
+ ptr += 2 + _localsCount * sizeof(uint16);
else
- ptr += _localsCount * 2;
+ ptr += _localsCount * sizeof(uint16);
return ptr;
}
@@ -669,13 +654,13 @@ Object *Script::scriptObjInit(reg_t obj_pos, bool fullObjectInit) {
if (getSciVersion() < SCI_VERSION_1_1 && fullObjectInit)
obj_pos.incOffset(8); // magic offset (SCRIPT_OBJECT_MAGIC_OFFSET)
- if (obj_pos.getOffset() >= _bufSize)
+ if (obj_pos.getOffset() >= _buf->size())
error("Attempt to initialize object beyond end of script");
// Get the object at the specified position and init it. This will
// automatically "allocate" space for it in the _objects map if necessary.
Object *obj = &_objects[obj_pos.getOffset()];
- obj->init(_buf, obj_pos, fullObjectInit);
+ obj->init(*_buf, obj_pos, fullObjectInit);
return obj;
}
@@ -705,14 +690,14 @@ static bool relocateBlock(Common::Array<reg_t> &block, int block_location, Segme
}
int Script::relocateOffsetSci3(uint32 offset) const {
- int relocStart = READ_LE_UINT32(_buf + 8);
- int relocCount = READ_LE_UINT16(_buf + 18);
- const byte *seeker = _buf + relocStart;
+ int relocStart = _buf->getUint32LEAt(8);
+ int relocCount = _buf->getUint16LEAt(18);
+ SciSpan <const byte> seeker = _buf->subspan(relocStart);
for (int i = 0; i < relocCount; ++i) {
- if (READ_SCI11ENDIAN_UINT32(seeker) == offset) {
+ if (seeker.getUint32SEAt(0) == offset) {
// TODO: Find out what UINT16 at (seeker + 8) means
- return READ_SCI11ENDIAN_UINT16(_buf + offset) + READ_SCI11ENDIAN_UINT32(seeker + 4);
+ return _buf->getUint16SEAt(offset) + seeker.getUint32SEAt(4);
}
seeker += 10;
}
@@ -722,39 +707,37 @@ int Script::relocateOffsetSci3(uint32 offset) const {
bool Script::relocateLocal(SegmentId segment, int location) {
if (_localsBlock)
- return relocateBlock(_localsBlock->_locals, _localsOffset, segment, location, _scriptSize);
+ return relocateBlock(_localsBlock->_locals, _localsOffset, segment, location, _script.size());
else
return false;
}
void Script::relocateSci0Sci21(reg_t block) {
- const byte *heap = _buf;
- uint16 heapSize = (uint16)_bufSize;
+ SciSpan<const byte> heap = *_buf;
uint16 heapOffset = 0;
if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- heap = _heapStart;
- heapSize = (uint16)_heapSize;
- heapOffset = _scriptSize;
+ heap = _heap;
+ heapOffset = _script.size();
}
- if (block.getOffset() >= (uint16)heapSize ||
- READ_SCI11ENDIAN_UINT16(heap + block.getOffset()) * 2 + block.getOffset() >= (uint16)heapSize)
+ if (block.getOffset() >= (uint16)heap.size() ||
+ heap.getUint16SEAt(block.getOffset()) * 2 + block.getOffset() >= (uint16)heap.size())
error("Relocation block outside of script");
- int count = READ_SCI11ENDIAN_UINT16(heap + block.getOffset());
+ int count = heap.getUint16SEAt(block.getOffset());
int exportIndex = 0;
int pos = 0;
for (int i = 0; i < count; i++) {
- pos = READ_SCI11ENDIAN_UINT16(heap + block.getOffset() + 2 + (exportIndex * 2)) + heapOffset;
+ pos = heap.getUint16SEAt(block.getOffset() + 2 + (exportIndex * 2)) + heapOffset;
// This occurs in SCI01/SCI1 games where usually one export value is
// zero. It seems that in this situation, we should skip the export and
// move to the next one, though the total count of valid exports remains
// the same
if (!pos) {
exportIndex++;
- pos = READ_SCI11ENDIAN_UINT16(heap + block.getOffset() + 2 + (exportIndex * 2)) + heapOffset;
+ pos = heap.getUint16SEAt(block.getOffset() + 2 + (exportIndex * 2)) + heapOffset;
if (!pos)
error("Script::relocate(): Consecutive zero exports found");
}
@@ -768,7 +751,7 @@ void Script::relocateSci0Sci21(reg_t block) {
// object, relocate it.
const ObjMap::iterator end = _objects.end();
for (ObjMap::iterator it = _objects.begin(); it != end; ++it)
- if (it->_value.relocateSci0Sci21(block.getSegment(), pos, _scriptSize))
+ if (it->_value.relocateSci0Sci21(block.getSegment(), pos, _script.size()))
break;
}
@@ -777,18 +760,18 @@ void Script::relocateSci0Sci21(reg_t block) {
}
void Script::relocateSci3(reg_t block) {
- const byte *relocStart = _buf + READ_SCI11ENDIAN_UINT32(_buf + 8);
+ SciSpan<const byte> relocStart = _buf->subspan(_buf->getUint32SEAt(8));
//int count = _bufSize - READ_SCI11ENDIAN_UINT32(_buf + 8);
ObjMap::iterator it;
for (it = _objects.begin(); it != _objects.end(); ++it) {
- const byte *seeker = relocStart;
- while (seeker < _buf + _bufSize) {
+ SciSpan<const byte> seeker = relocStart;
+ while (seeker.size()) {
// TODO: Find out what UINT16 at (seeker + 8) means
it->_value.relocateSci3(block.getSegment(),
- READ_SCI11ENDIAN_UINT32(seeker),
- READ_SCI11ENDIAN_UINT32(seeker + 4),
- _scriptSize);
+ seeker.getUint32SEAt(0),
+ seeker.getUint32SEAt(4),
+ _script.size());
seeker += 10;
}
}
@@ -816,7 +799,7 @@ void Script::setLockers(int lockers) {
uint32 Script::validateExportFunc(int pubfunct, bool relocSci3) {
bool exportsAreWide = (g_sci->_features->detectLofsType() == SCI_VERSION_1_MIDDLE);
- if (_numExports <= pubfunct) {
+ if (_numExports <= (uint)pubfunct) {
error("validateExportFunc(): pubfunct is invalid");
return 0;
}
@@ -827,10 +810,10 @@ uint32 Script::validateExportFunc(int pubfunct, bool relocSci3) {
uint32 offset;
if (getSciVersion() != SCI_VERSION_3) {
- offset = READ_SCI11ENDIAN_UINT16(_exportTable + pubfunct);
+ offset = _exports.getUint16SEAt(pubfunct);
} else {
if (!relocSci3)
- offset = READ_SCI11ENDIAN_UINT16(_exportTable + pubfunct) + getCodeBlockOffsetSci3();
+ offset = _exports.getUint16SEAt(pubfunct) + getCodeBlockOffsetSci3();
else
offset = relocateOffsetSci3(pubfunct * 2 + 22);
}
@@ -842,11 +825,11 @@ uint32 Script::validateExportFunc(int pubfunct, bool relocSci3) {
// is located at a specific address, thus findBlockSCI0() won't work.
// Fixes bugs #3039785 and #3037595.
if (offset < 10 && getSciVersion() <= SCI_VERSION_1_LATE) {
- const uint16 *secondExportTable = (const uint16 *)findBlockSCI0(SCI_OBJ_EXPORTS, 0);
+ const SciSpan<const uint16> secondExportTable = findBlockSCI0(SCI_OBJ_EXPORTS, 0).subspan<const uint16>(0);
if (secondExportTable) {
- secondExportTable += 3; // skip header plus 2 bytes (secondExportTable is a uint16 pointer)
- offset = READ_SCI11ENDIAN_UINT16(secondExportTable + pubfunct);
+ // 3 skips header plus 2 bytes (secondExportTable is a uint16 pointer)
+ offset = secondExportTable.getUint16SEAt(3 + pubfunct);
}
}
@@ -855,61 +838,58 @@ uint32 Script::validateExportFunc(int pubfunct, bool relocSci3) {
offset = _codeOffset;
}
- if (offset >= _bufSize)
+ if (offset >= _buf->size())
error("Invalid export function pointer");
return offset;
}
-byte *Script::findBlockSCI0(int type, int startBlockIndex) {
- byte *buf = _buf;
+SciSpan<const byte> Script::findBlockSCI0(ScriptObjectTypes type, int startBlockIndex) {
+ SciSpan<const byte> buf = *_buf;
bool oldScriptHeader = (getSciVersion() == SCI_VERSION_0_EARLY);
int blockIndex = 0;
if (oldScriptHeader)
buf += 2;
- do {
- int blockType = READ_LE_UINT16(buf);
+ for (;;) {
+ const int blockType = buf.getUint16LEAt(0);
if (blockType == 0)
break;
- if (blockType == type && blockIndex > startBlockIndex)
- return buf;
- int blockSize = READ_LE_UINT16(buf + 2);
+ // the size in the block header includes the size of the header itself
+ const int blockSize = buf.getUint16LEAt(2);
assert(blockSize > 0);
+
+ if (blockType == type && blockIndex > startBlockIndex) {
+ return buf.subspan(0, blockSize, Common::String::format("%s, %s block", _buf->name().c_str(), sciObjectTypeNames[type]));
+ }
+
buf += blockSize;
blockIndex++;
- } while (1);
+ }
- return NULL;
+ return SciSpan<const byte>();
}
// memory operations
-void Script::mcpyInOut(int dst, const void *src, size_t n) {
- if (_buf) {
- assert(dst + n <= _bufSize);
- memcpy(_buf + dst, src, n);
- }
-}
-
bool Script::isValidOffset(uint16 offset) const {
- return offset < _bufSize;
+ return offset < _buf->size();
}
SegmentRef Script::dereference(reg_t pointer) {
- if (pointer.getOffset() > _bufSize) {
- error("Script::dereference(): Attempt to dereference invalid pointer %04x:%04x into script segment (script size=%d)",
- PRINT_REG(pointer), (uint)_bufSize);
+ if (pointer.getOffset() > _buf->size()) {
+ error("Script::dereference(): Attempt to dereference invalid pointer %04x:%04x into script segment (script size=%lu)",
+ PRINT_REG(pointer), _buf->size());
return SegmentRef();
}
SegmentRef ret;
ret.isRaw = true;
- ret.maxSize = _bufSize - pointer.getOffset();
- ret.raw = _buf + pointer.getOffset();
+ ret.maxSize = _buf->size() - pointer.getOffset();
+ ret.raw = const_cast<byte *>(_buf->getUnsafeDataAt(pointer.getOffset(), ret.maxSize));
return ret;
}
@@ -938,10 +918,10 @@ void Script::initializeLocals(SegManager *segMan) {
LocalVariables *locals = allocLocalsSegment(segMan);
if (locals) {
if (getSciVersion() > SCI_VERSION_0_EARLY) {
- const byte *base = (const byte *)(_buf + getLocalsOffset());
+ const SciSpan<const byte> base = _buf->subspan(getLocalsOffset());
for (uint16 i = 0; i < getLocalsCount(); i++)
- locals->_locals[i] = make_reg(0, READ_SCI11ENDIAN_UINT16(base + i * 2));
+ locals->_locals[i] = make_reg(0, base.getUint16SEAt(i * 2));
} else {
// In SCI0 early, locals are set at run time, thus zero them all here
for (uint16 i = 0; i < getLocalsCount(); i++)
@@ -955,14 +935,19 @@ void Script::syncLocalsBlock(SegManager *segMan) {
}
void Script::initializeClasses(SegManager *segMan) {
- const byte *seeker = 0;
+ SciSpan<const byte> seeker;
uint16 mult = 0;
if (getSciVersion() <= SCI_VERSION_1_LATE) {
- seeker = findBlockSCI0(SCI_OBJ_CLASS);
+ seeker = _script;
mult = 1;
+
+ // SCI0 early has an extra two bytes of header
+ if (getSciVersion() == SCI_VERSION_0_EARLY) {
+ seeker += 2;
+ }
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- seeker = _heapStart + 4 + READ_SCI11ENDIAN_UINT16(_heapStart + 2) * 2;
+ seeker = _heap.subspan(4 + _heap.getUint16SEAt(2) * 2);
mult = 2;
} else if (getSciVersion() == SCI_VERSION_3) {
seeker = getSci3ObjectsPointer();
@@ -977,10 +962,10 @@ void Script::initializeClasses(SegManager *segMan) {
uint32 classpos;
int16 species = 0;
- while (true) {
+ for (;;) {
// In SCI0-SCI1, this is the segment type. In SCI11, it's a marker (0x1234)
- marker = READ_SCI11ENDIAN_UINT16(seeker);
- classpos = seeker - _buf;
+ marker = seeker.getUint16SEAt(0);
+ classpos = seeker - *_buf;
if (getSciVersion() <= SCI_VERSION_1_LATE && !marker)
break;
@@ -991,14 +976,14 @@ void Script::initializeClasses(SegManager *segMan) {
if (getSciVersion() <= SCI_VERSION_1_LATE) {
isClass = (marker == SCI_OBJ_CLASS);
if (isClass)
- species = READ_SCI11ENDIAN_UINT16(seeker + 12);
+ species = seeker.getUint16SEAt(12);
classpos += 12;
} else if (getSciVersion() >= SCI_VERSION_1_1 && getSciVersion() <= SCI_VERSION_2_1_LATE) {
- isClass = (READ_SCI11ENDIAN_UINT16(seeker + 14) & kInfoFlagClass); // -info- selector
- species = READ_SCI11ENDIAN_UINT16(seeker + 10);
+ isClass = (seeker.getUint16SEAt(14) & kInfoFlagClass); // -info- selector
+ species = seeker.getUint16SEAt(10);
} else if (getSciVersion() == SCI_VERSION_3) {
- isClass = (READ_SCI11ENDIAN_UINT16(seeker + 10) & kInfoFlagClass);
- species = READ_SCI11ENDIAN_UINT16(seeker + 4);
+ isClass = (seeker.getUint16SEAt(10) & kInfoFlagClass);
+ species = seeker.getUint16SEAt(4);
}
if (isClass) {
@@ -1022,7 +1007,7 @@ void Script::initializeClasses(SegManager *segMan) {
segMan->setClassOffset(species, make_reg(segmentId, classpos));
}
- seeker += READ_SCI11ENDIAN_UINT16(seeker + 2) * mult;
+ seeker += seeker.getUint16SEAt(2) * mult;
}
}
@@ -1032,10 +1017,10 @@ void Script::initializeObjectsSci0(SegManager *segMan, SegmentId segmentId) {
// We need to make two passes, as the objects in the script might be in the
// wrong order (e.g. in the demo of Iceman) - refer to bug #3034713
for (int pass = 1; pass <= 2; pass++) {
- const byte *seeker = _buf + (oldScriptHeader ? 2 : 0);
+ SciSpan<const byte> seeker = _buf->subspan(oldScriptHeader ? 2 : 0);
do {
- uint16 objType = READ_SCI11ENDIAN_UINT16(seeker);
+ uint16 objType = seeker.getUint16SEAt(0);
if (!objType)
break;
@@ -1043,7 +1028,7 @@ void Script::initializeObjectsSci0(SegManager *segMan, SegmentId segmentId) {
case SCI_OBJ_OBJECT:
case SCI_OBJ_CLASS:
{
- reg_t addr = make_reg(segmentId, seeker - _buf + 4);
+ reg_t addr = make_reg(segmentId, seeker - *_buf + 4);
Object *obj = scriptObjInit(addr);
obj->initSpecies(segMan, addr);
@@ -1069,20 +1054,20 @@ void Script::initializeObjectsSci0(SegManager *segMan, SegmentId segmentId) {
break;
}
- seeker += READ_SCI11ENDIAN_UINT16(seeker + 2);
- } while ((uint32)(seeker - _buf) < getScriptSize() - 2);
+ seeker += seeker.getUint16SEAt(2);
+ } while ((uint32)(seeker - *_buf) < getScriptSize() - 2);
}
- byte *relocationBlock = findBlockSCI0(SCI_OBJ_POINTERS);
+ const SciSpan<const byte> relocationBlock = findBlockSCI0(SCI_OBJ_POINTERS);
if (relocationBlock)
- relocateSci0Sci21(make_reg(segmentId, relocationBlock - getBuf() + 4));
+ relocateSci0Sci21(make_reg(segmentId, relocationBlock - *_buf + 4));
}
void Script::initializeObjectsSci11(SegManager *segMan, SegmentId segmentId) {
- const byte *seeker = _heapStart + 4 + READ_SCI11ENDIAN_UINT16(_heapStart + 2) * 2;
+ SciSpan<const byte> seeker = _heap.subspan(4 + _heap.getUint16SEAt(2) * 2);
- while (READ_SCI11ENDIAN_UINT16(seeker) == SCRIPT_OBJECT_MAGIC_NUMBER) {
- reg_t reg = make_reg(segmentId, seeker - _buf);
+ while (seeker.getUint16SEAt(0) == SCRIPT_OBJECT_MAGIC_NUMBER) {
+ reg_t reg = make_reg(segmentId, seeker - *_buf);
Object *obj = scriptObjInit(reg);
// Copy base from species class, as we need its selector IDs
@@ -1113,26 +1098,26 @@ void Script::initializeObjectsSci11(SegManager *segMan, SegmentId segmentId) {
// to be sufficient.
obj->setClassScriptSelector(make_reg(0, _nr));
- seeker += READ_SCI11ENDIAN_UINT16(seeker + 2) * 2;
+ seeker += seeker.getUint16SEAt(2) * 2;
}
- relocateSci0Sci21(make_reg(segmentId, READ_SCI11ENDIAN_UINT16(_heapStart)));
+ relocateSci0Sci21(make_reg(segmentId, _heap.getUint16SEAt(0)));
}
void Script::initializeObjectsSci3(SegManager *segMan, SegmentId segmentId) {
- const byte *seeker = getSci3ObjectsPointer();
+ SciSpan<const byte> seeker = getSci3ObjectsPointer();
- while (READ_SCI11ENDIAN_UINT16(seeker) == SCRIPT_OBJECT_MAGIC_NUMBER) {
+ while (seeker.getUint16SEAt(0) == SCRIPT_OBJECT_MAGIC_NUMBER) {
// We call setSegment and setOffset directly here, instead of using
// make_reg, as in large scripts, seeker - _buf can be larger than
// a 16-bit integer
reg_t reg;
reg.setSegment(segmentId);
- reg.setOffset(seeker - _buf);
+ reg.setOffset(seeker - *_buf);
Object *obj = scriptObjInit(reg);
obj->setSuperClassSelector(segMan->getClassAddress(obj->getSuperClassSelector().getOffset(), SCRIPT_GET_LOCK, 0));
- seeker += READ_SCI11ENDIAN_UINT16(seeker + 2);
+ seeker += seeker.getUint16SEAt(2);
}
relocateSci3(make_reg(segmentId, 0));
@@ -1170,7 +1155,7 @@ Common::Array<reg_t> Script::listAllDeallocatable(SegmentId segId) const {
Common::Array<reg_t> Script::listAllOutgoingReferences(reg_t addr) const {
Common::Array<reg_t> tmp;
- if (addr.getOffset() <= _bufSize && addr.getOffset() >= (uint)-SCRIPT_OBJECT_MAGIC_OFFSET && offsetIsObject(addr.getOffset())) {
+ if (addr.getOffset() <= _buf->size() && addr.getOffset() >= (uint)-SCRIPT_OBJECT_MAGIC_OFFSET && offsetIsObject(addr.getOffset())) {
const Object *obj = getObject(addr.getOffset());
if (obj) {
// Note all local variables, if we have a local variable environment
@@ -1207,7 +1192,7 @@ Common::Array<reg_t> Script::listObjectReferences() const {
}
bool Script::offsetIsObject(uint16 offset) const {
- return (READ_SCI11ENDIAN_UINT16((const byte *)_buf + offset + SCRIPT_OBJECT_MAGIC_OFFSET) == SCRIPT_OBJECT_MAGIC_NUMBER);
+ return _buf->getUint16SEAt(offset + SCRIPT_OBJECT_MAGIC_OFFSET) == SCRIPT_OBJECT_MAGIC_NUMBER;
}
} // End of namespace Sci
diff --git a/engines/sci/engine/script.h b/engines/sci/engine/script.h
index 677b367051..52b58eec2e 100644
--- a/engines/sci/engine/script.h
+++ b/engines/sci/engine/script.h
@@ -24,6 +24,7 @@
#define SCI_ENGINE_SCRIPT_H
#include "common/str.h"
+#include "sci/util.h"
#include "sci/engine/segment.h"
#include "sci/engine/script_patches.h"
@@ -67,19 +68,16 @@ typedef Common::Array<offsetLookupArrayEntry> offsetLookupArrayType;
class Script : public SegmentObj {
private:
int _nr; /**< Script number */
- byte *_buf; /**< Static data buffer, or NULL if not used */
- byte *_heapStart; /**< Start of heap if SCI1.1, NULL otherwise */
+ Common::SpanOwner<SciSpan<const byte> > _buf; /**< Static data buffer, or NULL if not used */
+ SciSpan<const byte> _script; /**< Script size includes alignment byte */
+ SciSpan<const byte> _heap; /**< Start of heap if SCI1.1, NULL otherwise */
int _lockers; /**< Number of classes and objects that require this script */
- size_t _scriptSize;
- size_t _heapSize;
- size_t _bufSize;
- const uint16 *_exportTable; /**< Abs. offset of the export table or 0 if not present */
- uint16 _numExports; /**< Number of entries in the exports table */
-
- const byte *_synonyms; /**< Synonyms block or 0 if not present */
- uint16 _numSynonyms; /**< Number of entries in the synonyms block */
+ SciSpan<const uint16> _exports; /**< Exports block or 0 if not present */
+ uint16 _numExports; /**< Number of export entries */
+ SciSpan<const byte> _synonyms; /**< Synonyms block or 0 if not present */
+ uint16 _numSynonyms; /**< Number of synonym entries */
int _codeOffset; /**< The absolute offset of the VM code block */
@@ -104,10 +102,11 @@ public:
int getLocalsOffset() const { return _localsOffset; }
uint16 getLocalsCount() const { return _localsCount; }
- uint32 getScriptSize() const { return _scriptSize; }
- uint32 getHeapSize() const { return _heapSize; }
- uint32 getBufSize() const { return _bufSize; }
- const byte *getBuf(uint offset = 0) const { return _buf + offset; }
+ uint32 getScriptSize() const { return _script.size(); }
+ uint32 getHeapSize() const { return _heap.size(); }
+ uint32 getBufSize() const { return _buf->size(); }
+
+ const byte *getBuf(uint offset = 0) const { return _buf->getUnsafeDataAt(offset); }
int getScriptNumber() const { return _nr; }
SegmentId getLocalsSegment() const { return _localsSegment; }
@@ -192,10 +191,10 @@ public:
void setLockers(int lockers);
/**
- * Retrieves a pointer to the exports of this script
- * @return pointer to the exports.
+ * Retrieves the offset of the export table in the script
+ * @return the exports offset.
*/
- const uint16 *getExportTable() const { return _exportTable; }
+ uint getExportsOffset() const { return _exports.sourceByteOffset(); }
/**
* Retrieves the number of exports of script.
@@ -207,7 +206,7 @@ public:
* Retrieves a pointer to the synonyms associated with this script
* @return pointer to the synonyms, in non-parsed format.
*/
- const byte *getSynonyms() const { return _synonyms; }
+ const SciSpan<const byte> &getSynonyms() const { return _synonyms; }
/**
* Retrieves the number of synonyms associated with this script.
@@ -244,18 +243,10 @@ public:
}
/**
- * Copies a byte string into a script's heap representation.
- * @param dst script-relative offset of the destination area
- * @param src pointer to the data source location
- * @param n number of bytes to copy
- */
- void mcpyInOut(int dst, const void *src, size_t n);
-
- /**
* Finds the pointer where a block of a specific type starts from,
* in SCI0 - SCI1 games
*/
- byte *findBlockSCI0(int type, int startBlockIndex = -1);
+ SciSpan<const byte> findBlockSCI0(ScriptObjectTypes type, int startBlockIndex = -1);
/**
* Syncs the string heap of a script. Used when saving/loading.
@@ -271,7 +262,7 @@ public:
/**
* Gets an offset to the beginning of the code block in a SCI3 script
*/
- int getCodeBlockOffsetSci3() { return READ_SCI11ENDIAN_UINT32(_buf); }
+ int getCodeBlockOffsetSci3() { return _buf->getInt32SEAt(0); }
/**
* Get the offset array
@@ -303,7 +294,7 @@ private:
/**
* Gets a pointer to the beginning of the objects in a SCI3 script
*/
- const byte *getSci3ObjectsPointer();
+ SciSpan<const byte> getSci3ObjectsPointer();
/**
* Initializes the script's objects (SCI0)
diff --git a/engines/sci/engine/script_patches.cpp b/engines/sci/engine/script_patches.cpp
index cf3a981347..d84d2ab780 100644
--- a/engines/sci/engine/script_patches.cpp
+++ b/engines/sci/engine/script_patches.cpp
@@ -4975,7 +4975,7 @@ ScriptPatcher::~ScriptPatcher() {
}
// will actually patch previously found signature area
-void ScriptPatcher::applyPatch(const SciScriptPatcherEntry *patchEntry, byte *scriptData, const uint32 scriptSize, int32 signatureOffset) {
+void ScriptPatcher::applyPatch(const SciScriptPatcherEntry *patchEntry, SciSpan<byte> scriptData, int32 signatureOffset) {
const uint16 *patchData = patchEntry->patchData;
byte orgData[PATCH_VALUELIMIT];
int32 offset = signatureOffset;
@@ -4983,10 +4983,10 @@ void ScriptPatcher::applyPatch(const SciScriptPatcherEntry *patchEntry, byte *sc
uint16 patchSelector = 0;
// Copy over original bytes from script
- uint32 orgDataSize = scriptSize - offset;
+ uint32 orgDataSize = scriptData.size() - offset;
if (orgDataSize > PATCH_VALUELIMIT)
orgDataSize = PATCH_VALUELIMIT;
- memcpy(&orgData, &scriptData[offset], orgDataSize);
+ scriptData.subspan(offset, orgDataSize).unsafeCopyDataTo(orgData);
while (patchWord != PATCH_END) {
uint16 patchCommand = patchWord & PATCH_COMMANDMASK;
@@ -5082,7 +5082,7 @@ void ScriptPatcher::applyPatch(const SciScriptPatcherEntry *patchEntry, byte *sc
}
}
-bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureData, const char *signatureDescription, const byte *scriptData, const uint32 scriptSize) {
+bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureData, const char *signatureDescription, const SciSpan<const byte> &scriptData) {
uint16 sigSelector = 0;
uint16 sigWord = *signatureData;
@@ -5097,7 +5097,7 @@ bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureDa
}
case SIG_CODE_UINT16:
case SIG_CODE_SELECTOR16: {
- if ((byteOffset + 1) < scriptSize) {
+ if (byteOffset + 1 < scriptData.size()) {
byte byte1;
byte byte2;
@@ -5134,7 +5134,7 @@ bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureDa
break;
}
case SIG_CODE_SELECTOR8: {
- if (byteOffset < scriptSize) {
+ if (byteOffset < scriptData.size()) {
sigSelector = _selectorIdTable[sigValue];
if (sigSelector & 0xFF00)
error("Script-Patcher: 8 bit selector required, game uses 16 bit selector\nFaulty signature: '%s'", signatureDescription);
@@ -5147,7 +5147,7 @@ bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureDa
break;
}
case SIG_CODE_BYTE:
- if (byteOffset < scriptSize) {
+ if (byteOffset < scriptData.size()) {
if (scriptData[byteOffset] != sigWord)
sigWord = SIG_MISMATCH;
byteOffset++;
@@ -5169,20 +5169,20 @@ bool ScriptPatcher::verifySignature(uint32 byteOffset, const uint16 *signatureDa
}
// will return -1 if no match was found, otherwise an offset to the start of the signature match
-int32 ScriptPatcher::findSignature(uint32 magicDWord, int magicOffset, const uint16 *signatureData, const char *patchDescription, const byte *scriptData, const uint32 scriptSize) {
- if (scriptSize < 4) // we need to find a DWORD, so less than 4 bytes is not okay
+int32 ScriptPatcher::findSignature(uint32 magicDWord, int magicOffset, const uint16 *signatureData, const char *patchDescription, const SciSpan<const byte> &scriptData) {
+ if (scriptData.size() < 4) // we need to find a DWORD, so less than 4 bytes is not okay
return -1;
// magicDWord is in platform-specific BE/LE form, so that the later match will work, this was done for performance
- const uint32 searchLimit = scriptSize - 3;
+ const uint32 searchLimit = scriptData.size() - 3;
uint32 DWordOffset = 0;
// first search for the magic DWORD
while (DWordOffset < searchLimit) {
- if (magicDWord == READ_UINT32(scriptData + DWordOffset)) {
+ if (magicDWord == scriptData.getUint32At(DWordOffset)) {
// magic DWORD found, check if actual signature matches
uint32 offset = DWordOffset + magicOffset;
- if (verifySignature(offset, signatureData, patchDescription, scriptData, scriptSize))
+ if (verifySignature(offset, signatureData, patchDescription, scriptData))
return offset;
}
DWordOffset++;
@@ -5191,8 +5191,8 @@ int32 ScriptPatcher::findSignature(uint32 magicDWord, int magicOffset, const uin
return -1;
}
-int32 ScriptPatcher::findSignature(const SciScriptPatcherEntry *patchEntry, const SciScriptPatcherRuntimeEntry *runtimeEntry, const byte *scriptData, const uint32 scriptSize) {
- return findSignature(runtimeEntry->magicDWord, runtimeEntry->magicOffset, patchEntry->signatureData, patchEntry->description, scriptData, scriptSize);
+int32 ScriptPatcher::findSignature(const SciScriptPatcherEntry *patchEntry, const SciScriptPatcherRuntimeEntry *runtimeEntry, const SciSpan<const byte> &scriptData) {
+ return findSignature(runtimeEntry->magicDWord, runtimeEntry->magicOffset, patchEntry->signatureData, patchEntry->description, scriptData);
}
// Attention: Magic DWord is returned using platform specific byte order. This is done on purpose for performance.
@@ -5380,7 +5380,7 @@ void ScriptPatcher::enablePatch(const SciScriptPatcherEntry *patchTable, const c
error("Script-Patcher: no patch found to enable");
}
-void ScriptPatcher::processScript(uint16 scriptNr, byte *scriptData, const uint32 scriptSize) {
+void ScriptPatcher::processScript(uint16 scriptNr, SciSpan<byte> scriptData) {
const SciScriptPatcherEntry *signatureTable = NULL;
const SciScriptPatcherEntry *curEntry = NULL;
SciScriptPatcherRuntimeEntry *curRuntimeEntry = NULL;
@@ -5552,11 +5552,11 @@ void ScriptPatcher::processScript(uint16 scriptNr, byte *scriptData, const uint3
int32 foundOffset = 0;
int16 applyCount = curEntry->applyCount;
do {
- foundOffset = findSignature(curEntry, curRuntimeEntry, scriptData, scriptSize);
+ foundOffset = findSignature(curEntry, curRuntimeEntry, scriptData);
if (foundOffset != -1) {
// found, so apply the patch
debugC(kDebugLevelScriptPatcher, "Script-Patcher: '%s' on script %d offset %d", curEntry->description, scriptNr, foundOffset);
- applyPatch(curEntry, scriptData, scriptSize, foundOffset);
+ applyPatch(curEntry, scriptData, foundOffset);
}
applyCount--;
} while ((foundOffset != -1) && (applyCount));
diff --git a/engines/sci/engine/script_patches.h b/engines/sci/engine/script_patches.h
index b5797be847..69f9794764 100644
--- a/engines/sci/engine/script_patches.h
+++ b/engines/sci/engine/script_patches.h
@@ -97,14 +97,14 @@ public:
void calculateMagicDWordAndVerify(const char *signatureDescription, const uint16 *signatureData, bool magicDWordIncluded, uint32 &calculatedMagicDWord, int &calculatedMagicDWordOffset);
// Called when a script is loaded to check for signature matches and apply patches in such cases
- void processScript(uint16 scriptNr, byte *scriptData, const uint32 scriptSize);
+ void processScript(uint16 scriptNr, SciSpan<byte> scriptData);
// Verifies, if a given signature matches the given script data (pointed to by additional byte offset)
- bool verifySignature(uint32 byteOffset, const uint16 *signatureData, const char *signatureDescription, const byte *scriptData, const uint32 scriptSize);
+ bool verifySignature(uint32 byteOffset, const uint16 *signatureData, const char *signatureDescription, const SciSpan<const byte> &scriptData);
// searches for a given signature inside script data
// returns -1 in case it was not found or an offset to the matching data
- int32 findSignature(uint32 magicDWord, int magicOffset, const uint16 *signatureData, const char *patchDescription, const byte *scriptData, const uint32 scriptSize);
+ int32 findSignature(uint32 magicDWord, int magicOffset, const uint16 *signatureData, const char *patchDescription, const SciSpan<const byte> &scriptData);
private:
// Initializes a patch table and creates run time information for it (for enabling/disabling), also calculates magic DWORD)
@@ -115,10 +115,10 @@ private:
// Searches for a given signature entry inside script data
// returns -1 in case it was not found or an offset to the matching data
- int32 findSignature(const SciScriptPatcherEntry *patchEntry, const SciScriptPatcherRuntimeEntry *runtimeEntry, const byte *scriptData, const uint32 scriptSize);
+ int32 findSignature(const SciScriptPatcherEntry *patchEntry, const SciScriptPatcherRuntimeEntry *runtimeEntry, const SciSpan<const byte> &scriptData);
// Applies a patch to a given script + offset (overwrites parts)
- void applyPatch(const SciScriptPatcherEntry *patchEntry, byte *scriptData, const uint32 scriptSize, int32 signatureOffset);
+ void applyPatch(const SciScriptPatcherEntry *patchEntry, SciSpan<byte> scriptData, int32 signatureOffset);
Selector *_selectorIdTable;
SciScriptPatcherRuntimeEntry *_runtimeTable;
diff --git a/engines/sci/engine/scriptdebug.cpp b/engines/sci/engine/scriptdebug.cpp
index 6002cbd8e4..d15cf83b71 100644
--- a/engines/sci/engine/scriptdebug.cpp
+++ b/engines/sci/engine/scriptdebug.cpp
@@ -71,8 +71,6 @@ const char *opcodeNames[] = {
reg_t disassemble(EngineState *s, reg32_t pos, reg_t objAddr, bool printBWTag, bool printBytecode) {
SegmentObj *mobj = s->_segMan->getSegment(pos.getSegment(), SEG_TYPE_SCRIPT);
Script *script_entity = NULL;
- const byte *scr;
- uint32 scr_size;
reg_t retval = make_reg(pos.getSegment(), pos.getOffset() + 1);
uint16 param_value = 0xffff; // Suppress GCC warning by setting default value, chose value as invalid to getKernelName etc.
uint i = 0;
@@ -84,14 +82,15 @@ reg_t disassemble(EngineState *s, reg32_t pos, reg_t objAddr, bool printBWTag, b
} else
script_entity = (Script *)mobj;
- scr = script_entity->getBuf();
- scr_size = script_entity->getBufSize();
+ uint scr_size = script_entity->getBufSize();
if (pos.getOffset() >= scr_size) {
warning("Trying to disassemble beyond end of script");
return NULL_REG;
}
+ const byte *scr = script_entity->getBuf();
+
int16 opparams[4];
byte opsize;
uint bytecount = readPMachineInstruction(scr + pos.getOffset(), opsize, opparams);
@@ -348,12 +347,13 @@ bool isJumpOpcode(EngineState *s, reg_t pos, reg_t& jumpTarget) {
return false;
Script *script_entity = (Script *)mobj;
- const byte *scr = script_entity->getBuf();
uint scr_size = script_entity->getScriptSize();
if (pos.getOffset() >= scr_size)
return false;
+ const byte *scr = script_entity->getBuf();
+
int16 opparams[4];
byte opsize;
int bytecount = readPMachineInstruction(scr + pos.getOffset(), opsize, opparams);
@@ -449,107 +449,114 @@ void SciEngine::scriptDebug() {
_console->attach();
}
-void Kernel::dumpScriptObject(char *data, int seeker, int objsize) {
- int selectors, overloads, selectorsize;
- int species = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 8 + seeker);
- int superclass = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 10 + seeker);
- int namepos = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 14 + seeker);
+void Kernel::dumpScriptObject(const SciSpan<const byte> &script, SciSpan <const byte> object) {
+ const int16 species = object.getInt16SEAt(8);
+ const int16 superclass = object.getInt16SEAt(10);
+ const int16 namepos = object.getInt16SEAt(14);
int i = 0;
debugN("Object\n");
- Common::hexdump((unsigned char *) data + seeker, objsize - 4, 16, seeker);
//-4 because the size includes the two-word header
+ Common::hexdump(object.getUnsafeDataAt(0, object.size() - 4), object.size() - 4, 16, object.sourceByteOffset());
- debugN("Name: %s\n", namepos ? ((char *)(data + namepos)) : "<unknown>");
+ debugN("Name: %s\n", namepos ? script.getStringAt(namepos).c_str() : "<unknown>");
debugN("Superclass: %x\n", superclass);
debugN("Species: %x\n", species);
- debugN("-info-:%x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 12 + seeker) & 0xffff);
+ debugN("-info-: %x\n", object.getInt16SEAt(12) & 0xFFFF);
+
+ debugN("Function area offset: %x\n", object.getInt16SEAt(4));
- debugN("Function area offset: %x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + seeker + 4));
- debugN("Selectors [%x]:\n", selectors = (selectorsize = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + seeker + 6)));
+ int16 selectors = object.getInt16SEAt(6);
+ debugN("Selectors [%x]:\n", selectors);
- seeker += 8;
+ object += 8;
while (selectors--) {
- debugN(" [#%03x] = 0x%x\n", i++, (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker) & 0xffff);
- seeker += 2;
+ debugN(" [#%03x] = 0x%x\n", i++, object.getInt16SEAt(0) & 0xFFFF);
+ object += 2;
}
- debugN("Overridden functions: %x\n", selectors = overloads = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker));
+ selectors = object.getInt16SEAt(0);
+ int16 overloads = selectors;
+ debugN("Overridden functions: %x\n", overloads);
- seeker += 2;
+ object += 2;
- if (overloads < 100)
+ if (overloads < 100) {
while (overloads--) {
- int selector = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + (seeker));
+ const int16 selector = object.getInt16SEAt(0);
- debugN(" [%03x] %s: @", selector & 0xffff, (selector >= 0 && selector < (int)_selectorNames.size()) ? _selectorNames[selector].c_str() : "<?>");
- debugN("%04x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker + selectors*2 + 2) & 0xffff);
+ debugN(" [%03x] %s: @", selector & 0xFFFF, (selector >= 0 && selector < (int)_selectorNames.size()) ? _selectorNames[selector].c_str() : "<?>");
+ debugN("%04x\n", object.getInt16SEAt(selectors * 2 + 2) & 0xFFFF);
- seeker += 2;
+ object += 2;
}
+ }
}
-void Kernel::dumpScriptClass(char *data, int seeker, int objsize) {
- int selectors, overloads, selectorsize;
- int species = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 8 + seeker);
- int superclass = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 10 + seeker);
- int namepos = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + 14 + seeker);
+void Kernel::dumpScriptClass(const SciSpan<const byte> &script, SciSpan<const byte> clazz) {
+ const int16 species = clazz.getInt16SEAt(8);
+ const int16 superclass = clazz.getInt16SEAt(10);
+ const int16 namepos = clazz.getInt16SEAt(14);
debugN("Class\n");
- Common::hexdump((unsigned char *) data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(clazz.getUnsafeDataAt(0, clazz.size() - 4), clazz.size() - 4, 16, clazz.sourceByteOffset());
- debugN("Name: %s\n", namepos ? ((char *)data + namepos) : "<unknown>");
+ debugN("Name: %s\n", namepos ? script.getStringAt(namepos).c_str() : "<unknown>");
debugN("Superclass: %x\n", superclass);
debugN("Species: %x\n", species);
- debugN("-info-:%x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + 12 + seeker) & 0xffff);
+ debugN("-info-: %x\n", clazz.getInt16SEAt(12) & 0xFFFF);
+
+ debugN("Function area offset: %x\n", clazz.getInt16SEAt(4));
- debugN("Function area offset: %x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker + 4));
- debugN("Selectors [%x]:\n", selectors = (selectorsize = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker + 6)));
+ int16 selectors = clazz.getInt16SEAt(6);
+ int16 selectorsize = selectors;
+ debugN("Selectors [%x]:\n", selectors);
- seeker += 8;
+ clazz += 8;
selectorsize <<= 1;
while (selectors--) {
- int selector = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *) data + (seeker) + selectorsize);
+ const int16 selector = clazz.getInt16SEAt(selectorsize);
- debugN(" [%03x] %s = 0x%x\n", 0xffff & selector, (selector >= 0 && selector < (int)_selectorNames.size()) ? _selectorNames[selector].c_str() : "<?>",
- (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker) & 0xffff);
+ debugN(" [%03x] %s = 0x%x\n", selector & 0xFFFF, (selector >= 0 && selector < (int)_selectorNames.size()) ? _selectorNames[selector].c_str() : "<?>", clazz.getInt16SEAt(0) & 0xFFFF);
- seeker += 2;
+ clazz += 2;
}
- seeker += selectorsize;
+ clazz += selectorsize;
- debugN("Overloaded functions: %x\n", selectors = overloads = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker));
+ int16 overloads = clazz.getInt16SEAt(0);
+ selectors = overloads;
+ debugN("Overloaded functions: %x\n", overloads);
- seeker += 2;
+ clazz += 2;
while (overloads--) {
- int selector = (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + (seeker));
+ int16 selector = clazz.getInt16SEAt(0);
debugN("selector=%d; selectorNames.size() =%d\n", selector, _selectorNames.size());
- debugN(" [%03x] %s: @", selector & 0xffff, (selector >= 0 && selector < (int)_selectorNames.size()) ?
+ debugN(" [%03x] %s: @", selector & 0xFFFF, (selector >= 0 && selector < (int)_selectorNames.size()) ?
_selectorNames[selector].c_str() : "<?>");
- debugN("%04x\n", (int16)READ_SCI11ENDIAN_UINT16((unsigned char *)data + seeker + selectors * 2 + 2) & 0xffff);
+ debugN("%04x\n", clazz.getInt16SEAt(selectors * 2 + 2) & 0xFFFF);
- seeker += 2;
+ clazz += 2;
}
}
void Kernel::dissectScript(int scriptNumber, Vocabulary *vocab) {
int objectctr[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32 _seeker = 0;
- Resource *script = _resMan->findResource(ResourceId(kResourceTypeScript, scriptNumber), 0);
+ Resource *script = _resMan->findResource(ResourceId(kResourceTypeScript, scriptNumber), false);
if (!script) {
warning("dissectScript(): Script not found!\n");
return;
}
- while (_seeker < script->size) {
- int objType = (int16)READ_SCI11ENDIAN_UINT16(script->data + _seeker);
+ while (_seeker < script->size()) {
+ int objType = script->getInt16SEAt(_seeker);
int objsize;
uint32 seeker = _seeker + 4;
@@ -562,7 +569,7 @@ void Kernel::dissectScript(int scriptNumber, Vocabulary *vocab) {
debugN("\n");
- objsize = (int16)READ_SCI11ENDIAN_UINT16(script->data + _seeker + 2);
+ objsize = script->getInt16SEAt(_seeker + 2);
debugN("Obj type #%x, size 0x%x: ", objType, objsize);
@@ -573,34 +580,35 @@ void Kernel::dissectScript(int scriptNumber, Vocabulary *vocab) {
switch (objType) {
case SCI_OBJ_OBJECT:
- dumpScriptObject((char *)script->data, seeker, objsize);
+ dumpScriptObject(*script, script->subspan(seeker, objsize));
break;
case SCI_OBJ_CODE:
debugN("Code\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
case SCI_OBJ_SYNONYMS:
debugN("Synonyms\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
case SCI_OBJ_SAID:
debugN("Said\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
debugN("%04x: ", seeker);
- vocab->debugDecipherSaidBlock(script->data + seeker);
+ vocab->debugDecipherSaidBlock(script->subspan(seeker));
debugN("\n");
break;
case SCI_OBJ_STRINGS:
debugN("Strings\n");
- while (script->data [seeker]) {
- debugN("%04x: %s", seeker, script->data + seeker);
- seeker += Common::strnlen((char *)script->data + seeker, script->size - seeker) + 1;
- if (seeker > script->size) {
+ while (script->getUint8At(seeker)) {
+ const Common::String string = script->getStringAt(seeker);
+ debugN("%04x: %s", seeker, string.c_str());
+ seeker += string.size() + 1;
+ if (seeker > script->size()) {
debugN("[TRUNCATED]");
}
debugN("\n");
@@ -609,27 +617,27 @@ void Kernel::dissectScript(int scriptNumber, Vocabulary *vocab) {
break;
case SCI_OBJ_CLASS:
- dumpScriptClass((char *)script->data, seeker, objsize);
+ dumpScriptClass(*script, script->subspan(seeker, objsize));
break;
case SCI_OBJ_EXPORTS:
debugN("Exports\n");
- Common::hexdump((unsigned char *)script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
case SCI_OBJ_POINTERS:
debugN("Pointers\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
case 9:
debugN("<unknown>\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
case SCI_OBJ_LOCALVARS:
debugN("Local vars\n");
- Common::hexdump(script->data + seeker, objsize - 4, 16, seeker);
+ Common::hexdump(script->getUnsafeDataAt(seeker, objsize - 4), objsize - 4, 16, seeker);
break;
default:
@@ -821,7 +829,7 @@ void logKernelCall(const KernelFunction *kernelCall, const KernelSubFunction *ke
SegmentRef saidSpec = s->_segMan->dereference(argv[parmNr]);
if (saidSpec.isRaw) {
debugN(" ('");
- g_sci->getVocabulary()->debugDecipherSaidBlock(saidSpec.raw);
+ g_sci->getVocabulary()->debugDecipherSaidBlock(SciSpan<const byte>(saidSpec.raw, saidSpec.maxSize, Common::String::format("said %04x:%04x", PRINT_REG(argv[parmNr]))));
debugN("')");
} else {
debugN(" (non-raw said-spec)");
diff --git a/engines/sci/engine/seg_manager.cpp b/engines/sci/engine/seg_manager.cpp
index 9ccd1098d3..3157c84f85 100644
--- a/engines/sci/engine/seg_manager.cpp
+++ b/engines/sci/engine/seg_manager.cpp
@@ -976,11 +976,11 @@ void SegManager::createClassTable() {
if (!vocab996)
error("SegManager: failed to open vocab 996");
- int totalClasses = vocab996->size >> 2;
+ int totalClasses = vocab996->size() >> 2;
_classTable.resize(totalClasses);
for (uint16 classNr = 0; classNr < totalClasses; classNr++) {
- uint16 scriptNr = READ_SCI11ENDIAN_UINT16(vocab996->data + classNr * 4 + 2);
+ uint16 scriptNr = vocab996->getUint16SEAt(classNr * 4 + 2);
_classTable[classNr].reg = NULL_REG;
_classTable[classNr].script = scriptNr;
@@ -993,15 +993,13 @@ reg_t SegManager::getClassAddress(int classnr, ScriptLoadType lock, uint16 calle
if (classnr < 0 || (int)_classTable.size() <= classnr || _classTable[classnr].script < 0) {
error("[VM] Attempt to dereference class %x, which doesn't exist (max %x)", classnr, _classTable.size());
- return NULL_REG;
} else {
Class *the_class = &_classTable[classnr];
if (!the_class->reg.getSegment()) {
getScriptSegment(the_class->script, lock);
if (!the_class->reg.getSegment()) {
- error("[VM] Trying to instantiate class %x by instantiating script 0x%x (%03d) failed;", classnr, the_class->script, the_class->script);
- return NULL_REG;
+ error("[VM] Trying to instantiate class %x by instantiating script 0x%x (%03d) failed", classnr, the_class->script, the_class->script);
}
} else
if (callerSegment != the_class->reg.getSegment())
diff --git a/engines/sci/engine/workarounds.cpp b/engines/sci/engine/workarounds.cpp
index ed913b27eb..84211fd432 100644
--- a/engines/sci/engine/workarounds.cpp
+++ b/engines/sci/engine/workarounds.cpp
@@ -929,7 +929,7 @@ SciWorkaroundSolution trackOriginAndFindWorkaround(int index, const SciWorkaroun
}
// now actually check for signature match
- if (g_sci->getScriptPatcher()->verifySignature(curLocalCallOffset, workaround->localCallSignature, "workaround signature", curScriptPtr, curScriptSize)) {
+ if (g_sci->getScriptPatcher()->verifySignature(curLocalCallOffset, workaround->localCallSignature, "workaround signature", SciSpan<const byte>(curScriptPtr, curScriptSize))) {
matched = true;
}