Skip to content

Commit

Permalink
Merge adb647d into f7a2105
Browse files Browse the repository at this point in the history
  • Loading branch information
Grazfather committed Dec 16, 2023
2 parents f7a2105 + adb647d commit e6a8663
Showing 1 changed file with 97 additions and 34 deletions.
131 changes: 97 additions & 34 deletions gef.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ def update_gef(argv: List[str]) -> int:
__registered_architectures__ : Dict[Union["Elf.Abi", str], Type["Architecture"]] = {}
__registered_file_formats__ : Set[ Type["FileFormat"] ] = set()

GefMemoryMapProvider = Callable[[], Generator["Section", None, None]]


def reset_all_caches() -> None:
"""Free all caches. If an object is cached, it will have a callable attribute `cache_clear`
Expand Down Expand Up @@ -644,14 +646,22 @@ def from_process_maps(cls, perm_str: str) -> "Permission":
return perm

@classmethod
def from_info_mem(cls, perm_str: str) -> "Permission":
def from_monitor_info_mem(cls, perm_str: str) -> "Permission":
perm = cls(0)
# perm_str[0] shows if this is a user page, which
# we don't track
if perm_str[1] == "r": perm |= Permission.READ
if perm_str[2] == "w": perm |= Permission.WRITE
return perm

@classmethod
def from_info_mem(cls, perm_str: str) -> "Permission":
perm = cls(0)
if "r" in perm_str: perm |= Permission.READ
if "w" in perm_str: perm |= Permission.WRITE
if "x" in perm_str: perm |= Permission.EXECUTE
return perm


class Section:
"""GEF representation of process memory sections."""
Expand Down Expand Up @@ -2258,6 +2268,7 @@ class Architecture(ArchitectureBase):
_ptrsize: Optional[int] = None
_endianness: Optional[Endianness] = None
special_registers: Union[Tuple[()], Tuple[str, ...]] = ()
maps: Optional[GefMemoryMapProvider] = None

def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Expand Down Expand Up @@ -2810,6 +2821,24 @@ class X86(Architecture):
_ptrsize = 4
_endianness = Endianness.LITTLE_ENDIAN

# TODO: Delete this, this is for testing only
@staticmethod
def maps():
try:
return list(GefMemoryManager.parse_procfs_maps())
except:
pass

try:
return list(GefMemoryManager.parse_gdb_info_sections())
except:
pass

try:
return list(GefMemoryManager.parse_monitor_info_mem())
except:
pass

def flag_register_to_human(self, val: Optional[int] = None) -> str:
reg = self.flag_register
if not val:
Expand Down Expand Up @@ -10368,19 +10397,31 @@ def maps(self) -> List[Section]:
return self.__maps

def __parse_maps(self) -> List[Section]:
"""Return the mapped memory sections"""
"""Return the mapped memory sections. If the current arch has its maps
method defined, then defer to that to generated maps, otherwise, try to
figure it out from procfs, then info sections, then monitor info
mem."""
if gef.arch.maps is not None:
maps = list(gef.arch.maps())
return maps

try:
if is_qemu_system():
return list(self.__parse_info_mem())
except gdb.error:
# Target may not support this command
return list(self.parse_procfs_maps())
except:
pass

try:
return list(self.__parse_procfs_maps())
except FileNotFoundError:
return list(self.__parse_gdb_info_sections())
return list(self.parse_gdb_info_sections())
except:
pass

try:
return list(self.parse_monitor_info_mem())
except:
pass

def __parse_procfs_maps(self) -> Generator[Section, None, None]:
@staticmethod
def parse_procfs_maps() -> Generator[Section, None, None]:
"""Get the memory mapping from procfs."""
procfs_mapfile = gef.session.maps
if not procfs_mapfile:
Expand All @@ -10403,14 +10444,15 @@ def __parse_procfs_maps(self) -> Generator[Section, None, None]:
perm = Permission.from_process_maps(perm)
inode = int(inode)
yield Section(page_start=addr_start,
page_end=addr_end,
offset=off,
permission=perm,
inode=inode,
path=pathname)
page_end=addr_end,
offset=off,
permission=perm,
inode=inode,
path=pathname)
return

def __parse_gdb_info_sections(self) -> Generator[Section, None, None]:
@staticmethod
def parse_gdb_info_sections() -> Generator[Section, None, None]:
"""Get the memory mapping from GDB's command `maintenance info sections` (limited info)."""
stream = StringIO(gdb.execute("maintenance info sections", to_string=True))

Expand All @@ -10424,24 +10466,27 @@ def __parse_gdb_info_sections(self) -> Generator[Section, None, None]:
off = int(parts[3][:-1], 16)
path = parts[4]
perm = Permission.from_info_sections(parts[5:])
yield Section(
page_start=addr_start,
page_end=addr_end,
offset=off,
permission=perm,
inode="",
path=path
)
yield Section(page_start=addr_start,
page_end=addr_end,
offset=off,
permission=perm,
path=path)

except IndexError:
continue
except ValueError:
continue
return

def __parse_info_mem(self) -> Generator[Section, None, None]:
@staticmethod
def parse_monitor_info_mem() -> Generator[Section, None, None]:
"""Get the memory mapping from GDB's command `monitor info mem`"""
for line in StringIO(gdb.execute("monitor info mem", to_string=True)):
try:
stream = StringIO(gdb.execute("monitor info mem", to_string=True))
except Exception:
return

for line in stream:
if not line:
break
try:
Expand All @@ -10451,14 +10496,32 @@ def __parse_info_mem(self) -> Generator[Section, None, None]:
except ValueError as e:
continue

perm = Permission.from_info_mem(perms)
yield Section(
page_start=start,
page_end=end,
offset=off,
permission=perm,
inode="",
)
perm = Permission.from_monitor_info_mem(perms)
yield Section(page_start=start,
page_end=end,
offset=off,
permission=perm)

@staticmethod
def parse_info_mem():
"""Get the memory mapping from GDB's command `info mem`. This can be
provided by certain gdbserver implementations."""
for line in StringIO(gdb.execute("info mem", to_string=True)):
# Using memory regions provided by the target.
# Num Enb Low Addr High Addr Attrs
# 0 y 0x10000000 0x10200000 flash blocksize 0x1000 nocache
# 1 y 0x20000000 0x20042000 rw nocache
_, en, start, end, *attrs = line.split()
if en != "y":
continue

if "flash" in attrs:
perm = Permission.from_info_mem("r")
else:
perm = Permission.from_info_mem("rw")
yield Section(page_start=int(start, 0),
page_end=int(end, 0),
permission=perm)


class GefHeapManager(GefManager):
Expand Down

0 comments on commit e6a8663

Please sign in to comment.