Skip to content

Commit

Permalink
Remove more python2-specific stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Grazfather committed Jun 24, 2021
1 parent 4661f81 commit 5df3002
Showing 1 changed file with 21 additions and 27 deletions.
48 changes: 21 additions & 27 deletions gef.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
#
#

from __future__ import print_function, division, absolute_import

import abc
import argparse
Expand Down Expand Up @@ -757,7 +756,7 @@ def __init__(self, addr, name=None):
finally:
self.top = int(self.top)
self.last_remainder = int(self.last_remainder)
self.n = int(self.next)
self.n = int(self.__next__)
self.nfree = int(self.next_free)
self.sysmem = int(self.system_mem)
return
Expand Down Expand Up @@ -785,7 +784,7 @@ def bin(self, i):
return fd, bw

def get_next(self):
addr_next = int(self.next)
addr_next = int(self.__next__)
arena_main = GlibcArena(self.__name)
if addr_next == arena_main.__addr:
return None
Expand Down Expand Up @@ -1077,7 +1076,7 @@ def _show_code_line(fname, idx):
def gef_pystring(x):
"""Returns a sanitized version as string of the bytes list given in input."""
res = str(x, encoding="utf-8")
substs = [("\n","\\n"), ("\r","\\r"), ("\t","\\t"), ("\v","\\v"), ("\b","\\b"), ]
substs = [("\n", "\\n"), ("\r", "\\r"), ("\t", "\\t"), ("\v", "\\v"), ("\b", "\\b"), ]
for x, y in substs: res = res.replace(x, y)
return res

Expand Down Expand Up @@ -1558,9 +1557,8 @@ def flags_to_human(reg_value, value_table):
return "[{}]".format(" ".join(flags))


class Architecture:
class Architecture(metaclass=abc.ABCMeta):
"""Generic metaclass for the architecture supported by GEF."""
__metaclass__ = abc.ABCMeta

