From 97878dfb4d32c508e5d90309d928b85b559619e2 Mon Sep 17 00:00:00 2001 From: Tibor Nagy Date: Wed, 19 Feb 2020 08:56:57 +0100 Subject: [PATCH] HexEditor: Fix out of bounds cursor Fixing out of bounds cursor in three different cases: - when the buffer is empty - when loading new files - when entering values at the end of the buffer --- Applications/HexEditor/HexEditor.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Applications/HexEditor/HexEditor.cpp b/Applications/HexEditor/HexEditor.cpp index 89fbf6f70a..4ce6f6f95a 100644 --- a/Applications/HexEditor/HexEditor.cpp +++ b/Applications/HexEditor/HexEditor.cpp @@ -67,6 +67,8 @@ void HexEditor::set_buffer(const ByteBuffer& buffer) { m_buffer = buffer; set_content_length(buffer.size()); + m_position = 0; + m_byte_position = 0; update(); update_status(); } @@ -417,6 +419,10 @@ void HexEditor::keydown_event(GUI::KeyEvent& event) void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event) { if ((event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) || (event.key() >= KeyCode::Key_A && event.key() <= KeyCode::Key_F)) { + if (m_buffer.is_empty()) + return; + ASSERT(m_position >= 0); + ASSERT(m_position < m_buffer.size()); // yes, this is terrible... but it works. auto value = (event.key() >= KeyCode::Key_0 && event.key() <= KeyCode::Key_9) @@ -429,7 +435,8 @@ void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event) m_byte_position++; } else { m_buffer.data()[m_position] = (m_buffer.data()[m_position] & 0xF0) | value; // save the first 4 bits, OR the new value in the last 4 - m_position++; + if (m_position + 1 < m_buffer.size()) + m_position++; m_byte_position = 0; } @@ -441,10 +448,17 @@ void HexEditor::hex_mode_keydown_event(GUI::KeyEvent& event) void HexEditor::text_mode_keydown_event(GUI::KeyEvent& event) { + if (m_buffer.is_empty()) + return; + ASSERT(m_position >= 0); + ASSERT(m_position < m_buffer.size()); + m_tracked_changes.set(m_position, m_buffer.data()[m_position]); m_buffer.data()[m_position] = (u8)event.text().characters()[0]; // save the first 4 bits, OR the new value in the last 4 - m_position++; + if (m_position + 1 < m_buffer.size()) + m_position++; m_byte_position = 0; + update(); update_status(); did_change();