openMSX
Rom.cc
Go to the documentation of this file.
1#include "Rom.hh"
2#include "DeviceConfig.hh"
3#include "HardwareConfig.hh"
4#include "XMLElement.hh"
5#include "RomInfo.hh"
6#include "RomDatabase.hh"
7#include "FileContext.hh"
8#include "Filename.hh"
9#include "FileException.hh"
10#include "PanasonicMemory.hh"
11#include "MSXMotherBoard.hh"
12#include "Reactor.hh"
13#include "Debugger.hh"
14#include "Debuggable.hh"
15#include "CliComm.hh"
16#include "FilePool.hh"
17#include "ConfigException.hh"
18#include "EmptyPatch.hh"
19#include "IPSPatch.hh"
20#include "ranges.hh"
21#include "sha1.hh"
22#include "stl.hh"
23#include <cstring>
24#include <limits>
25#include <memory>
26
27using std::string;
28
29namespace openmsx {
30
31class RomDebuggable final : public Debuggable
32{
33public:
34 RomDebuggable(Debugger& debugger, Rom& rom);
36 RomDebuggable(const RomDebuggable&) = delete;
38
39 [[nodiscard]] unsigned getSize() const override;
40 [[nodiscard]] std::string_view getDescription() const override;
41 [[nodiscard]] byte read(unsigned address) override;
42 void write(unsigned address, byte value) override;
43 void moved(Rom& r);
44private:
45 Debugger& debugger;
46 Rom* rom;
47};
48
49
50Rom::Rom(string name_, static_string_view description_,
51 const DeviceConfig& config, const string& id /*= {}*/)
52 : name(std::move(name_)), description(description_)
53{
54 // Try all <rom> tags with matching "id" attribute.
55 string errors;
56 for (const auto* c : config.getXML()->getChildren("rom")) {
57 if (c->getAttributeValue("id", {}) == id) {
58 try {
59 init(config.getMotherBoard(), *c, config.getFileContext());
60 return;
61 } catch (MSXException& e) {
62 // remember error message, and try next
63 if (!errors.empty() && (errors.back() != '\n')) {
64 errors += '\n';
65 }
66 errors += e.getMessage();
67 }
68 }
69 }
70 if (errors.empty()) {
71 // No matching <rom> tag.
72 string err = "Missing <rom> tag";
73 if (!id.empty()) {
74 strAppend(err, " with id=\"", id, '"');
75 }
76 throw ConfigException(std::move(err));
77 } else {
78 // We got at least one matching <rom>, but it failed to load.
79 // Report error messages of all failed attempts.
80 throw ConfigException(errors);
81 }
82}
83
84void Rom::init(MSXMotherBoard& motherBoard, const XMLElement& config,
85 const FileContext& context)
86{
87 // (Only) if the content of this ROM depends on state that is not part
88 // of a savestate, we want to compare the sha1sum of the ROM from the
89 // time the savestate was created with the one from the loaded
90 // savestate. External state can be a .rom file or a patch file.
91 bool checkResolvedSha1 = false;
92
93 auto sums = to_vector(config.getChildren("sha1"));
94 auto filenames = to_vector(config.getChildren("filename"));
95 const auto* resolvedFilenameElem = config.findChild("resolvedFilename");
96 const auto* resolvedSha1Elem = config.findChild("resolvedSha1");
97 if (config.findChild("firstblock")) {
98 // part of the TurboR main ROM
99 // If there is a firstblock/lastblock tag, (only) use these to
100 // locate the rom. In the past we would also write add a
101 // resolvedSha1 tag for this type of ROM (before we used
102 // 'checkResolvedSha1'). So there are old savestates that have
103 // both type of tags. For such a savestate it's important to
104 // first check firstblock, otherwise it will only load when
105 // there is a file that matches the sha1sums of the
106 // firstblock-lastblock portion of the containing file.
107 int first = config.getChildDataAsInt("firstblock", 0);
108 int last = config.getChildDataAsInt("lastblock", 0);
109 size = (last - first + 1) * 0x2000;
110 rom = motherBoard.getPanasonicMemory().getRomRange(first, last);
111 assert(rom);
112
113 // Part of a bigger (already checked) rom, no need to check.
114 checkResolvedSha1 = false;
115
116 } else if (resolvedFilenameElem || resolvedSha1Elem ||
117 !sums.empty() || !filenames.empty()) {
118 auto& filepool = motherBoard.getReactor().getFilePool();
119 // first try already resolved filename ..
120 if (resolvedFilenameElem) {
121 try {
122 file = File(std::string(resolvedFilenameElem->getData()));
123 } catch (FileException&) {
124 // ignore
125 }
126 }
127 // .. then try the actual sha1sum ..
128 auto fileType = context.isUserContext()
130 if (!file.is_open() && resolvedSha1Elem) {
131 Sha1Sum sha1(resolvedSha1Elem->getData());
132 file = filepool.getFile(fileType, sha1);
133 if (file.is_open()) {
134 // avoid recalculating same sha1 later
135 originalSha1 = sha1;
136 }
137 }
138 // .. and then try filename as originally given by user ..
139 if (!file.is_open()) {
140 for (auto& f : filenames) {
141 try {
142 file = File(Filename(f->getData(), context));
143 break;
144 } catch (FileException&) {
145 // ignore
146 }
147 }
148 }
149 // .. then try all alternative sha1sums ..
150 // (this might retry the actual sha1sum)
151 if (!file.is_open()) {
152 for (auto& s : sums) {
153 Sha1Sum sha1(s->getData());
154 file = filepool.getFile(fileType, sha1);
155 if (file.is_open()) {
156 // avoid recalculating same sha1 later
157 originalSha1 = sha1;
158 break;
159 }
160 }
161 }
162 // .. still no file, then error
163 if (!file.is_open()) {
164 string error = strCat("Couldn't find ROM file for \"", name, '"');
165 if (!filenames.empty()) {
166 strAppend(error, ' ', filenames.front()->getData());
167 }
168 if (resolvedSha1Elem) {
169 strAppend(error, " (sha1: ", resolvedSha1Elem->getData(), ')');
170 } else if (!sums.empty()) {
171 strAppend(error, " (sha1: ", sums.front()->getData(), ')');
172 }
173 strAppend(error, '.');
174 throw MSXException(std::move(error));
175 }
176
177 // actually read file content
178 if (config.findChild("filesize") ||
179 config.findChild("skip_headerbytes")) {
180 throw MSXException(
181 "The <filesize> and <skip_headerbytes> tags "
182 "inside a <rom> section are no longer "
183 "supported.");
184 }
185 try {
186 auto mmap = file.mmap();
187 if (mmap.size() > std::numeric_limits<decltype(size)>::max()) {
188 throw MSXException("Rom file too big: ", file.getURL());
189 }
190 rom = mmap.data();
191 size = unsigned(mmap.size());
192 } catch (FileException&) {
193 throw MSXException("Error reading ROM image: ", file.getURL());
194 }
195
196 // For file-based roms, calc sha1 via File::getSha1Sum(). It can
197 // possibly use the FilePool cache to avoid the calculation.
198 if (originalSha1.empty()) {
199 originalSha1 = filepool.getSha1Sum(file);
200 }
201
202 // verify SHA1
203 if (!checkSHA1(config)) {
204 motherBoard.getMSXCliComm().printWarning(
205 "SHA1 sum for '", name,
206 "' does not match with sum of '",
207 file.getURL(), "'.");
208 }
209
210 // We loaded an external file, so check.
211 checkResolvedSha1 = true;
212
213 } else {
214 // for an empty SCC the <size> tag is missing, so take 0
215 // for MegaFlashRomSCC the <size> tag is used to specify
216 // the size of the mapper (and you don't care about initial
217 // content)
218 size = config.getChildDataAsInt("size", 0) * 1024; // in kb
219 extendedRom.resize(size);
220 memset(extendedRom.data(), 0xff, size);
221 rom = extendedRom.data();
222
223 // Content does not depend on external files. No need to check
224 checkResolvedSha1 = false;
225 }
226
227 if (size != 0) {
228 if (const auto* patchesElem = config.findChild("patches")) {
229 // calculate before content is altered
230 (void)getOriginalSHA1(); // fills cache
231
232 std::unique_ptr<PatchInterface> patch =
233 std::make_unique<EmptyPatch>(rom, size);
234
235 for (const auto* p : patchesElem->getChildren("ips")) {
236 patch = std::make_unique<IPSPatch>(
237 Filename(p->getData(), context),
238 std::move(patch));
239 }
240 auto patchSize = unsigned(patch->getSize());
241 if (patchSize <= size) {
242 patch->copyBlock(0, const_cast<byte*>(rom), size);
243 } else {
244 size = patchSize;
245 extendedRom.resize(size);
246 patch->copyBlock(0, extendedRom.data(), size);
247 rom = extendedRom.data();
248 }
249
250 // calculated because it's different from original
251 actualSha1 = SHA1::calc({rom, size});
252
253 // Content altered by external patch file -> check.
254 checkResolvedSha1 = true;
255 }
256 }
257
258 // TODO fix this, this is a hack that depends heavily on
259 // HardwareConfig::createRomConfig
260 if (name.starts_with("MSXRom")) {
261 auto& db = motherBoard.getReactor().getSoftwareDatabase();
262 std::string_view title;
263 if (const auto* romInfo = db.fetchRomInfo(getOriginalSHA1())) {
264 title = romInfo->getTitle(db.getBufferStart());
265 }
266 if (!title.empty()) {
267 name = title;
268 } else {
269 // unknown ROM, use file name
270 name = file.getOriginalName();
271 }
272 }
273
274 // Make name unique wrt all registered debuggables.
275 auto& debugger = motherBoard.getDebugger();
276 if (size) {
277 if (debugger.findDebuggable(name)) {
278 unsigned n = 0;
279 string tmp;
280 do {
281 tmp = strCat(name, " (", ++n, ')');
282 } while (debugger.findDebuggable(tmp));
283 name = std::move(tmp);
284 }
285 }
286
287 if (checkResolvedSha1) {
288 auto& doc = motherBoard.getMachineConfig()->getXMLDocument();
289 auto patchedSha1Str = getSHA1().toString();
290 const auto* actualSha1Elem = doc.getOrCreateChild(
291 const_cast<XMLElement&>(config),
292 "resolvedSha1", doc.allocateString(patchedSha1Str));
293 if (actualSha1Elem->getData() != patchedSha1Str) {
294 std::string_view tmp = file.is_open() ? file.getURL() : name;
295 // can only happen in case of loadstate
296 motherBoard.getMSXCliComm().printWarning(
297 "The content of the rom ", tmp, " has "
298 "changed since the time this savestate was "
299 "created. This might result in emulation "
300 "problems.");
301 }
302 }
303
304 // This must come after we store the 'resolvedSha1', because on
305 // loadstate we use that tag to search the complete rom in a filepool.
306 if (const auto* windowElem = config.findChild("window")) {
307 unsigned windowBase = windowElem->getAttributeValueAsInt("base", 0);
308 unsigned windowSize = windowElem->getAttributeValueAsInt("size", size);
309 if ((windowBase + windowSize) > size) {
310 throw MSXException(
311 "The specified window [", windowBase, ',',
312 windowBase + windowSize, ") falls outside "
313 "the rom (with size ", size, ").");
314 }
315 rom = &rom[windowBase];
316 size = windowSize;
317 }
318
319 // Only create the debuggable once all checks succeeded.
320 if (size) {
321 romDebuggable = std::make_unique<RomDebuggable>(debugger, *this);
322 }
323}
324
325bool Rom::checkSHA1(const XMLElement& config) const
326{
327 auto sums = to_vector(config.getChildren("sha1"));
328 return sums.empty() ||
330 [](const auto* s) { return Sha1Sum(s->getData()); });
331}
332
333Rom::Rom(Rom&& r) noexcept
334 : rom (std::move(r.rom))
335 , extendedRom (std::move(r.extendedRom))
336 , file (std::move(r.file))
337 , originalSha1 (std::move(r.originalSha1))
338 , actualSha1 (std::move(r.actualSha1))
339 , name (std::move(r.name))
340 , description (std::move(r.description))
341 , size (std::move(r.size))
342 , romDebuggable(std::move(r.romDebuggable))
343{
344 if (romDebuggable) romDebuggable->moved(*this);
345}
346
347Rom::~Rom() = default;
348
349std::string_view Rom::getFilename() const
350{
351 return file.is_open() ? file.getURL() : std::string_view();
352}
353
355{
356 if (originalSha1.empty()) {
357 originalSha1 = SHA1::calc({rom, size});
358 }
359 return originalSha1;
360}
361
362const Sha1Sum& Rom::getSHA1() const
363{
364 if (actualSha1.empty())
365 {
366 actualSha1 = getOriginalSHA1();
367 }
368 return actualSha1;
369}
370
371void Rom::addPadding(unsigned newSize, byte filler)
372{
373 assert(newSize >= size);
374 if (newSize == size) return;
375
376 MemBuffer<byte> tmp(newSize);
377 auto* newData = tmp.data();
378 memcpy(newData, rom, size);
379 memset(newData + size, filler, newSize - size);
380
381 extendedRom = std::move(tmp);
382 rom = newData;
383 size = newSize;
384}
385
387 : debugger(debugger_), rom(&rom_)
388{
389 debugger.registerDebuggable(rom->getName(), *this);
390}
391
393{
394 debugger.unregisterDebuggable(rom->getName(), *this);
395}
396
398{
399 return rom->getSize();
400}
401
402std::string_view RomDebuggable::getDescription() const
403{
404 return rom->getDescription();
405}
406
407byte RomDebuggable::read(unsigned address)
408{
409 assert(address < getSize());
410 return (*rom)[address];
411}
412
413void RomDebuggable::write(unsigned /*address*/, byte /*value*/)
414{
415 // ignore
416}
417
419{
420 rom = &r;
421}
422
423} // namespace openmsx
void printWarning(std::string_view message)
Definition: CliComm.cc:10
void unregisterDebuggable(std::string_view name, Debuggable &debuggable)
Definition: Debugger.cc:51
void registerDebuggable(std::string name, Debuggable &debuggable)
Definition: Debugger.cc:45
const FileContext & getFileContext() const
Definition: DeviceConfig.cc:9
MSXMotherBoard & getMotherBoard() const
Definition: DeviceConfig.cc:13
const XMLElement * getXML() const
Definition: DeviceConfig.hh:48
std::span< const uint8_t > mmap()
Map file in memory.
Definition: File.cc:101
std::string_view getOriginalName()
Get Original filename for this object.
Definition: File.cc:146
bool is_open() const
Return true iff this file handle refers to an open file.
Definition: File.hh:63
const std::string & getURL() const
Returns the URL of this file object.
Definition: File.cc:136
XMLDocument & getXMLDocument()
const HardwareConfig * getMachineConfig() const
PanasonicMemory & getPanasonicMemory()
void resize(size_t size)
Grow or shrink the memory block.
Definition: MemBuffer.hh:111
const T * data() const
Returns pointer to the start of the memory buffer.
Definition: MemBuffer.hh:81
const byte * getRomRange(unsigned first, unsigned last)
RomDatabase & getSoftwareDatabase()
Definition: Reactor.cc:304
FilePool & getFilePool()
Definition: Reactor.hh:91
RomDebuggable & operator=(const RomDebuggable &)=delete
unsigned getSize() const override
Definition: Rom.cc:397
byte read(unsigned address) override
Definition: Rom.cc:407
void write(unsigned address, byte value) override
Definition: Rom.cc:413
RomDebuggable(const RomDebuggable &)=delete
RomDebuggable(Debugger &debugger, Rom &rom)
Definition: Rom.cc:386
void moved(Rom &r)
Definition: Rom.cc:418
std::string_view getDescription() const override
Definition: Rom.cc:402
std::string_view getDescription() const
Definition: Rom.hh:38
unsigned getSize() const
Definition: Rom.hh:34
const Sha1Sum & getSHA1() const
Definition: Rom.cc:362
const Sha1Sum & getOriginalSHA1() const
Definition: Rom.cc:354
std::string_view getFilename() const
Definition: Rom.cc:349
Rom(std::string name, static_string_view description, const DeviceConfig &config, const std::string &id={})
Definition: Rom.cc:50
const std::string & getName() const
Definition: Rom.hh:37
void addPadding(unsigned newSize, byte filler=0xff)
Definition: Rom.cc:371
static Sha1Sum calc(std::span< const uint8_t > data)
Easier to use interface, if you can pass all data in one go.
Definition: utils/sha1.cc:363
This class represents the result of a sha1 calculation (a 160-bit value).
Definition: sha1.hh:22
bool empty() const
Definition: utils/sha1.cc:241
std::string toString() const
Definition: utils/sha1.cc:229
int getChildDataAsInt(std::string_view childName, int defaultValue) const
Definition: XMLElement.cc:81
const XMLElement * findChild(std::string_view childName) const
Definition: XMLElement.cc:19
ChildRange getChildren() const
Definition: XMLElement.hh:194
static_string_view
constexpr double e
Definition: Math.hh:18
std::optional< Context > context
Definition: GLContext.cc:9
constexpr vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:283
This file implemented 3 utility functions:
Definition: Autofire.cc:9
STL namespace.
size_t size(std::string_view utf8)
auto to_vector(Range &&range) -> std::vector< detail::ToVectorType< T, decltype(std::begin(range))> >
Definition: stl.hh:266
constexpr bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition: stl.hh:23
std::string strCat(Ts &&...ts)
Definition: strCat.hh:549
void strAppend(std::string &result, Ts &&...ts)
Definition: strCat.hh:627