[go: up one dir, main page]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a bunch of ruff lints #4774

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
  •  
  •  
  •  
1 change: 1 addition & 0 deletions angr/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# pylint: disable=wildcard-import
# pylint: disable=wrong-import-position
from __future__ import annotations

__version__ = "9.2.117.dev0"

Expand Down
1 change: 1 addition & 0 deletions angr/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import annotations
import argparse

from angr.analyses.decompiler.structuring import STRUCTURER_CLASSES, DEFAULT_STRUCTURER
Expand Down
1 change: 1 addition & 0 deletions angr/analyses/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# pylint:disable=wrong-import-position
from __future__ import annotations
from .analysis import Analysis, AnalysesHub


Expand Down
90 changes: 45 additions & 45 deletions angr/analyses/analysis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# ruff: noqa: F401
from __future__ import annotations
import functools
import sys
import contextlib
Expand Down Expand Up @@ -88,14 +89,13 @@ def __repr__(self):
msg_str = msg_str[:66] + "..."
if msg_str[0] in ('"', "'"):
msg_str += msg_str[0]
return "<AnalysisLogEntry %s>" % msg_str
else:
msg_str = repr(self.message)
if len(msg_str) > 40:
msg_str = msg_str[:36] + "..."
if msg_str[0] in ('"', "'"):
msg_str += msg_str[0]
return f"<AnalysisLogEntry {msg_str} with {self.exc_type.__name__}: {self.exc_value}>"
return f"<AnalysisLogEntry {msg_str}>"
msg_str = repr(self.message)
if len(msg_str) > 40:
msg_str = msg_str[:36] + "..."
if msg_str[0] in ('"', "'"):
msg_str += msg_str[0]
return f"<AnalysisLogEntry {msg_str} with {self.exc_type.__name__}: {self.exc_value}>"


A = TypeVar("A", bound="Analysis")
Expand All @@ -114,7 +114,7 @@ def __init__(self, project):
def reload_analyses(self): # pylint: disable=no-self-use
return

def _init_plugin(self, plugin_cls: type[A]) -> "AnalysisFactory[A]":
def _init_plugin(self, plugin_cls: type[A]) -> AnalysisFactory[A]:
return AnalysisFactory(self.project, plugin_cls)

def __getstate__(self):
Expand All @@ -125,42 +125,42 @@ def __setstate__(self, sd):
s, self.project = sd
super().__setstate__(s)

def __getitem__(self, plugin_cls: type[A]) -> "AnalysisFactory[A]":
def __getitem__(self, plugin_cls: type[A]) -> AnalysisFactory[A]:
return AnalysisFactory(self.project, plugin_cls)


class KnownAnalysesPlugin(typing.Protocol):
Identifier: "Type[Identifier]"
CalleeCleanupFinder: "Type[CalleeCleanupFinder]"
VSA_DDG: "Type[VSA_DDG]"
CDG: "Type[CDG]"
BinDiff: "Type[BinDiff]"
CFGEmulated: "Type[CFGEmulated]"
CFB: "Type[CFBlanket]"
CFBlanket: "Type[CFBlanket]"
CFG: "Type[CFG]"
CFGFast: "Type[CFGFast]"
StaticHooker: "Type[StaticHooker]"
DDG: "Type[DDG]"
CongruencyCheck: "Type[CongruencyCheck]"
Reassembler: "Type[Reassembler]"
BackwardSlice: "Type[BackwardSlice]"
BinaryOptimizer: "Type[BinaryOptimizer]"
VFG: "Type[VFG]"
LoopFinder: "Type[LoopFinder]"
Disassembly: "Type[Disassembly]"
Veritesting: "Type[Veritesting]"
CodeTagging: "Type[CodeTagging]"
BoyScout: "Type[BoyScout]"
VariableRecoveryFast: "Type[VariableRecoveryFast]"
VariableRecovery: "Type[VariableRecovery]"
ReachingDefinitions: "Type[ReachingDefinitionsAnalysis]"
CompleteCallingConventions: "Type[CompleteCallingConventionsAnalysis]"
Clinic: "Type[Clinic]"
Propagator: "Type[PropagatorAnalysis]"
CallingConvention: "Type[CallingConventionAnalysis]"
Decompiler: "Type[Decompiler]"
XRefs: "Type[XRefsAnalysis]"
Identifier: type[Identifier]
CalleeCleanupFinder: type[CalleeCleanupFinder]
VSA_DDG: type[VSA_DDG]
CDG: type[CDG]
BinDiff: type[BinDiff]
CFGEmulated: type[CFGEmulated]
CFB: type[CFBlanket]
CFBlanket: type[CFBlanket]
CFG: type[CFG]
CFGFast: type[CFGFast]
StaticHooker: type[StaticHooker]
DDG: type[DDG]
CongruencyCheck: type[CongruencyCheck]
Reassembler: type[Reassembler]
BackwardSlice: type[BackwardSlice]
BinaryOptimizer: type[BinaryOptimizer]
VFG: type[VFG]
LoopFinder: type[LoopFinder]
Disassembly: type[Disassembly]
Veritesting: type[Veritesting]
CodeTagging: type[CodeTagging]
BoyScout: type[BoyScout]
VariableRecoveryFast: type[VariableRecoveryFast]
VariableRecovery: type[VariableRecovery]
ReachingDefinitions: type[ReachingDefinitionsAnalysis]
CompleteCallingConventions: type[CompleteCallingConventionsAnalysis]
Clinic: type[Clinic]
Propagator: type[PropagatorAnalysis]
CallingConvention: type[CallingConventionAnalysis]
Decompiler: type[Decompiler]
XRefs: type[XRefsAnalysis]


