Type fixes (#1517)

* More type fixes

* Don't call Arch.__init__ directly

* Fix context type error

* Fix disasm type error
pull/1518/head
Gulshan Singh 3 years ago committed by GitHub
parent 6aa66095d9
commit 301d0b9ccd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -162,9 +162,9 @@ class Command(gdb.Command):
return False
last_line = lines[-1]
number, command = last_line.split(maxsplit=1)
number_str, command = last_line.split(maxsplit=1)
try:
number = int(number)
number = int(number_str)
except ValueError:
# Workaround for a GDB 8.2 bug when show commands return error value
# See issue #523

@ -391,7 +391,7 @@ def context(subcontext=None) -> None:
if len(args) == 0:
args = config_context_sections.split()
sections = [("legend", lambda target=None, **kwargs: [M.legend()])] if args else []
sections = [("legend", lambda *args, **kwargs: [M.legend()])] if args else []
sections += [(arg, context_sections.get(arg[0], None)) for arg in args]
result = defaultdict(list)

@ -950,9 +950,9 @@ def try_free(addr) -> None:
tc_idx = (chunk_size_unmasked - chunk_minsize + malloc_alignment - 1) // malloc_alignment
if tc_idx < allocator.mp["tcache_bins"]:
print(message.notice("Tcache checks"))
e = addr + 2 * size_sz
e += allocator.tcache_entry.keys().index("key") * ptr_size
e = pwndbg.gdblib.memory.pvoid(e)
e = addr + 2 * size_sz # type: ignore[misc]
e += allocator.tcache_entry.keys().index("key") * ptr_size # type: ignore[misc]
e = pwndbg.gdblib.memory.pvoid(e) # type: ignore[misc]
tcache_addr = int(allocator.thread_cache.address)
if e == tcache_addr:
# todo, actually do checks
@ -1028,7 +1028,7 @@ def try_free(addr) -> None:
finalize(errors_found, returned_before_error)
return
fastbin_top_chunk_size = chunksize(unsigned_size(fastbin_top_chunk["size"]))
fastbin_top_chunk_size = chunksize(unsigned_size(fastbin_top_chunk["size"])) # type: ignore[index]
if chunk_fastbin_idx != allocator.fastbin_index(fastbin_top_chunk_size):
err = "invalid fastbin entry (free) -> chunk's size is not near top chunk's size\n"
err += " chunk's size == {}, idx == {}\n"

@ -93,14 +93,13 @@ class Process:
if not line:
continue
k_v = line.split(None, 1)
k_v = line.split(maxsplit=1)
if len(k_v) == 1:
k_v.append(b"")
k, v = k_v
# Python3 ftw!
k = k.decode("latin-1")
v = v.decode("latin-1")
@ -129,7 +128,7 @@ class Process:
# capability sets
if k in ["capeff", "capinh", "capprm", "capbnd"]:
orig = v
orig: int = v
v = []
for i in range(max(capabilities) + 1):
if (orig >> i) & 1 == 1:

@ -5,6 +5,8 @@ address +/- a few instructions.
import collections
from typing import DefaultDict
from typing import List
from typing import Union
import capstone
import gdb
@ -128,13 +130,13 @@ class SimpleInstruction:
def __init__(self, address) -> None:
self.address = address
ins = gdb.newest_frame().architecture().disassemble(address)[0]
asm = ins["asm"].split(None, 1)
asm = ins["asm"].split(maxsplit=1)
self.mnemonic = asm[0].strip()
self.op_str = asm[1].strip() if len(asm) > 1 else ""
self.size = ins["length"]
self.next = self.address + self.size
self.target = self.next
self.groups = []
self.groups: List[Any] = []
self.symbol = None
self.condition = False
@ -151,15 +153,20 @@ def get_one_instruction(address):
return ins
def one(address=None):
def one(address=None) -> Union[capstone.CsInsn, SimpleInstruction]:
if address is None:
address = pwndbg.gdblib.regs.pc
if not pwndbg.gdblib.memory.peek(address):
return None
# TODO: Why a for loop?
for insn in get(address, 1):
backward_cache[insn.next] = insn.address
return insn
return None
def fix(i):
for op in i.operands:
@ -218,7 +225,7 @@ def near(address, instructions=1, emulate=False, show_prev_insns=True):
if current is None or not pwndbg.gdblib.memory.peek(address):
return []
insns = []
insns: List[Union[capstone.CsInsn, SimpleInstruction]] = []
# Try to go backward by seeing which instructions we've returned
# before, which were followed by this one.

@ -53,10 +53,7 @@ def _get_arch(ptrsize):
def update() -> None:
# We can't just assign to `arch` with a new `Arch` object. Modules that have
# already imported it will still have a reference to the old `arch`
# object. Instead, we call `__init__` again with the new args
arch_name, ptrsize, endian = _get_arch(typeinfo.ptrsize)
arch.__init__(arch_name, ptrsize, endian)
arch.update(arch_name, ptrsize, endian)
pwnlib.context.context.arch = pwnlib_archs_mapping[arch_name]
pwnlib.context.context.bits = ptrsize * 8

@ -372,7 +372,7 @@ def map_inner(ei_class, ehdr, objfile):
# For each page described by this program header
for page_addr in range(vaddr, vaddr + memsz, pwndbg.lib.memory.PAGE_SIZE):
if page_addr in pages:
page = pages[pages.index(page_addr)]
page = pages[pages.index(page_addr)] # type: ignore[arg-type]
# Don't ever remove the execute flag.
# Sometimes we'll load a read-only area into .text

@ -88,7 +88,7 @@ def get(address: int, gdb_only=False) -> str:
# main + 3 in section .text of /bin/bash
# system + 1 in section .text of /lib/x86_64-linux-gnu/libc.so.6
# No symbol matches system-1.
a, b, c, _ = result.split(None, 3)
a, b, c, _ = result.split(maxsplit=3)
if b == "+":
return "%s+%s" % (a, c)

@ -385,12 +385,12 @@ def proc_pid_maps():
pages = []
for line in data.splitlines():
maps, perm, offset, dev, inode_objfile = line.split(None, 4)
maps, perm, offset, dev, inode_objfile = line.split(maxsplit=4)
start, stop = maps.split("-")
try:
inode, objfile = inode_objfile.split(None, 1)
inode, objfile = inode_objfile.split(maxsplit=1)
except Exception:
# Name unnamed anonymous pages so they can be used e.g. with search commands
objfile = "[anon_" + start[:-3] + "]"
@ -612,7 +612,7 @@ def info_files():
# The name of the main executable
if line.startswith("`"):
exename, filetype = line.split(None, 1)
exename, filetype = line.split(maxsplit=1)
main_exe = exename.strip("`,'")
continue
@ -620,8 +620,8 @@ def info_files():
if not line.startswith("0x"):
continue
# start, stop, _, segment, _, filename = line.split(None,6)
fields = line.split(None, 6)
# start, stop, _, segment, _, filename = line.split(maxsplit=6)
fields = line.split(maxsplit=6)
vaddr = int(fields[0], 16)
if len(fields) == 5:

@ -1917,9 +1917,9 @@ class HeuristicHeap(GlibcMemoryAllocator):
for reg in regs:
if "[" + reg + "]" in instr.op_str:
# ldr reg1, [pc, #offset]
offset = regs[reg].operands[1].mem.disp
offset = regs[reg].operands[1].mem.disp # type: ignore[index]
offset = pwndbg.gdblib.memory.s32(
(regs[reg].address + 4 & -4) + offset
(regs[reg].address + 4 & -4) + offset # type: ignore[index]
)
# add reg1, pc
self._mp_addr = offset + ldr[reg].address + 4
@ -1930,7 +1930,7 @@ class HeuristicHeap(GlibcMemoryAllocator):
if instr.op_str == reg + ", pc":
ldr[reg] = instr
elif instr.mnemonic == "ldr" and "[pc," in instr.op_str:
regs[instr.operands[0].str] = instr
regs[instr.operands[0].str] = instr # type: ignore[index]
# can't find the reference about mp_ in __libc_free, try to find it with heap boundaries of main_arena
if (

@ -41,8 +41,8 @@ if pwndbg.gdblib.arch.ptrsize == 4:
PTR = ctypes.c_uint32
SIZE_T = ctypes.c_uint32
else:
PTR = ctypes.c_uint64
SIZE_T = ctypes.c_uint64
PTR = ctypes.c_uint64 # type: ignore[misc]
SIZE_T = ctypes.c_uint64 # type: ignore[misc]
class c_pvoid(PTR):

@ -6,6 +6,11 @@ from typing_extensions import Literal
class Arch:
def __init__(self, arch_name: str, ptrsize: int, endian: Literal["little", "big"]) -> None:
self.update(arch_name, ptrsize, endian)
self.native_endian = str(sys.byteorder)
def update(self, arch_name: str, ptrsize: int, endian: Literal["little", "big"]) -> None:
self.name = arch_name
# TODO: `current` is the old name for the arch name, and it's now an
# alias for `name`. It's used throughout the codebase, do we want to
@ -17,7 +22,7 @@ class Arch:
self.fmt = {(4, "little"): "<I", (4, "big"): ">I", (8, "little"): "<Q", (8, "big"): ">Q"}[
(self.ptrsize, self.endian)
] # type: str
]
if self.name == "arm" and self.endian == "big":
self.qemu = "armeb"
@ -26,8 +31,6 @@ class Arch:
else:
self.qemu = self.name
self.native_endian = str(sys.byteorder)
def pack(self, integer: int) -> bytes:
return struct.pack(self.fmt, integer & self.ptrmask)

@ -151,7 +151,7 @@ def unix(data: str):
Num RefCount Protocol Flags Type St Inode Path
0000000000000000: 00000002 00000000 00010000 0005 01 1536 /dev/socket/msm_irqbalance
"""
fields = line.split(None, 7)
fields = line.split(maxsplit=7)
u = UnixSocket()
if len(fields) >= 8:

Loading…
Cancel
Save