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