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