From: Jonathan Neuschäfer <j.neuschaefer@gmx.net>
Date: Tue, 9 Jan 2018 00:00:55 +0000 (+0100)
Subject: mem_t: Throw an error if zero-sized memory is requested (#168)
X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=fd0dbf46c3d9f8b005d35dfed79dbd4b4b0f974a;p=riscv-isa-sim.git

mem_t: Throw an error if zero-sized memory is requested (#168)

* mem_t: Throw an error if zero-sized memory is requested

If for some reason the user requests a memory size of 0 megabytes, print
a useful error message.

* Check for overflow in memory size

If the user passes in a large enough memory size (-m) that the size in
bytes doesn't fit into size_t, catch this error in the make_mems function.
---

diff --git a/riscv/devices.h b/riscv/devices.h
index e4df6c9..4e4d27f 100644
--- a/riscv/devices.h
+++ b/riscv/devices.h
@@ -41,6 +41,8 @@ class rom_device_t : public abstract_device_t {
 class mem_t : public abstract_device_t {
  public:
   mem_t(size_t size) : len(size) {
+    if (!size)
+      throw std::runtime_error("zero bytes of target memory requested");
     data = (char*)calloc(1, size);
     if (!data)
       throw std::runtime_error("couldn't allocate " + std::to_string(size) + " bytes of target memory");
diff --git a/spike_main/spike.cc b/spike_main/spike.cc
index 1205965..d3caa22 100644
--- a/spike_main/spike.cc
+++ b/spike_main/spike.cc
@@ -47,6 +47,8 @@ static std::vector<std::pair<reg_t, mem_t*>> make_mems(const char* arg)
   auto mb = strtoull(arg, &p, 0);
   if (*p == 0) {
     reg_t size = reg_t(mb) << 20;
+    if (size != (size_t)size)
+      throw std::runtime_error("Size would overflow size_t");
     return std::vector<std::pair<reg_t, mem_t*>>(1, std::make_pair(reg_t(DRAM_BASE), new mem_t(size)));
   }