@abc.abstractproperty
def all_registers(self): pass
Expand Down Expand Up @@ -2477,7 +2475,7 @@ def read_cstring_from_memory(address, max_length=GEF_MAX_STRING_LENGTH, encoding
res = bytes(read_memory(address, length)).decode("utf-8")

res = res.split("\x00", 1)[0]
ustr = res.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t")
ustr = res.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
if max_length and len(res) > max_length:
return "{}[...]".format(ustr[:max_length])

Expand Down Expand Up @@ -4163,11 +4161,9 @@ def register_function(cls):
return cls


class GenericCommand(gdb.Command):
class GenericCommand(gdb.Command, metaclass=abc.ABCMeta):
"""This is an abstract class for invoking commands, should not be instantiated."""

__metaclass__ = abc.ABCMeta

def __init__(self, *args, **kwargs):
self.pre_load()
syntax = Color.yellowify("\nSyntax: ") + self._syntax_
Expand Down Expand Up @@ -4630,7 +4626,7 @@ def comp2_b(x): return "{:b}".format((x + (1 << off)) % (1 << off))

try:
res = eval(" ".join(parsed_expr))
if type(res) is int:
if isinstance(res, int):
show_as_int(res)
else:
gef_print("{}".format(res))
Expand Down Expand Up @@ -4853,7 +4849,7 @@ def __init__(self, *args, **kwargs):
self.add_setting("dereference_string", "yellow", "Color of dereferenced string")
self.add_setting("dereference_code", "gray", "Color of dereferenced code")
self.add_setting("dereference_base_address", "cyan", "Color of dereferenced address")
self.add_setting("dereference_register_value", "bold blue" , "Color of dereferenced register")
self.add_setting("dereference_register_value", "bold blue", "Color of dereferenced register")
self.add_setting("registers_register_name", "blue", "Color of the register name in the register window")
self.add_setting("registers_value_changed", "bold red", "Color of the changed register in the register window")
self.add_setting("address_stack", "pink", "Color to use when a stack address is found")
Expand Down Expand Up @@ -5077,10 +5073,10 @@ def load_module(self, file_path):
return module

def enumerate_structures_from_module(self, module):
_invalid = set(["BigEndianStructure", "LittleEndianStructure", "Structure"])
_structs = set([x for x in dir(module) \
_invalid = {"BigEndianStructure", "LittleEndianStructure", "Structure"}
_structs = {x for x in dir(module) \
if inspect.isclass(getattr(module, x)) \
and issubclass(getattr(module, x), ctypes.Structure)])
and issubclass(getattr(module, x), ctypes.Structure)}
return _structs - _invalid


Expand Down Expand Up @@ -5519,7 +5515,7 @@ def import_structures(self, structs):
m = ' (\"{}\", {}),\n'.format(name, csize)
f.write(m)
f.write("]\n")
ok("Success, {:d} structure{:s} imported".format(len(structs),"s" if len(structs)>1 else ""))
ok("Success, {:d} structure{:s} imported".format(len(structs), "s" if len(structs)>1 else ""))
return


Expand Down Expand Up @@ -5937,7 +5933,6 @@ def set_fs(uc, addr): return set_msr(uc, FSMSR, addr)
#
# @_hugsy_
#
from __future__ import print_function
import collections
import capstone, unicorn
Expand Down Expand Up @@ -7234,7 +7229,7 @@ def do_invoke(self, argv):
ropper = sys.modules["ropper"]
if "--file" not in argv:
path = get_filepath()
sect = next(filter(lambda x: x.path == path, get_process_maps()))
sect = next([x for x in get_process_maps() if x.path == path])
argv.append("--file")
argv.append(path)
argv.append("-I")
Expand Down Expand Up @@ -7322,7 +7317,7 @@ def do_invoke(self, argv, *args, **kwargs):
# this is fire a ValueError if the arch/mode/endianess are invalid
arch, mode = get_keystone_arch(arch=arch_s.upper(), mode=mode_s.upper(), endian=endian_s.upper())
insns = [x.strip() for x in " ".join(args.instructions).split(";") if x]
info("Assembling {} instruction(s) for {}:{}".format(len(insns),arch_s, mode_s))
info("Assembling {} instruction(s) for {}:{}".format(len(insns), arch_s, mode_s))

if args.as_shellcode:
gef_print("""sc="" """)
Expand Down Expand Up @@ -8244,7 +8239,7 @@ def reason():
line += Color.colorify("stopped", "bold red")
thread.switch()
frame = gdb.selected_frame()
line += " {:s} in {:s} ()".format(Color.colorify("{:#x}".format(frame.pc()), "blue"), Color.colorify(frame.name() or "??" ,"bold yellow"))
line += " {:s} in {:s} ()".format(Color.colorify("{:#x}".format(frame.pc()), "blue"), Color.colorify(frame.name() or "??", "bold yellow"))
line += ", reason: {}".format(Color.colorify(reason(), "bold pink"))
elif thread.is_exited():
line += Color.colorify("exited", "bold yellow")
Expand Down Expand Up @@ -9811,9 +9806,8 @@ def get_zone_base_address(name):

return None

class GenericFunction(gdb.Function):
class GenericFunction(gdb.Function, metaclass=abc.ABCMeta):
"""This is an abstract class for invoking convenience functions, should not be instantiated."""
__metaclass__ = abc.ABCMeta

@abc.abstractproperty
def _function_(self): pass
Expand Down Expand Up @@ -10053,7 +10047,7 @@ def load(self, initial=False):
self.loaded_functions.append(function_class_name())

def is_loaded(x):
return any(filter(lambda u: x == u[0], self.loaded_commands))
return any([u for u in self.loaded_commands if x == u[0]])

for cmd, class_name in self.commands:
if is_loaded(cmd):
Expand All @@ -10077,7 +10071,7 @@ def is_loaded(x):
if initial:
gef_print("{:s} for {:s} ready, type `{:s}' to start, `{:s}' to configure"
.format(Color.greenify("GEF"), get_os(),
Color.colorify("gef","underline yellow"),
Color.colorify("gef", "underline yellow"),
Color.colorify("gef config", "underline pink")))

ver = "{:d}.{:d}".format(sys.version_info.major, sys.version_info.minor)
Expand Down Expand Up @@ -10169,7 +10163,7 @@ def invoke(self, args, from_tty):

if argc == 1:
prefix = argv[0]
names = list(filter(lambda x: x.startswith(prefix), __config__.keys()))
names = list([x for x in __config__.keys() if x.startswith(prefix)])
if names:
if len(names) == 1:
gef_print(titlify("GEF configuration setting: {:s}".format(names[0])))
Expand Down Expand Up @@ -10426,7 +10420,7 @@ def __init__(self, alias, command, completer_class=gdb.COMPLETE_NONE, command_cl
if not p:
return

if list(filter(lambda x: x._alias == alias, __aliases__)):
if list([x for x in __aliases__ if x._alias == alias]):
return

self._command = command
Expand Down Expand Up @@ -10508,7 +10502,7 @@ def do_invoke(self, argv):
self.usage()
return
try:
alias_to_remove = next(filter(lambda x: x._alias == argv[0], __aliases__))
alias_to_remove = next([x for x in __aliases__ if x._alias == argv[0]])
__aliases__.remove(alias_to_remove)
except (ValueError, StopIteration) as e:
err("{0} not found in aliases.".format(argv[0]))
Expand Down

0 comments on commit 5df3002

Please sign in to comment.