Added more security to EventHook.
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Deukhoofd 2020-08-01 11:34:25 +02:00
parent 301f9b9656
commit 1b9da9a721
Signed by: Deukhoofd
GPG Key ID: ADF2E9256009EDCE
1 changed files with 13 additions and 10 deletions

View File

@ -15,7 +15,7 @@ namespace CreatureLib::Battling {
private: private:
std::vector<EventHookFunc> _listeners; std::vector<EventHookFunc> _listeners;
size_t _position; size_t _offset;
size_t _capacity; size_t _capacity;
uint8_t* _memory = nullptr; uint8_t* _memory = nullptr;
@ -23,34 +23,37 @@ namespace CreatureLib::Battling {
static const size_t defaultSize = 1024; static const size_t defaultSize = 1024;
public: public:
EventHook() : _position(0), _capacity(defaultSize), _memory(static_cast<uint8_t*>(malloc(defaultSize))) { EventHook() : _offset(0), _capacity(defaultSize) {
if (_memory == nullptr) { auto ptr = calloc(defaultSize, 1);
if (ptr == nullptr) {
THROW_CREATURE("Out of memory."); THROW_CREATURE("Out of memory.");
} }
_memory = static_cast<uint8_t*>(ptr);
} }
EventHook(const EventHook&) = delete; EventHook(const EventHook&) = delete;
EventHook& operator=(const EventHook&) = delete; EventHook& operator=(const EventHook&) = delete;
~EventHook() { free(_memory); } ~EventHook() { free(_memory); }
size_t GetPosition() const noexcept { return _position; } size_t GetPosition() const noexcept { return _offset; }
size_t GetCapacity() const noexcept { return _capacity; } size_t GetCapacity() const noexcept { return _capacity; }
template <class T, class... parameters> void Trigger(parameters... args) { template <class T, class... parameters> void Trigger(parameters... args) {
if (_listeners.size() == 0) if (_listeners.size() == 0)
return; return;
if (_position + sizeof(T) >= _capacity) { if (_offset + sizeof(T) >= _capacity) {
_capacity += defaultSize; _capacity += defaultSize;
_memory = static_cast<uint8_t*>(realloc(_memory, _capacity)); auto newPtr = realloc(_memory, _capacity);
if (_memory == nullptr) { if (newPtr == nullptr) {
THROW_CREATURE("Out of memory."); THROW_CREATURE("Out of memory.");
} }
_memory = static_cast<uint8_t*>(newPtr);
} }
uint8_t* ptr = _memory + _position; uint8_t* ptr = _memory + _offset;
T* event = new (ptr) T(args...); T* event = new (ptr) T(args...);
_position += sizeof(T); _offset += sizeof(T);
for (auto listener : _listeners) { for (auto listener : _listeners) {
listener(event); try_creature(listener(event), "Exception in event listener");
} }
} }