Skip to content

Commit

Permalink
minor fix + added deprecation checks
Browse files Browse the repository at this point in the history
  • Loading branch information
hugsy committed Jan 8, 2024
1 parent 38c1c6d commit cf824ac
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 50 deletions.
63 changes: 16 additions & 47 deletions gef.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,13 @@
from io import StringIO, TextIOWrapper
from types import ModuleType
from typing import (Any, ByteString, Callable, Dict, Generator, Iterable,
Iterator, List, NoReturn, Optional, Sequence, Set, Tuple, Type,
Union)
Iterator, List, Literal, NoReturn, Optional, Sequence, Set, Tuple, Type,
Union, TYPE_CHECKING)
from urllib.request import urlopen

if TYPE_CHECKING:
import gdb

GEF_DEFAULT_BRANCH = "main"
GEF_EXTRAS_DEFAULT_BRANCH = "main"

Expand Down Expand Up @@ -3399,24 +3402,24 @@ def get_os() -> str:
def is_qemu() -> bool:
if not is_remote_debug():
return False
response = gdb.execute("maintenance packet Qqemu.sstepbits", to_string=True, from_tty=False)
return isinstance(response, str) and "ENABLE=" in response
response = gdb.execute("maintenance packet Qqemu.sstepbits", to_string=True, from_tty=False) or ""
return "ENABLE=" in response


@lru_cache()
def is_qemu_usermode() -> bool:
if not is_qemu():
return False
response = gdb.execute("maintenance packet qOffsets", to_string=True, from_tty=False)
return isinstance(response, str) and "Text=" in response
response = gdb.execute("maintenance packet qOffsets", to_string=True, from_tty=False) or ""
return "Text=" in response


@lru_cache()
def is_qemu_system() -> bool:
if not is_qemu():
return False
response = gdb.execute("maintenance packet qOffsets", to_string=True, from_tty=False)
return isinstance(response, str) and "received: \"\"" in response
response = gdb.execute("maintenance packet qOffsets", to_string=True, from_tty=False) or ""
return "received: \"\"" in response


def get_filepath() -> Optional[str]:
Expand Down Expand Up @@ -3606,7 +3609,7 @@ def exit_handler(_: "gdb.ExitedEvent") -> None:
warn(f"{bkp_fpath} exists, content will be overwritten")

with bkp_fpath.open("w") as fd:
for bp in gdb.breakpoints():
for bp in list(gdb.breakpoints()):
if not bp.enabled or not bp.is_valid:
continue
fd.write(f"{'t' if bp.temporary else ''}break {bp.location}\n")
Expand Down Expand Up @@ -4080,7 +4083,7 @@ def instantiate(self, base: int) -> None:
self.destroy()

try:
res = gdb.execute(self.set_func(base), to_string=True)
res = gdb.execute(self.set_func(base), to_string=True) or ""
if not res: return
except gdb.error as e:
err(str(e))
Expand All @@ -4089,6 +4092,7 @@ def instantiate(self, base: int) -> None:
if "Breakpoint" not in res:
err(res)
return

res_list = res.split()
self.bp_num = res_list[1]
self.bp_addr = res_list[3]
Expand Down Expand Up @@ -6849,41 +6853,6 @@ def do_invoke(self, *_: Any, **kwargs: Any) -> None:
return


@register
class SolveKernelSymbolCommand(GenericCommand):
"""Solve kernel symbols from kallsyms table."""

_cmdline_ = "ksymaddr"
_syntax_ = f"{_cmdline_} SymbolToSearch"
_example_ = f"{_cmdline_} prepare_creds"

@parse_arguments({"symbol": ""}, {})
def do_invoke(self, _: List[str], **kwargs: Any) -> None:
def hex_to_int(num):
try:
return int(num, 16)
except ValueError:
return 0
args : argparse.Namespace = kwargs["arguments"]
if not args.symbol:
self.usage()
return
sym = args.symbol
with open("/proc/kallsyms", "r") as f:
syms = [line.strip().split(" ", 2) for line in f]
matches = [(hex_to_int(addr), sym_t, " ".join(name.split())) for addr, sym_t, name in syms if sym in name]
for addr, sym_t, name in matches:
if sym == name.split()[0]:
ok(f"Found matching symbol for '{name}' at {addr:#x} (type={sym_t})")
else:
warn(f"Found partial match for '{sym}' at {addr:#x} (type={sym_t}): {name}")
if not matches:
err(f"No match for '{sym}'")
elif matches[0][0] == 0:
err("Check that you have the correct permissions to view kernel symbol addresses")
return


@register
class DetailRegistersCommand(GenericCommand):
"""Display full details on one, many or all registers value from current architecture."""
Expand Down Expand Up @@ -7176,7 +7145,7 @@ def do_invoke(self, _: List[str], **kwargs: Any) -> None:

try:
elf = Elf(filename)
except ValueError as ve:
except ValueError:
err(f"`{filename}` is an invalid value for ELF file")
return

Expand Down Expand Up @@ -10926,7 +10895,7 @@ def auxiliary_vector(self) -> Optional[Dict[str, int]]:
return None
if not self._auxiliary_vector:
auxiliary_vector = {}
auxv_info = gdb.execute("info auxv", to_string=True)
auxv_info = gdb.execute("info auxv", to_string=True) or ""
if not auxv_info or "failed" in auxv_info:
err("Failed to query auxiliary variables")
return None
Expand Down
13 changes: 13 additions & 0 deletions tests/api/deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""


import pytest
from tests.base import RemoteGefUnitTestGeneric
from tests.utils import WARNING_DEPRECATION_MESSAGE

Expand Down Expand Up @@ -30,3 +31,15 @@ def test_deprecated_elf_values(self):
for item in old_stuff:
output = gdb.execute(f"pi {item}", to_string=True)
assert WARNING_DEPRECATION_MESSAGE in output

def test_deprecated_gef_attributes(self):
root = self._conn.root
old_attributes = (
"gef.gdb.loaded_commands",
"gef.gdb.loaded_functions",
"gef.gdb.missing_commands",
)

for i in old_attributes:
with pytest.raises(Exception, match="ObsoleteException"):
root.eval(i)
9 changes: 6 additions & 3 deletions tests/commands/nop.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ def test_cmd_nop_nop(self):
gef = self._gef
gdb.execute("start")
gef.memory.write(gef.arch.pc, p32(0x9191))
res = gdb.execute(f"{self.cmd} --n", to_string=True)
res = gdb.execute(f"{self.cmd} --n", to_string=True) or ""
assert res
mem = u16(gef.memory.read(gef.arch.pc, 2))
self.assertEqual(0x9190, mem)

Expand Down Expand Up @@ -173,7 +174,8 @@ def test_cmd_nop_bytes(self):
res = gdb.execute(
f"{self.cmd} --b",
to_string=True,
)
) or ""
assert res
mem = u16(gef.memory.read(gef.arch.pc, 2))
self.assertEqual(0x9190, mem)

Expand Down Expand Up @@ -205,7 +207,8 @@ def test_cmd_nop_bytes_arg(self):
gef = self._gef
gdb.execute("start")
gef.memory.write(gef.arch.pc, p64(0xFEEBFEEBFEEBFEEB))
res = gdb.execute(f"{self.cmd} --i 2 --b --f", to_string=True)
res = gdb.execute(f"{self.cmd} --i 2 --b --f", to_string=True) or ""
assert res
mem = u64(gef.memory.read(gef.arch.pc, 8))
self.assertEqual(0xFEEBFEEBFEEB9090, mem)

Expand Down

0 comments on commit cf824ac

Please sign in to comment.