Fix flake8 warnings (#2100)

* Initial commit for running GH tests

Signed-off-by: Chirag Aggarwal <thechiragaggarwal@outlook.com>

* Removed/Fixed unused variables - flake8 F841 warnings

Signed-off-by: Chirag Aggarwal <thechiragaggarwal@outlook.com>

---------

Signed-off-by: Chirag Aggarwal <thechiragaggarwal@outlook.com>
pull/2102/head
jetchirag 2 years ago committed by GitHub
parent 66740fc803
commit e7548c7f14
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -41,8 +41,6 @@ def instruction(ins):
sym = pwndbg.gdblib.symbol.get(ins.target) or None
target = M.get(ins.target)
const = ins.target_const
hextarget = hex(ins.target)
hexlen = len(hextarget)
# If it's a constant expression, color it directly in the asm.
if const:

@ -194,7 +194,7 @@ class Command(gdb.Command):
def __call__(self, *args: Any, **kwargs: Any) -> str | None:
try:
return self.function(*args, **kwargs)
except TypeError as te:
except TypeError:
print(f"{self.function.__name__.strip()!r}: {self.function.__doc__.strip()}")
pwndbg.exception.handle(self.function.__name__)
except Exception:

@ -189,7 +189,7 @@ def build_context_prompt_body():
try:
source = pwndbg.ghidra.decompile()
decompile = True
except Exception as e:
except Exception:
pass
## Now, let's build the prompt
prompt = "Consider the following context in the GDB debugger:\n"

@ -73,8 +73,6 @@ def print_symbols_in_section(section_name, filter_text="") -> None:
print(message.error(f"Could not find section {section_name}"))
return
elf_header = pwndbg.gdblib.elf.exe()
# If we started the binary and it has PIE, rebase it
if pwndbg.gdblib.proc.alive:
bin_base_addr = pwndbg.gdblib.proc.binary_base_addr

@ -1140,7 +1140,7 @@ def try_free(addr) -> None:
# try to get the chunk
try:
chunk = read_chunk(addr)
except gdb.MemoryError as e:
except gdb.MemoryError:
print(message.error(f"Can't read chunk at address 0x{addr:x}, memory error"))
return
@ -1202,9 +1202,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 # type: ignore[misc]
e += allocator.tcache_entry.keys().index("key") * ptr_size # type: ignore[misc]
e = pwndbg.gdblib.memory.pvoid(e) # type: ignore[misc]
e = addr + 2 * size_sz
e += allocator.tcache_entry.keys().index("key") * ptr_size
e = pwndbg.gdblib.memory.pvoid(e)
tcache_addr = int(allocator.thread_cache.address)
if e == tcache_addr:
# todo, actually do checks
@ -1267,7 +1267,7 @@ def try_free(addr) -> None:
if fastbin_top_chunk != 0:
try:
fastbin_top_chunk = read_chunk(fastbin_top_chunk)
except gdb.MemoryError as e:
except gdb.MemoryError:
print(
message.error(
f"Can't read top fastbin chunk at address 0x{fastbin_top_chunk:x}, memory error"
@ -1323,7 +1323,7 @@ def try_free(addr) -> None:
try:
next_chunk = read_chunk(next_chunk_addr)
next_chunk_size = chunksize(unsigned_size(next_chunk["size"]))
except (OverflowError, gdb.MemoryError) as e:
except (OverflowError, gdb.MemoryError):
print(message.error(f"Can't read next chunk at address 0x{next_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1353,7 +1353,7 @@ def try_free(addr) -> None:
try:
prev_chunk = read_chunk(prev_chunk_addr)
prev_chunk_size = chunksize(unsigned_size(prev_chunk["size"]))
except (OverflowError, gdb.MemoryError) as e:
except (OverflowError, gdb.MemoryError):
print(message.error(f"Can't read next chunk at address 0x{prev_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1376,7 +1376,7 @@ def try_free(addr) -> None:
try:
next_next_chunk_addr = next_chunk_addr + next_chunk_size
next_next_chunk = read_chunk(next_next_chunk_addr)
except (OverflowError, gdb.MemoryError) as e:
except (OverflowError, gdb.MemoryError):
print(message.error(f"Can't read next chunk at address 0x{next_next_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1405,14 +1405,14 @@ def try_free(addr) -> None:
)
print(message.error(err))
errors_found += 1
except (OverflowError, gdb.MemoryError) as e:
except (OverflowError, gdb.MemoryError):
print(
message.error(
f"Can't read chunk at 0x{unsorted['fd']:x}, it is unsorted bin fd"
)
)
errors_found += 1
except (OverflowError, gdb.MemoryError) as e:
except (OverflowError, gdb.MemoryError):
print(message.error(f"Can't read unsorted bin chunk at 0x{unsorted_addr:x}"))
errors_found += 1

@ -118,8 +118,6 @@ def kchecksec() -> None:
)
return
cmdline = pwndbg.gdblib.kernel.kcmdline()
options = _hardening_options + _arch_hardening_options.get(pwndbg.gdblib.arch.name, [])
for opt in options:
config_name = opt.name

@ -60,7 +60,7 @@ def killthreads(thread_ids: list[int] | None = None, all: bool = False) -> None:
gdb.execute(f"thread {thread_id}", to_string=True)
try:
gdb.execute("call (void) pthread_exit(0)", to_string=True)
except gdb.error as e:
except gdb.error:
# gdb will throw an error, because the thread dies during the call, which is expected
pass

@ -114,7 +114,6 @@ def pwndbg_(filter_pattern, shell, all_, category_, list_categories) -> None:
filter_pattern, pwndbg_cmds, shell_cmds
):
alias_str = ""
aliases_len = 0
if aliases:
aliases = map(C.blue, aliases)
alias_str = f" [{', '.join(aliases)}]"

@ -36,13 +36,13 @@ def xuntil(target) -> None:
except (TypeError, ValueError):
# The following gdb command will throw an error if the symbol is not defined.
try:
result = gdb.execute(f"info address {target}", to_string=True, from_tty=False)
gdb.execute(f"info address {target}", to_string=True, from_tty=False)
except gdb.error:
print(message.error(f"Unable to resolve {target}"))
return
spec = target
b = gdb.Breakpoint(spec, temporary=True)
gdb.Breakpoint(spec, temporary=True)
if pwndbg.gdblib.proc.alive:
gdb.execute("continue", from_tty=False)
else:

@ -33,6 +33,6 @@ def ropper(argument) -> None:
cmd += argument
try:
io = subprocess.call(cmd)
subprocess.call(cmd)
except Exception:
print("Could not run ropper. Please ensure it's installed and in $PATH.")

@ -70,7 +70,7 @@ def start(args=None) -> None:
if not address:
continue
b = gdb.Breakpoint(symbol, temporary=True)
gdb.Breakpoint(symbol, temporary=True)
gdb.execute(run, from_tty=False, to_string=True)
return

@ -32,7 +32,6 @@ def valist(addr: int, count: int) -> None:
reg_save_area = pwndbg.gdblib.memory.u64(addr + 16)
indent = " " * len("gp_offset => ")
heading = C.blue("reg_save_area".ljust(len(indent) - 1))
print(f"{C.blue('reg_save_area')}")
for i in range(6):
line = ""

@ -91,7 +91,7 @@ def get_disassembler_cached(arch, ptrsize: int, endian, extra=None):
cs = Cs(arch, mode)
try:
cs.syntax = CapstoneSyntax[flavor]
except CsError as ex:
except CsError:
pass
cs.detail = True
return cs

@ -11,7 +11,6 @@ import pwndbg.gdblib.regs
class DisassemblyAssistant(pwndbg.disasm.arch.DisassemblyAssistant):
def memory_sz(self, instruction, op) -> str:
segment = ""
parts = []
if op.mem.base != 0:

@ -27,8 +27,7 @@ class DisassemblyAssistant(pwndbg.disasm.arch.DisassemblyAssistant):
return None
def memory(self, instruction, op):
current = instruction.address == pwndbg.gdblib.regs.pc
# current = instruction.address == pwndbg.gdblib.regs.pc
# The only register we can reason about if it's *not* the current
# instruction is $rip. For example:
# lea rdi, [rip - 0x1f6]
@ -62,7 +61,7 @@ class DisassemblyAssistant(pwndbg.disasm.arch.DisassemblyAssistant):
def memory_sz(self, instruction, op):
arith = False
segment = op.mem.segment
disp = op.value.mem.disp
# disp = op.value.mem.disp
base = op.value.mem.base
index = op.value.mem.index
scale = op.value.mem.scale
@ -133,7 +132,7 @@ class DisassemblyAssistant(pwndbg.disasm.arch.DisassemblyAssistant):
cf = efl & (1 << 0)
pf = efl & (1 << 2)
af = efl & (1 << 4)
# af = efl & (1 << 4)
zf = efl & (1 << 6)
sf = efl & (1 << 7)
of = efl & (1 << 11)

@ -438,7 +438,7 @@ class Emulator:
try:
self.single_step_hook_hit_count = 0
self.emulate_with_hook(self.single_step_hook_code, count=1)
except U.unicorn.UcError as e:
except U.unicorn.UcError:
self._single_step = (None, None)
return self._single_step

@ -17,7 +17,6 @@ import pwndbg.gdblib.arch
import pwndbg.gdblib.config
import pwndbg.gdblib.memory
import pwndbg.gdblib.strings
import pwndbg.gdblib.symbol
import pwndbg.gdblib.typeinfo
import pwndbg.lib.cache
from pwndbg import color
@ -61,7 +60,6 @@ def enhance(value: int, code: bool = True, safe_linking: bool = False) -> str:
"""
value = int(value)
name = pwndbg.gdblib.symbol.get(value) or None
page = pwndbg.gdblib.vmmap.find(value)
# If it's not in a page we know about, try to dereference

@ -30,7 +30,6 @@ def get_arrsize(f: gdb.Value) -> int:
if t.code != gdb.TYPE_CODE_ARRAY:
return 0
t2 = t.target()
s = t2.sizeof
return int(t.sizeof / t2.sizeof)

@ -175,7 +175,6 @@ def link_map_head():
r_debug = CStruct.r_debug()
r_version = r_debug.read(r_debug_address, "r_version")
r_map = r_debug.read(r_debug_address, "r_map")
if r_map != 0:

@ -415,7 +415,7 @@ def map_inner(ei_class, ehdr, objfile: str) -> Tuple[pwndbg.lib.memory.Page, ...
vaddr = int(phdr.p_vaddr)
offset = int(phdr.p_offset)
flags = int(phdr.p_flags)
ptype = int(phdr.p_type)
# ptype = int(phdr.p_type)
memsz += pwndbg.lib.memory.page_offset(vaddr)
memsz = pwndbg.lib.memory.page_size_align(memsz)

@ -193,12 +193,10 @@ class TrapAllocator:
while len(self.blocks) > 0:
block = self.blocks.pop()
result = pwndbg.gdblib.shellcode.exec_syscall(
"SYS_munmap", block, self.block_capacity * self.slot_size, disable_breakpoints=True
"SYS_munmap", block, size, disable_breakpoints=True
)
if result != 0:
raise RuntimeError(
f"SYS_munmap({block:#x}, {self.block_capacity * self.slot_size:#x}) failed ({result:#x})"
)
raise RuntimeError(f"SYS_munmap({block:#x}, {size:#x}) failed ({result:#x})")
self._reset()

@ -298,7 +298,6 @@ class Tracker:
continue
# Check if the chunk is free.
found = False
for b in bins_list:
if b.contains_chunk(ch.real_size, ch.address):
# The chunk is free. Add it to the free list and install
@ -310,9 +309,8 @@ class Tracker:
self.free_watchpoints[ch.address] = wp
# Move on to the next chunk.
found = True
break
except IndexError as e:
except IndexError:
import traceback
traceback.print_exc()
@ -374,7 +372,7 @@ def get_chunk(address, requested_size):
# so, we separate them here.
FLAGS_BITMASK = 7
flags = size & 7
flags = size & FLAGS_BITMASK
size ^= flags
return Chunk(address, size, requested_size, flags)

@ -246,7 +246,7 @@ def break_on_program_code() -> bool:
if proc.stopped_with_signal:
return False
o = gdb.execute("si", from_tty=False, to_string=True)
gdb.execute("si", from_tty=False, to_string=True)
for start, end in binary_exec_page_ranges:
if start <= regs.pc < end:

@ -319,7 +319,7 @@ def coredump_maps() -> Tuple[pwndbg.lib.memory.Page, ...]:
if "AT_EXECFN" in line:
try:
stack_addr = int(line.split()[-2], 16)
except Exception as e:
except Exception:
pass
break

@ -1394,7 +1394,7 @@ class DebugSymsHeap(GlibcMemoryAllocator):
try:
self._thread_cache = pwndbg.gdblib.memory.poi(self.tcache_perthread_struct, tcache)
self._thread_cache["entries"].fetch_lazy()
except Exception as e:
except Exception:
print(
message.error(
"Error fetching tcache. GDB cannot access "

@ -490,10 +490,8 @@ idc = IDC()
def print_member(sid, offset) -> None:
mid = GetMemberId(sid, offset)
mname = GetMemberName(sid, offset) or "(no name)"
msize = GetMemberSize(sid, offset) or 0
mflag = GetMemberFlag(sid, offset) or 0
print(f" +{offset:#x} - {mname} [{msize:#x} bytes]")

@ -39,7 +39,6 @@ def _which_binutils(util: str, arch: Arch, **kwargs: Any) -> str | None:
###############################
arch_name = arch.name
bits = arch.ptrsize
# Fix up binjitsu vs Debian triplet naming, and account
# for 'thumb' being its own binjitsu architecture.

@ -13,7 +13,6 @@ ignore = [
"F405",
"F811",
"F821",
"F841",
"W505",
]

@ -26,7 +26,6 @@ def test_vis_heap_chunk_command(start_binary):
# We will use `heap_addr` variable to fill in proper addresses below
heap_addr = heap_page.start
heap_end = heap_page.end
# We sometimes need that value, so let's cache it
dq2 = None
@ -174,10 +173,6 @@ def test_vis_heap_chunk_command(start_binary):
heap_addr = heap_page.start
# This is not ideal, but hopefully it works on different builds // feel free to name it better
some_addr = heap_addr + 0x2C0
some_addr_hexdump = hexdump_16B(hex(heap_addr + 0x90))
expected_all3 = [""]
# Add the biggest chunk, the one from libc

@ -63,7 +63,6 @@ def test_command_killthreads_produces_error_when_unknown_thread_passed(start_bin
gdb.execute("break break_here")
gdb.execute("run")
initial_thread_count = len(gdb.selected_inferior().threads())
# check if thread with id 3 exists
assert len([thread for thread in gdb.selected_inferior().threads() if thread.num == 3]) == 1

@ -14,7 +14,6 @@ def test_mmap_executes_properly(start_binary):
"""
start_binary(USE_FDS_BINARY)
pc = pwndbg.gdblib.regs.pc
page_size = pwndbg.lib.memory.PAGE_SIZE
# Checks for an mmap(2) error.

@ -11,11 +11,13 @@ def test_command_kbase():
def test_command_kchecksec():
res = gdb.execute("kchecksec", to_string=True)
assert res is not None # for F841 warning
# TODO: do something with res
def test_command_kcmdline():
res = gdb.execute("kcmdline", to_string=True)
assert res is not None # for F841 warning
# TODO: do something with res

Loading…
Cancel
Save