# HG changeset patch # User František Kučera # Date 1514047952 -3600 # Node ID 4975c24cc361c3f0e3103ac1618f3d1fa2dd0376 # Parent 8f0a5552db789132b6b9990c620777145a74d19d check memory bounds in read() and write() diff -r 8f0a5552db78 -r 4975c24cc361 c++/rgb-assembler/rgb-assembler.cpp --- a/c++/rgb-assembler/rgb-assembler.cpp Sat Dec 23 17:33:49 2017 +0100 +++ b/c++/rgb-assembler/rgb-assembler.cpp Sat Dec 23 17:52:32 2017 +0100 @@ -76,6 +76,12 @@ // TODO: more commands, better numbers +template T logMemoryError(const address_t &index) { + wprintf(L"memory error: index = %d, sizeof(T) = %d, MEMORY_SIZE = %d\n", index, sizeof (T), MEMORY_SIZE); + // TODO: return error value or throw exception + return T(); +} + /** * Reads data on given position in memory and increments the index (position). * @@ -84,10 +90,14 @@ * @return value found at given position */ template T read(octet_t * memory, address_t &index) { - // TODO: for addresses: map higher memory to static hardcoded areas or peripherals - T * value = reinterpret_cast (memory + index); - index += sizeof (T); - return *value; + // TODO: map higher memory to static hardcoded areas or peripherals + if (index + sizeof (T) <= MEMORY_SIZE) { + T * value = reinterpret_cast (memory + index); + index += sizeof (T); + return *value; + } else { + return logMemoryError(index); + } } /** @@ -96,10 +106,14 @@ * @param index offset in same units as memory type * @param value value to be written at given position */ -template void write(octet_t * memory, address_t &index, const T value) { - T * m = reinterpret_cast (memory + index); - *m = value; - index += sizeof (value); +template T write(octet_t * memory, address_t &index, const T value) { + if (index + sizeof (T) <= MEMORY_SIZE) { + T * m = reinterpret_cast (memory + index); + *m = value; + index += sizeof (value); + } else { + return logMemoryError(index); + } } int main(int argc, char* argv[]) {