SpiNorFlash: check Read/Write for out of bounds

Just to be extra pedantic and to get an error while developing on
InfiniSim. Because on PC we can easily add the debugger, on the device
we can, but it is a bit more involved.
main
Reinhold Gschweicher 2022-05-15 22:46:07 +07:00
parent 644431cbc4
commit 9427d4ddb1
1 changed files with 7 additions and 0 deletions

@ -4,6 +4,7 @@
#include "drivers/Spi.h" #include "drivers/Spi.h"
#include <filesystem> #include <filesystem>
#include <iostream> #include <iostream>
#include <stdexcept>
using namespace Pinetime::Drivers; using namespace Pinetime::Drivers;
@ -63,6 +64,9 @@ uint8_t SpiNorFlash::ReadConfigurationRegister() {
void SpiNorFlash::Read(uint32_t address, uint8_t* buffer, size_t size) { void SpiNorFlash::Read(uint32_t address, uint8_t* buffer, size_t size) {
static_assert(sizeof(uint8_t) == sizeof(char)); static_assert(sizeof(uint8_t) == sizeof(char));
if (address + size * sizeof(uint8_t) > memorySize) {
throw std::runtime_error("SpiNorFlash::Read out of bounds");
}
memoryFile.seekp(address); memoryFile.seekp(address);
memoryFile.read(reinterpret_cast<char *>(buffer), size); memoryFile.read(reinterpret_cast<char *>(buffer), size);
} }
@ -88,6 +92,9 @@ bool SpiNorFlash::EraseFailed() {
} }
void SpiNorFlash::Write(uint32_t address, const uint8_t* buffer, size_t size) { void SpiNorFlash::Write(uint32_t address, const uint8_t* buffer, size_t size) {
if (address + size * sizeof(uint8_t) > memorySize) {
throw std::runtime_error("SpiNorFlash::Write out of bounds");
}
memoryFile.seekp(address); memoryFile.seekp(address);
memoryFile.write(reinterpret_cast<const char *>(buffer), size); memoryFile.write(reinterpret_cast<const char *>(buffer), size);
memoryFile.flush(); memoryFile.flush();