From 63c98b41ae2d36808ebbb57e7f8e871ba247d444 Mon Sep 17 00:00:00 2001 From: Andrew Waterman Date: Mon, 1 May 2017 16:44:47 -0700 Subject: [PATCH] Fix segfault when accessing bad memory addresses --- riscv/devices.cc | 11 ++++------- riscv/devices.h | 3 +-- riscv/sim.cc | 5 +++-- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/riscv/devices.cc b/riscv/devices.cc index af4dc7d..15115c8 100644 --- a/riscv/devices.cc +++ b/riscv/devices.cc @@ -21,13 +21,10 @@ bool bus_t::store(reg_t addr, size_t len, const uint8_t* bytes) return it->second->store(addr - -it->first, len, bytes); } -bus_t::descriptor bus_t::find_device(reg_t addr) +std::pair bus_t::find_device(reg_t addr) { auto it = devices.lower_bound(-addr); - if (it == devices.end()) { - bus_t::descriptor desc = {0, 0}; - return desc; - } - bus_t::descriptor desc = {-it->first, it->second}; - return desc; + if (it == devices.end() || addr < -it->first) + return std::make_pair((reg_t)0, (abstract_device_t*)NULL); + return std::make_pair(-it->first, it->second); } diff --git a/riscv/devices.h b/riscv/devices.h index ba344db..0f0c916 100644 --- a/riscv/devices.h +++ b/riscv/devices.h @@ -20,8 +20,7 @@ class bus_t : public abstract_device_t { bool store(reg_t addr, size_t len, const uint8_t* bytes); void add_device(reg_t addr, abstract_device_t* dev); - struct descriptor { reg_t base; abstract_device_t* device; }; - descriptor find_device(reg_t addr); + std::pair find_device(reg_t addr); private: std::map devices; diff --git a/riscv/sim.cc b/riscv/sim.cc index ebf94b6..edf0819 100644 --- a/riscv/sim.cc +++ b/riscv/sim.cc @@ -317,8 +317,9 @@ void sim_t::make_dtb() char* sim_t::addr_to_mem(reg_t addr) { auto desc = bus.find_device(addr); - if (auto mem = dynamic_cast(desc.device)) - return mem->contents() + (addr - desc.base); + if (auto mem = dynamic_cast(desc.second)) + if (addr - desc.first < mem->size()) + return mem->contents() + (addr - desc.first); return NULL; } -- 2.30.2