Convert format strings to f-strings (#1738)

This commit is contained in:
Gulshan Singh 2023-05-24 04:33:24 -07:00 committed by GitHub
parent 6e0d159273
commit a3b66dae5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 54 additions and 102 deletions

View File

@ -88,11 +88,7 @@ encoding = locale.getpreferredencoding()
if encoding != "UTF-8":
print("******")
print(
"Your encoding ({}) is different than UTF-8. pwndbg might not work properly.".format(
encoding
)
)
print(f"Your encoding ({encoding}) is different than UTF-8. pwndbg might not work properly.")
print("You might try launching GDB with:")
print(" LC_CTYPE=C.UTF-8 gdb")
print(

View File

@ -75,9 +75,7 @@ def wrap(f):
idaapi.execute_sync(work, flags)
if error:
msg = "Failed on calling {}.{} with args: {}, kwargs: {}\nException: {}".format(
f.__module__, f.__name__, a, kw, str(error[0])
)
msg = f"Failed on calling {f.__module__}.{f.__name__} with args: {a}, kwargs: {kw}\nException: {str(error[0])}"
print("[!!!] ERROR:", msg)
raise error[0]

View File

@ -112,7 +112,7 @@ def use_info_auxv():
for line in lines:
match = re.match("([0-9]+) .*? (0x[0-9a-f]+|[0-9]+$)", line)
if not match:
print("Warning: Skipping auxv entry '{}'".format(line))
print(f"Warning: Skipping auxv entry '{line}'")
continue
const, value = int(match.group(1)), int(match.group(2), 0)

View File

@ -20,9 +20,7 @@ def dumpargs(force=False) -> None:
else:
print("Couldn't resolve call arguments from registers.")
print(
"Detected ABI: {} ({} bit) either doesn't pass arguments through registers or is not implemented. Maybe they are passed on the stack?".format(
pwndbg.gdblib.arch.current, pwndbg.gdblib.arch.ptrsize * 8
)
f"Detected ABI: {pwndbg.gdblib.arch.current} ({pwndbg.gdblib.arch.ptrsize * 8} bit) either doesn't pass arguments through registers or is not implemented. Maybe they are passed on the stack?"
)

View File

@ -380,7 +380,7 @@ def malloc_chunk(addr, fake=False, verbose=False, simple=False) -> None:
headers_to_print = [] # both state (free/allocated) and flags
fields_to_print = set() # in addition to addr and size
out_fields = "Addr: {}\n".format(M.get(chunk.address))
out_fields = f"Addr: {M.get(chunk.address)}\n"
if fake:
headers_to_print.append(message.on("Fake chunk"))
@ -413,7 +413,7 @@ def malloc_chunk(addr, fake=False, verbose=False, simple=False) -> None:
for bins in bins_list:
if bins.contains_chunk(chunk.real_size, chunk.address):
no_match = False
headers_to_print.append(message.on("Free chunk ({})".format(bins.bin_type)))
headers_to_print.append(message.on(f"Free chunk ({bins.bin_type})"))
if not verbose:
fields_to_print.update(bins.bin_type.valid_fields())
if no_match:
@ -422,7 +422,7 @@ def malloc_chunk(addr, fake=False, verbose=False, simple=False) -> None:
if verbose:
fields_to_print.update(["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"])
else:
out_fields += "Size: 0x{:02x}\n".format(chunk.size)
out_fields += f"Size: 0x{chunk.size:02x}\n"
prev_inuse, is_mmapped, non_main_arena = allocator.chunk_flags(chunk.size)
if prev_inuse:
@ -435,8 +435,8 @@ def malloc_chunk(addr, fake=False, verbose=False, simple=False) -> None:
fields_ordered = ["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"]
for field_to_print in fields_ordered:
if field_to_print in fields_to_print:
out_fields += message.system(field_to_print) + ": 0x{:02x}\n".format(
getattr(chunk, field_to_print)
out_fields += (
message.system(field_to_print) + f": 0x{getattr(chunk, field_to_print):02x}\n"
)
print(" | ".join(headers_to_print) + "\n" + out_fields)
@ -945,7 +945,7 @@ def vis_heap_chunks(
data = pwndbg.gdblib.memory.read(cursor, ptr_size)
cell = pwndbg.gdblib.arch.unpack(data)
cell_hex = "\t0x{:0{n}x}".format(cell, n=ptr_size * 2)
cell_hex = f"\t0x{cell:0{ptr_size * 2}x}"
out += color_func(cell_hex)
printed += 1
@ -996,13 +996,11 @@ def bin_labels_mapping(collections):
b = bins.bins[size]
if isinstance(size, int):
size = hex(size)
count = "/{:d}".format(b.count) if bins_type == BinType.TCACHE else None
count = f"/{b.count:d}" if bins_type == BinType.TCACHE else None
chunks = b.fd_chain
for chunk_addr in chunks:
labels_mapping.setdefault(chunk_addr, []).append(
"{:s}[{:s}][{:d}{}]".format(
bins_type, size, chunks.index(chunk_addr), count or ""
)
f"{bins_type:s}[{size:s}][{chunks.index(chunk_addr):d}{count or ''}]"
)
return labels_mapping
@ -1075,7 +1073,7 @@ def try_free(addr) -> None:
try:
chunk = read_chunk(addr)
except gdb.MemoryError as e:
print(message.error("Can't read chunk at address 0x{:x}, memory error".format(addr)))
print(message.error(f"Can't read chunk at address 0x{addr:x}, memory error"))
return
chunk_size = unsigned_size(chunk["size"])
@ -1108,7 +1106,7 @@ def try_free(addr) -> None:
err = "free(): invalid pointer -> misaligned chunk\n"
err += " LSB of 0x{:x} are 0b{}, should be 0b{}"
if addr_tmp != addr:
err += " (0x{:x} was added to the address)".format(2 * size_sz)
err += f" (0x{2 * size_sz:x} was added to the address)"
err = err.format(addr_tmp, bin(addr_tmp)[-aligned_lsb:], "0" * aligned_lsb)
print(message.error(err))
errors_found += 1
@ -1173,9 +1171,7 @@ def try_free(addr) -> None:
except gdb.MemoryError as e:
print(
message.error(
"Can't read next chunk at address 0x{:x}, memory error".format(
chunk + chunk_size_unmasked
)
f"Can't read next chunk at address 0x{chunk + chunk_size_unmasked:x}, memory error"
)
)
finalize(errors_found, returned_before_error)
@ -1206,9 +1202,7 @@ def try_free(addr) -> None:
except gdb.MemoryError as e:
print(
message.error(
"Can't read top fastbin chunk at address 0x{:x}, memory error".format(
fastbin_top_chunk
)
f"Can't read top fastbin chunk at address 0x{fastbin_top_chunk:x}, memory error"
)
)
finalize(errors_found, returned_before_error)
@ -1262,7 +1256,7 @@ def try_free(addr) -> None:
next_chunk = read_chunk(next_chunk_addr)
next_chunk_size = chunksize(unsigned_size(next_chunk["size"]))
except (OverflowError, gdb.MemoryError) as e:
print(message.error("Can't read next chunk at address 0x{:x}".format(next_chunk_addr)))
print(message.error(f"Can't read next chunk at address 0x{next_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1292,9 +1286,7 @@ def try_free(addr) -> None:
prev_chunk = read_chunk(prev_chunk_addr)
prev_chunk_size = chunksize(unsigned_size(prev_chunk["size"]))
except (OverflowError, gdb.MemoryError) as e:
print(
message.error("Can't read next chunk at address 0x{:x}".format(prev_chunk_addr))
)
print(message.error(f"Can't read next chunk at address 0x{prev_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1317,11 +1309,7 @@ def try_free(addr) -> None:
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:
print(
message.error(
"Can't read next chunk at address 0x{:x}".format(next_next_chunk_addr)
)
)
print(message.error(f"Can't read next chunk at address 0x{next_next_chunk_addr:x}"))
finalize(errors_found, returned_before_error)
return
@ -1352,16 +1340,12 @@ def try_free(addr) -> None:
except (OverflowError, gdb.MemoryError) as e:
print(
message.error(
"Can't read chunk at 0x{:x}, it is unsorted bin fd".format(
unsorted["fd"]
)
f"Can't read chunk at 0x{unsorted['fd']:x}, it is unsorted bin fd"
)
)
errors_found += 1
except (OverflowError, gdb.MemoryError) as e:
print(
message.error("Can't read unsorted bin chunk at 0x{:x}".format(unsorted_addr))
)
print(message.error(f"Can't read unsorted bin chunk at 0x{unsorted_addr:x}"))
errors_found += 1
else:

View File

@ -151,7 +151,7 @@ def search(type, hex, executable, writable, value, mapping_name, save, next, tru
try:
value = codecs.decode(value, "hex")
except binascii.Error as e:
print("invalid input for type hex: {}".format(e))
print(f"invalid input for type hex: {e}")
return
# Convert to an integer if needed, and pack to bytes
@ -169,7 +169,7 @@ def search(type, hex, executable, writable, value, mapping_name, save, next, tru
try:
value = struct.pack(fmt, value)
except struct.error as e:
print("invalid input for type {}: {}".format(type, e))
print(f"invalid input for type {type}: {e}")
return
# Null-terminate strings

View File

@ -75,7 +75,7 @@ def register_shell_function(cmd, deprecated=False) -> None:
f"This command is deprecated in Pwndbg. Please use the GDB's built-in syntax for running shell commands instead: !{cmd} <args>"
)
doc = "Invokes `{}` shell command".format(cmd)
doc = f"Invokes `{cmd}` shell command"
if deprecated:
doc += " (deprecated)"

View File

@ -36,15 +36,7 @@ def print_vmmap_table_header() -> None:
Prints the table header for the vmmap command.
"""
print(
"{start:>{width}} {end:>{width}} {permstr} {size:>8} {offset:>6} {objfile}".format(
start="Start",
end="End",
permstr="Perm",
size="Size",
offset="Offset",
objfile="File",
width=2 + 2 * pwndbg.gdblib.arch.ptrsize,
)
f"{'Start':>{2 + 2 * pwndbg.gdblib.arch.ptrsize}} {'End':>{2 + 2 * pwndbg.gdblib.arch.ptrsize}} {'Perm'} {'Size':>8} {'Offset':>6} {'File'}"
)

View File

@ -20,13 +20,7 @@ parser.add_argument("address", nargs="?", default="$pc", help="Address to inspec
def print_line(name, addr, first, second, op, width=20) -> None:
print(
"{} {} = {} {} {:#x}".format(
name.rjust(width),
M.get(addr),
M.get(first) if not isinstance(first, str) else first.ljust(len(hex(addr).rstrip("L"))),
op,
second,
)
f"{name.rjust(width)} {M.get(addr)} = {M.get(first) if not isinstance(first, str) else first.ljust(len(hex(addr).rstrip('L')))} {op} {second:#x}"
)
@ -90,7 +84,7 @@ def xinfo_mmap_file(page, addr) -> None:
print_line("File (Disk)", addr, file_name, file_offset, "+")
break
else:
print("{} {} = [not file backed]".format("File (Disk)".rjust(20), M.get(addr)))
print(f"{'File (Disk)'.rjust(20)} {M.get(addr)} = [not file backed]")
containing_sections = pwndbg.gdblib.elf.get_containing_sections(file_name, first.vaddr, addr)
if len(containing_sections) > 0:
@ -116,10 +110,10 @@ def xinfo(address=None) -> None:
page = pwndbg.gdblib.vmmap.find(addr)
if page is None:
print("\n Virtual address {:#x} is not mapped.".format(addr))
print(f"\n Virtual address {addr:#x} is not mapped.")
return
print("Extended information for virtual address {}:".format(M.get(addr)))
print(f"Extended information for virtual address {M.get(addr)}:")
print("\n Containing mapping:")
print(M.get(address, text=str(page)))

View File

@ -154,4 +154,4 @@ def enhance(value: int, code: bool = True, safe_linking: bool = False) -> str:
if len(retval) == 1:
return retval[0]
return retval[0] + E.comment(color.strip(" /* {} */".format("; ".join(retval[1:]))))
return retval[0] + E.comment(color.strip(f" /* {'; '.join(retval[1:])} */"))

View File

@ -86,7 +86,7 @@ def handle(name="Error"):
else:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(message.error("Exception occurred: {}: {} ({})".format(name, exc_value, exc_type)))
print(message.error(f"Exception occurred: {name}: {exc_value} ({exc_type})"))
inform_verbose_and_debug()

View File

@ -42,7 +42,7 @@ def decompile(func=None):
src = r2.cmdj("pdgj @" + func)
if not src:
raise Exception("Decompile command failed, check if '{}' is a valid target".format(func))
raise Exception(f"Decompile command failed, check if '{func}' is a valid target")
current_line_marker = "/*%%PWNDBG_CODE_MARKER%%*/"
source = src.get("code", "")

View File

@ -63,7 +63,7 @@ def init_ida_rpc_client() -> None:
if _ida is None and (now - _ida_last_connection_check) < int(ida_timeout) + 5:
return
addr = "http://{host}:{port}".format(host=ida_rpc_host, port=ida_rpc_port)
addr = f"http://{ida_rpc_host}:{ida_rpc_port}"
_ida = xmlrpc.client.ServerProxy(addr)
socket.setdefaulttimeout(int(ida_timeout))
@ -98,9 +98,7 @@ def init_ida_rpc_client() -> None:
exc_type, exc_value, _ = exception
print(
message.error(
"Failed to connect to IDA Pro ({}: {})".format(
exc_type.__qualname__, exc_value
)
f"Failed to connect to IDA Pro ({exc_type.__qualname__}: {exc_value})"
)
)
if exc_type is socket.timeout:

View File

@ -129,15 +129,7 @@ class Page:
)
def __str__(self) -> str:
return "{start:#{width}x} {end:#{width}x} {permstr} {size:8x} {offset:6x} {objfile}".format(
start=self.vaddr,
end=self.vaddr + self.memsz,
permstr=self.permstr,
size=self.memsz,
offset=self.offset,
objfile=self.objfile or "",
width=2 + 2 * pwndbg.gdblib.arch.ptrsize,
)
return f"{self.vaddr:#{2 + 2 * pwndbg.gdblib.arch.ptrsize}x} {self.vaddr + self.memsz:#{2 + 2 * pwndbg.gdblib.arch.ptrsize}x} {self.permstr} {self.memsz:8x} {self.offset:6x} {self.objfile or ''}"
def __repr__(self) -> str:
return "%s(%r)" % (self.__class__.__name__, self.__str__())

View File

@ -60,7 +60,7 @@ def banner(title, target=sys.stdin, width=None, extra=""):
def addrsz(address) -> str:
address = int(address) & pwndbg.gdblib.arch.ptrmask
return "%#{}x".format(2 * pwndbg.gdblib.arch.ptrsize) % address
return f"%#{2 * pwndbg.gdblib.arch.ptrsize}x" % address
def get_window_size(target=sys.stdin):

View File

@ -37,7 +37,7 @@ def binary_parse_breakpoints(binary_code):
line = lines[line_no]
line_no += 1
for bug_id, func_name in func_names.items():
if "void {}".format(func_name) in line:
if f"void {func_name}" in line:
# find break1 and break2 inside function
b1, b2 = None, None
@ -74,7 +74,7 @@ def setup_heap(start_binary, bug_no):
except FileNotFoundError:
pass
start_binary(HEAP_BINARY, str(bug_no), "> {}".format(OUTPUT_FILE))
start_binary(HEAP_BINARY, str(bug_no), f"> {OUTPUT_FILE}")
gdb.execute("break " + str(breakpoints[bug_no][0]))
gdb.execute("break " + str(breakpoints[bug_no][1]))
@ -94,7 +94,7 @@ def setup_heap(start_binary, bug_no):
def test_try_free_invalid_overflow(start_binary):
chunks = setup_heap(start_binary, 1)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "free(): invalid pointer -> &chunk + chunk->size > max memory" in result
os.remove(OUTPUT_FILE)
@ -102,7 +102,7 @@ def test_try_free_invalid_overflow(start_binary):
def test_try_free_invalid_misaligned(start_binary):
chunks = setup_heap(start_binary, 2)
result = gdb.execute("try_free {}".format(hex(chunks["a"] + 2)), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'] + 2)}", to_string=True)
assert "free(): invalid pointer -> misaligned chunk" in result
os.remove(OUTPUT_FILE)
@ -110,7 +110,7 @@ def test_try_free_invalid_misaligned(start_binary):
def test_try_free_invalid_size_minsize(start_binary):
chunks = setup_heap(start_binary, 3)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "free(): invalid size -> chunk's size smaller than MINSIZE" in result
os.remove(OUTPUT_FILE)
@ -118,7 +118,7 @@ def test_try_free_invalid_size_minsize(start_binary):
def test_try_free_invalid_size_misaligned(start_binary):
chunks = setup_heap(start_binary, 4)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "free(): invalid size -> chunk's size is not aligned" in result
os.remove(OUTPUT_FILE)
@ -126,7 +126,7 @@ def test_try_free_invalid_size_misaligned(start_binary):
def test_try_free_double_free_tcache(start_binary):
chunks = setup_heap(start_binary, 5)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "Will do checks for tcache double-free" in result
os.remove(OUTPUT_FILE)
@ -134,7 +134,7 @@ def test_try_free_double_free_tcache(start_binary):
def test_try_free_invalid_next_size_fast(start_binary):
chunks = setup_heap(start_binary, 6)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "free(): invalid next size (fast)" in result
os.remove(OUTPUT_FILE)
@ -142,7 +142,7 @@ def test_try_free_invalid_next_size_fast(start_binary):
def test_try_free_double_free(start_binary):
chunks = setup_heap(start_binary, 7)
result = gdb.execute("try_free {}".format(hex(chunks["a"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['a'])}", to_string=True)
assert "double free or corruption (fasttop)" in result
os.remove(OUTPUT_FILE)
@ -150,7 +150,7 @@ def test_try_free_double_free(start_binary):
def test_try_free_invalid_fastbin_entry(start_binary):
chunks = setup_heap(start_binary, 8)
result = gdb.execute("try_free {}".format(hex(chunks["c"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['c'])}", to_string=True)
assert "invalid fastbin entry (free)" in result
os.remove(OUTPUT_FILE)
@ -163,7 +163,7 @@ def test_try_free_double_free_or_corruption_top(start_binary):
arena = allocator.thread_arena or allocator.main_arena
top_chunk = arena.top + (2 * ptr_size)
result = gdb.execute("try_free {}".format(hex(top_chunk)), to_string=True)
result = gdb.execute(f"try_free {hex(top_chunk)}", to_string=True)
assert "double free or corruption (top)" in result
os.remove(OUTPUT_FILE)
@ -171,7 +171,7 @@ def test_try_free_double_free_or_corruption_top(start_binary):
def test_try_free_double_free_or_corruption_out(start_binary):
chunks = setup_heap(start_binary, 10)
result = gdb.execute("try_free {}".format(hex(chunks["d"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['d'])}", to_string=True)
assert "double free or corruption (out)" in result
os.remove(OUTPUT_FILE)
@ -179,7 +179,7 @@ def test_try_free_double_free_or_corruption_out(start_binary):
def test_try_free_double_free_or_corruption_prev(start_binary):
chunks = setup_heap(start_binary, 11)
result = gdb.execute("try_free {}".format(hex(chunks["d"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['d'])}", to_string=True)
assert "double free or corruption (!prev)" in result
os.remove(OUTPUT_FILE)
@ -187,7 +187,7 @@ def test_try_free_double_free_or_corruption_prev(start_binary):
def test_try_free_invalid_next_size_normal(start_binary):
chunks = setup_heap(start_binary, 12)
result = gdb.execute("try_free {}".format(hex(chunks["d"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['d'])}", to_string=True)
assert "free(): invalid next size (normal)" in result
os.remove(OUTPUT_FILE)
@ -195,7 +195,7 @@ def test_try_free_invalid_next_size_normal(start_binary):
def test_try_free_corrupted_consolidate_backward(start_binary):
chunks = setup_heap(start_binary, 13)
result = gdb.execute("try_free {}".format(hex(chunks["e"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['e'])}", to_string=True)
assert "corrupted size vs. prev_size while consolidating" in result
os.remove(OUTPUT_FILE)
@ -203,7 +203,7 @@ def test_try_free_corrupted_consolidate_backward(start_binary):
def test_try_free_corrupted_consolidate_backward(start_binary):
chunks = setup_heap(start_binary, 13)
result = gdb.execute("try_free {}".format(hex(chunks["e"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['e'])}", to_string=True)
assert "corrupted size vs. prev_size while consolidating" in result
os.remove(OUTPUT_FILE)
@ -214,6 +214,6 @@ def test_try_free_corrupted_consolidate_backward(start_binary):
def test_try_free_corrupted_unsorted_chunks(start_binary):
chunks = setup_heap(start_binary, 14)
result = gdb.execute("try_free {}".format(hex(chunks["f"])), to_string=True)
result = gdb.execute(f"try_free {hex(chunks['f'])}", to_string=True)
assert "free(): corrupted unsorted chunks" in result
os.remove(OUTPUT_FILE)

View File

@ -58,7 +58,7 @@ def test_command_telescope_n_records(start_binary):
n = 3
gdb.execute("entry")
result = gdb.execute("telescope $rsp {}".format(n), to_string=True).strip().splitlines()
result = gdb.execute(f"telescope $rsp {n}", to_string=True).strip().splitlines()
assert len(result) == n