Skip to content

Commit

Permalink
[memory] Fix read_cstring trying to read too far (#1112)
Browse files Browse the repository at this point in the history
  • Loading branch information
ValekoZ authored Sep 29, 2024
1 parent 115137c commit d8a3043
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
20 changes: 18 additions & 2 deletions gef.py
Original file line number Diff line number Diff line change
Expand Up @@ -10742,8 +10742,24 @@ def read_cstring(self,
try:
res_bytes = self.read(address, length)
except gdb.error:
err(f"Can't read memory at '{address}'")
return ""
current_address = address
res_bytes = b""
while len(res_bytes) < length:
try:
# Calculate how many bytes there are until next page
next_page = current_address + DEFAULT_PAGE_SIZE
page_mask = ~(DEFAULT_PAGE_SIZE - 1)
size = (next_page & page_mask) - current_address

# Read until the end of the current page
res_bytes += self.read(current_address, size)

current_address += size
except gdb.error:
if not res_bytes:
err(f"Can't read memory at '{address:#x}'")
return ""
break
try:
with warnings.catch_warnings():
# ignore DeprecationWarnings (see #735)
Expand Down
14 changes: 14 additions & 0 deletions tests/api/gef_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,17 @@ def test_func_parse_maps_realpath(self):
"/usr" not in section.realpath):
assert pathlib.Path(section.realpath).is_file()
break

def test_func_read_cstring_oob(self):
gef, gdb = self._gef, self._gdb

gdb.execute("b main")
gdb.execute("start")

section = gef.memory.maps[0]
oob_val = gef.memory.read_cstring(section.page_start, section.page_end -
section.page_start + 0x100)
val = gef.memory.read_cstring(section.page_start, section.page_end -
section.page_start)

assert val == oob_val

0 comments on commit d8a3043

Please sign in to comment.