Skip to content

Commit

Permalink
Normalize type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
twizmwazin committed Aug 25, 2023
1 parent a7819f4 commit 6229e8c
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 25 deletions.
12 changes: 8 additions & 4 deletions cle/backends/elf/elf.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def get_symbol(self, symid, symbol_table=None): # pylint: disable=arguments-dif
:param symid: Either an index into .dynsym or the name of a symbol.
"""
version = None
if type(symid) is int:
if isinstance(symid, int):
if symid == 0:
# special case the null symbol, this is important for static binaries
return self._nullsymbol
Expand All @@ -400,7 +400,7 @@ def get_symbol(self, symid, symbol_table=None): # pylint: disable=arguments-dif
return cached
if self.hashtable is not None and symbol_table is self.hashtable.symtab and self._vertable is not None:
version = self._vertable.get_symbol(symid).entry.ndx
elif type(symid) is str:
elif isinstance(symid, str):
if not symid:
log.warning("Trying to resolve a symbol by its empty name")
return None
Expand Down Expand Up @@ -578,7 +578,7 @@ def _load_function_hints_from_fde(self, dwarf, source):

try:
for entry in dwarf.EH_CFI_entries():
if type(entry) is callframe.FDE:
if isinstance(entry, callframe.FDE):
self.function_hints.append(
FunctionHint(
entry.header["initial_location"],
Expand All @@ -601,7 +601,11 @@ def _load_exception_handling(self, dwarf):
try:
lsda = LSDAExceptionTable(self._binary_stream, self.arch.bits, self.arch.memory_endness == "Iend_LE")
for entry in dwarf.EH_CFI_entries():
if type(entry) is callframe.FDE and hasattr(entry, "lsda_pointer") and entry.lsda_pointer is not None:
if (
isinstance(entry, callframe.FDE)
and hasattr(entry, "lsda_pointer")
and entry.lsda_pointer is not None
):
# function address
func_addr = entry.header.get("initial_location", None)
if func_addr is None:
Expand Down
6 changes: 3 additions & 3 deletions cle/backends/elf/metaelf.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Relro(Enum):
def maybedecode(string):
# so... it turns out that pyelftools is garbage and will transparently give you either strings or bytestrings
# based on pretty much nothing whatsoever
return string if type(string) is str else string.decode()
return string if isinstance(string, str) else string.decode()


def _get_relro(elf):
Expand Down Expand Up @@ -207,7 +207,7 @@ def tick():
tick.bailout_timer = 5

def scan_forward(addr, name, push=False):
names = [name] if type(name) not in (list, tuple) else name
names = [name] if not isinstance(name, (list, tuple)) else name

def block_is_good(blk):
all_constants = {c.value for c in blk.all_constants}
Expand Down Expand Up @@ -479,7 +479,7 @@ def extract_soname(path):
for tag in seg.iter_tags():
if tag.entry.d_tag == "DT_SONAME":
return maybedecode(tag.soname)
if type(path) is str:
if isinstance(path, str):
return os.path.basename(path)

except elftools.common.exceptions.ELFError:
Expand Down
2 changes: 1 addition & 1 deletion cle/backends/elf/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def maybedecode(string):
return string if type(string) is str else string.decode()
return string if isinstance(string, str) else string.decode()


class ELFSegment(Segment):
Expand Down
4 changes: 2 additions & 2 deletions cle/backends/elf/symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


def maybedecode(string):
return string if type(string) is str else string.decode()
return string if isinstance(string, str) else string.decode()


class ELFSymbol(Symbol):
Expand Down Expand Up @@ -49,7 +49,7 @@ def __init__(self, owner, symb):
self.version = None
self.binding = symb.entry.st_info.bind
self.is_hidden = symb.entry["st_other"]["visibility"] == "STV_HIDDEN"
self.section = sec_ndx if type(sec_ndx) is not str else None
self.section = sec_ndx if not isinstance(sec_ndx, str) else None
self.is_static = self._type == SymbolType.TYPE_SECTION or sec_ndx == "SHN_ABS"
self.is_common = sec_ndx == "SHN_COMMON"
self.is_weak = self.binding == "STB_WEAK"
Expand Down
20 changes: 10 additions & 10 deletions cle/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ def __init__(
self._satisfied_deps: Dict[str, Union[Literal[False], Backend]] = {x: False for x in skip_libs}
self._main_opts = {} if main_opts is None else main_opts
self._lib_opts = {} if lib_opts is None else lib_opts
self._custom_ld_path = [ld_path] if type(ld_path) is str else ld_path
force_load_libs = [force_load_libs] if type(force_load_libs) is str else force_load_libs
preload_libs = [preload_libs] if type(preload_libs) is str else preload_libs
self._custom_ld_path = [ld_path] if isinstance(ld_path, str) else ld_path
force_load_libs = [force_load_libs] if isinstance(force_load_libs, str) else force_load_libs
preload_libs = [preload_libs] if isinstance(preload_libs, str) else preload_libs
self._use_system_libs = use_system_libs
self._ignore_import_version_numbers = ignore_import_version_numbers
self._case_insensitive = case_insensitive
Expand All @@ -165,7 +165,7 @@ def __init__(
if sys.platform == "win32": # TODO: a real check for case insensitive filesystems
if self._main_binary_path:
self._main_binary_path = self._main_binary_path.lower()
force_load_libs = [x.lower() if type(x) is str else x for x in force_load_libs]
force_load_libs = [x.lower() if isinstance(x, str) else x for x in force_load_libs]
for x in list(self._satisfied_deps):
self._satisfied_deps[x.lower()] = self._satisfied_deps[x]
for x in list(self._lib_opts):
Expand Down Expand Up @@ -436,7 +436,7 @@ def _check_object_memory(obj_):
self._last_object = obj_
return obj_
return None
elif type(obj_.memory) is str:
elif isinstance(obj_.memory, str):
self._last_object = obj_
return obj_
else:
Expand Down Expand Up @@ -564,11 +564,11 @@ def find_symbol(self, thing, fuzzy=False) -> Optional[Symbol]:
:returns: A :class:`cle.backends.Symbol` object if found, None otherwise.
"""
if type(thing) is archinfo.arch_soot.SootAddressDescriptor:
if isinstance(thing, archinfo.arch_soot.SootAddressDescriptor):
# Soot address
# TODO launch this shit into the sun
return thing.method.fullname # type: ignore
elif type(thing) is int:
elif isinstance(thing, int):
# address
if fuzzy:
so = self.find_object_containing(thing)
Expand Down Expand Up @@ -832,7 +832,7 @@ def _internal_load(self, *args, preloading=()):
objects.extend(obj.child_objects)
dependencies.extend(obj.deps)