class AnalysesHubWithDefault(AnalysesHub, KnownAnalysesPlugin):
Expand All @@ -170,7 +170,7 @@ class AnalysesHubWithDefault(AnalysesHub, KnownAnalysesPlugin):


class AnalysisFactory(Generic[A]):
def __init__(self, project: "Project", analysis_cls: type[A]):
def __init__(self, project: Project, analysis_cls: type[A]):
self._project = project
self._analysis_cls = analysis_cls
self.__doc__ = ""
Expand All @@ -181,7 +181,7 @@ def __init__(self, project: "Project", analysis_cls: type[A]):
def prep(
self,
fail_fast=False,
kb: Optional["KnowledgeBase"] = None,
kb: KnowledgeBase | None = None,
progress_callback: Callable | None = None,
show_progressbar: bool = False,
) -> type[A]:
Expand Down Expand Up @@ -235,8 +235,8 @@ class Analysis:
:ivar progress.Progress _progressbar: The progress bar object.
"""

project: "Project"
kb: "KnowledgeBase"
project: Project
kb: KnowledgeBase
_fail_fast: bool
_name: str
errors = []
Expand Down
37 changes: 16 additions & 21 deletions angr/analyses/backward_slice.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import annotations
import logging
from collections import defaultdict

Expand Down Expand Up @@ -77,7 +78,7 @@ def __init__(
elif type(t) is tuple:
self._targets.append(t)
else:
raise AngrBackwardSlicingError("Unsupported type of target %s" % t)
raise AngrBackwardSlicingError(f"Unsupported type of target {t}")

# Save a list of taints to begin with at the beginning of each SimRun
self.initial_taints_per_run = None
Expand All @@ -96,8 +97,7 @@ def __init__(
#

def __repr__(self):
s = "BackwardSlice (to %s)" % self._targets
return s
return f"BackwardSlice (to {self._targets})"

def dbg_repr(self, max_display=10):
"""
Expand Down Expand Up @@ -137,34 +137,31 @@ def dbg_repr_run(self, run_addr):
"""

if self.project.is_hooked(run_addr):
ss = "%#x Hooked\n" % run_addr
ss = f"{run_addr:#x} Hooked\n"

else:
ss = "%#x\n" % run_addr
ss = f"{run_addr:#x}\n"

# statements
chosen_statements = self.chosen_statements[run_addr]

vex_block = self.project.factory.block(run_addr).vex

statements = vex_block.statements
for i in range(0, len(statements)):
if i in chosen_statements:
line = "+"
else:
line = "-"
for i in range(len(statements)):
line = "+" if i in chosen_statements else "-"
line += "[% 3d] " % i
line += str(statements[i])
ss += line + "\n"

# exits
targets = self.chosen_exits[run_addr]
addr_strs = []
for exit_stmt_id, target_addr in targets:
for _exit_stmt_id, target_addr in targets:
if target_addr is None:
addr_strs.append("default")
else:
addr_strs.append("%#x" % target_addr)
addr_strs.append(f"{target_addr:#x}")

ss += "Chosen exits: " + ", ".join(addr_strs)

Expand Down Expand Up @@ -327,9 +324,7 @@ def _construct_control_flow_slice(self, simruns):
if simrun not in cfg:
l.error("SimRun instance %s is not in the CFG.", simrun)

stack = []
for simrun in simruns:
stack.append(simrun)
stack = list(simruns)

self.runs_in_slice = networkx.DiGraph()
self.cfg_nodes_in_slice = networkx.DiGraph()
Expand Down Expand Up @@ -371,7 +366,7 @@ def _construct_default(self, targets):

for cfg_node, stmt_idx in targets:
if cfg_node not in self._cfg.graph:
raise AngrBackwardSlicingError("Target CFGNode %s is not in the CFG." % cfg_node)
raise AngrBackwardSlicingError(f"Target CFGNode {cfg_node} is not in the CFG.")

if stmt_idx == -1:
new_taints = self._handle_control_dependence(cfg_node)
Expand Down Expand Up @@ -574,8 +569,8 @@ def _map_to_cfg(self):
new_exit_statements_per_run = defaultdict(list)

while len(exit_statements_per_run):
for block_address, exits in exit_statements_per_run.items():
for stmt_idx, exit_target in exits:
for exits in exit_statements_per_run.values():
for _stmt_idx, exit_target in exits:
if exit_target not in self.chosen_exits:
# Oh we found one!
# The default exit should be taken no matter where it leads to
Expand Down Expand Up @@ -606,9 +601,9 @@ def _pick_statement(self, block_address, stmt_idx):

# Sanity check
if not isinstance(block_address, int):
raise AngrBackwardSlicingError("Invalid block address %s." % block_address)
raise AngrBackwardSlicingError(f"Invalid block address {block_address}.")
if not isinstance(stmt_idx, int):
raise AngrBackwardSlicingError("Invalid statement ID %s." % stmt_idx)
raise AngrBackwardSlicingError(f"Invalid statement ID {stmt_idx}.")

self.chosen_statements[block_address].add(stmt_idx)

Expand Down Expand Up @@ -664,7 +659,7 @@ def _normalize_stmt_idx(self, block_addr, stmt_idx):
vex_block = self.project.factory.block(block_addr).vex
return len(vex_block.statements)

raise AngrBackwardSlicingError('Unsupported statement ID "%s"' % stmt_idx)
raise AngrBackwardSlicingError(f'Unsupported statement ID "{stmt_idx}"')

@staticmethod
def _last_branching_statement(statements):
Expand Down
Loading
Loading