if type(self.tls) is ThreadManager: # ... java
if isinstance(self.tls, ThreadManager): # ... java
if isinstance(obj, MetaELF):
self._tls = ELFThreadManager(self, obj.arch)
elif isinstance(obj, PE):
Expand Down Expand Up @@ -944,7 +944,7 @@ def _load_object_isolated(self, spec):
binary_stream = spec
binary = None
close = False
elif type(spec) in (bytes, str):
elif isinstance(spec, (bytes, str)):
binary = self._search_load_path(spec) # this is allowed to cheat and do partial static loading
log.debug("... using full path %s", binary)
binary_stream = open(binary, "rb")
Expand Down Expand Up @@ -1242,7 +1242,7 @@ def _possible_idents(self, spec, lowercase=False):
yield soname
if self._ignore_import_version_numbers:
yield soname.rstrip(".0123456789")
elif type(spec) in (bytes, str):
elif isinstance(spec, (bytes, str)):
yield spec
yield os.path.basename(spec)
yield os.path.basename(spec).split(".")[0]
Expand Down
10 changes: 5 additions & 5 deletions cle/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def add_backer(self, start, data, overwrite=False):
raise ValueError("Address %#x is already backed!" % start)
if isinstance(data, Clemory) and data._root:
raise ValueError("Cannot add a root clemory as a backer!")
if type(data) is bytes:
if isinstance(data, bytes):
data = bytearray(data)
bisect.insort(self._backers, (start, data))
self._update_min_max()
Expand Down Expand Up @@ -243,7 +243,7 @@ def __repr__(self) -> str:
def update_backer(self, start, data):
if not isinstance(data, (bytes, list, Clemory)):
raise TypeError("Data must be a bytes, list, or Clemory object.")
if type(data) is bytes:
if isinstance(data, bytes):
data = bytearray(data)
for i, (oldstart, _) in enumerate(self._backers):
if oldstart == start:
Expand Down Expand Up @@ -275,7 +275,7 @@ def __iter__(self):

def __getitem__(self, k):
for start, data in self._backers:
if type(data) in (bytearray, list):
if isinstance(data, (bytearray, list)):
if 0 <= k - start < len(data):
return data[k - start]
elif isinstance(data, Clemory):
Expand All @@ -288,7 +288,7 @@ def __getitem__(self, k):

def __setitem__(self, k, v):
for start, data in self._backers:
if type(data) in (bytearray, list):
if isinstance(data, (bytearray, list)):
if 0 <= k - start < len(data):
data[k - start] = v
return
Expand Down Expand Up @@ -433,7 +433,7 @@ def find(self, data, search_min=None, search_max=None):
if search_max < backer.min_addr + start or search_min > backer.max_addr + start:
continue
yield from (addr + start for addr in backer.find(data, search_min - start, search_max - start))
elif type(backer) is list:
elif isinstance(backer, list):
raise TypeError("find is not supported for list-backed clemories")
else:
if search_max < start or search_min > start + len(data):
Expand Down

0 comments on commit 6229e8c

Please sign in to comment.