mirror of
https://github.com/mandiant/capa.git
synced 2025-12-22 07:10:29 -08:00
code style : update remaining files (#1353)
* code style: update string formatting using fstrings --------- Co-authored-by: Willi Ballenthin <willi.ballenthin@gmail.com> Co-authored-by: Moritz <mr-tz@users.noreply.github.com>
This commit is contained in:
@@ -112,7 +112,7 @@ def get_capa_results(args):
|
||||
return {
|
||||
"path": path,
|
||||
"status": "error",
|
||||
"error": "input file does not appear to be a PE file: %s" % path,
|
||||
"error": f"input file does not appear to be a PE file: {path}",
|
||||
}
|
||||
except capa.main.UnsupportedRuntimeError:
|
||||
return {
|
||||
@@ -124,7 +124,7 @@ def get_capa_results(args):
|
||||
return {
|
||||
"path": path,
|
||||
"status": "error",
|
||||
"error": "unexpected error: %s" % (e),
|
||||
"error": f"unexpected error: {e}",
|
||||
}
|
||||
|
||||
meta = capa.main.collect_metadata([], path, [], extractor)
|
||||
@@ -202,7 +202,7 @@ def main(argv=None):
|
||||
elif result["status"] == "ok":
|
||||
results[result["path"]] = rd.ResultDocument.parse_obj(result["ok"]).json(exclude_none=True)
|
||||
else:
|
||||
raise ValueError("unexpected status: %s" % (result["status"]))
|
||||
raise ValueError(f"unexpected status: {result['status']}")
|
||||
|
||||
print(json.dumps(results))
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def render_capabilities(doc: rd.ResultDocument, result):
|
||||
if count == 1:
|
||||
capability = rule.meta.name
|
||||
else:
|
||||
capability = "%s (%d matches)" % (rule.meta.name, count)
|
||||
capability = f"{rule.meta.name} ({count} matches)"
|
||||
|
||||
result["CAPABILITY"].setdefault(rule.meta.namespace, list())
|
||||
result["CAPABILITY"][rule.meta.namespace].append(capability)
|
||||
@@ -108,9 +108,9 @@ def render_attack(doc, result):
|
||||
inner_rows = []
|
||||
for technique, subtechnique, id in sorted(techniques):
|
||||
if subtechnique is None:
|
||||
inner_rows.append("%s %s" % (technique, id))
|
||||
inner_rows.append(f"{technique} {id}")
|
||||
else:
|
||||
inner_rows.append("%s::%s %s" % (technique, subtechnique, id))
|
||||
inner_rows.append(f"{technique}::{subtechnique} {id}")
|
||||
result["ATTCK"].setdefault(tactic.upper(), inner_rows)
|
||||
|
||||
|
||||
@@ -142,9 +142,9 @@ def render_mbc(doc, result):
|
||||
inner_rows = []
|
||||
for behavior, method, id in sorted(behaviors):
|
||||
if method is None:
|
||||
inner_rows.append("%s [%s]" % (behavior, id))
|
||||
inner_rows.append(f"{behavior} [{id}]")
|
||||
else:
|
||||
inner_rows.append("%s::%s [%s]" % (behavior, method, id))
|
||||
inner_rows.append(f"{behavior}::{method} [{id}]")
|
||||
result["MBC"].setdefault(objective.upper(), inner_rows)
|
||||
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ def load_analysis(bv):
|
||||
if not path or not os.access(path, os.R_OK):
|
||||
binaryninja.log_error("Invalid filename.")
|
||||
return 0
|
||||
binaryninja.log_info("Using capa file %s" % path)
|
||||
binaryninja.log_info(f"Using capa file {path}")
|
||||
|
||||
with open(path, "rb") as f:
|
||||
doc = json.loads(f.read().decode("utf-8"))
|
||||
@@ -97,7 +97,7 @@ def load_analysis(bv):
|
||||
else:
|
||||
cmt = f"{name}"
|
||||
|
||||
binaryninja.log_info("0x%x: %s" % (va, cmt))
|
||||
binaryninja.log_info(f"{hex(va)}: {cmt}")
|
||||
try:
|
||||
# message will look something like:
|
||||
#
|
||||
|
||||
@@ -101,9 +101,9 @@ def main():
|
||||
rows = sorted(rows)
|
||||
for ns, name, va in rows:
|
||||
if ns:
|
||||
cmt = f"{name} ({ns})"
|
||||
cmt = name + f"({ns})"
|
||||
else:
|
||||
cmt = f"{name}"
|
||||
cmt = name
|
||||
|
||||
logger.info("0x%x: %s", va, cmt)
|
||||
try:
|
||||
|
||||
@@ -19,17 +19,17 @@ def display_top(snapshot, key_type="lineno", limit=10):
|
||||
print(f"Top {limit} lines")
|
||||
for index, stat in enumerate(top_stats[:limit], 1):
|
||||
frame = stat.traceback[0]
|
||||
print(f"#{index}: {frame.filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB")
|
||||
print(f"#{index}: {frame.filename}:{frame.lineno}: {(stat.size/1024):.1f} KiB")
|
||||
line = linecache.getline(frame.filename, frame.lineno).strip()
|
||||
if line:
|
||||
print(" %s" % line)
|
||||
print(f" {line}")
|
||||
|
||||
other = top_stats[limit:]
|
||||
if other:
|
||||
size = sum(stat.size for stat in other)
|
||||
print(f"{len(other)} other: {size / 1024:.1f} KiB")
|
||||
print(f"{len(other)} other: {(size/1024):.1f} KiB")
|
||||
total = sum(stat.size for stat in top_stats)
|
||||
print(f"Total allocated size: {total / 1024:.1f} KiB")
|
||||
print(f"Total allocated size: {(total/1024):.1f} KiB")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -49,7 +49,7 @@ def main():
|
||||
print()
|
||||
|
||||
for i in range(count):
|
||||
print(f"iteration {i + 1}/{count}...")
|
||||
print(f"iteration {i+1}/{count}...")
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
t0 = time.time()
|
||||
@@ -59,9 +59,9 @@ def main():
|
||||
gc.collect()
|
||||
|
||||
process = psutil.Process(os.getpid())
|
||||
print(f" duration: {t1 - t0:.02f}s")
|
||||
print(f" rss: {process.memory_info().rss / 1024 / 1024:.1f} MiB")
|
||||
print(f" vms: {process.memory_info().vms / 1024 / 1024:.1f} MiB")
|
||||
print(f" duration: {(t1-t0):.2f}")
|
||||
print(f" rss: {(process.memory_info().rss / 1024 / 1024):.1f} MiB")
|
||||
print(f" vms: {(process.memory_info().vms / 1024 / 1024):.1f} MiB")
|
||||
|
||||
print("done.")
|
||||
gc.collect()
|
||||
|
||||
@@ -133,9 +133,9 @@ def main(argv=None):
|
||||
# so lets put that first.
|
||||
#
|
||||
# https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat
|
||||
"%0.2fs" % (min(samples) / float(args.number)),
|
||||
"%0.2fs" % (sum(samples) / float(args.repeat) / float(args.number)),
|
||||
"%0.2fs" % (max(samples) / float(args.number)),
|
||||
f"{(min(samples) / float(args.number)):.2f}s",
|
||||
f"{(sum(samples) / float(args.repeat) / float(args.number)):.2f}s",
|
||||
f"{(max(samples) / float(args.number)):.2f}s",
|
||||
)
|
||||
],
|
||||
headers=["label", "count(evaluations)", "min(time)", "avg(time)", "max(time)"],
|
||||
|
||||
@@ -118,7 +118,7 @@ def render_matches_by_function(doc: rd.ResultDocument):
|
||||
for f in doc.meta.analysis.feature_counts.functions:
|
||||
if not matches_by_function.get(f.address, {}):
|
||||
continue
|
||||
ostream.writeln("function at %s with %d features: " % (capa.render.verbose.format_address(addr), f.count))
|
||||
ostream.writeln(f"function at {capa.render.verbose.format_address(addr)} with {f.count} features: ")
|
||||
for rule_name in sorted(matches_by_function[f.address]):
|
||||
ostream.writeln(" - " + rule_name)
|
||||
|
||||
|
||||
@@ -130,11 +130,11 @@ def main(argv=None):
|
||||
return -1
|
||||
|
||||
for feature, addr in extractor.extract_global_features():
|
||||
print("global: %s: %s" % (format_address(addr), feature))
|
||||
print(f"global: {format_address(addr)}: {feature}")
|
||||
|
||||
if not args.function:
|
||||
for feature, addr in extractor.extract_file_features():
|
||||
print("file: %s: %s" % (format_address(addr), feature))
|
||||
print(f"file: {format_address(addr)}: {feature}")
|
||||
|
||||
function_handles = tuple(extractor.get_functions())
|
||||
|
||||
@@ -146,11 +146,11 @@ def main(argv=None):
|
||||
function_handles = tuple(filter(lambda fh: format_address(fh.address) == args.function, function_handles))
|
||||
|
||||
if args.function not in [format_address(fh.address) for fh in function_handles]:
|
||||
print("%s not a function" % args.function)
|
||||
print(f"{args.function} not a function")
|
||||
return -1
|
||||
|
||||
if len(function_handles) == 0:
|
||||
print("%s not a function", args.function)
|
||||
print(f"{args.function} not a function")
|
||||
return -1
|
||||
|
||||
print_features(function_handles, extractor)
|
||||
@@ -164,13 +164,13 @@ def ida_main():
|
||||
import capa.features.extractors.ida.extractor
|
||||
|
||||
function = idc.get_func_attr(idc.here(), idc.FUNCATTR_START)
|
||||
print("getting features for current function 0x%X" % function)
|
||||
print(f"getting features for current function {hex(function)}")
|
||||
|
||||
extractor = capa.features.extractors.ida.extractor.IdaFeatureExtractor()
|
||||
|
||||
if not function:
|
||||
for feature, addr in extractor.extract_file_features():
|
||||
print("file: %s: %s" % (format_address(addr), feature))
|
||||
print(f"file: {format_address(addr)}: {feature}")
|
||||
return
|
||||
|
||||
function_handles = tuple(extractor.get_functions())
|
||||
@@ -179,7 +179,7 @@ def ida_main():
|
||||
function_handles = tuple(filter(lambda fh: fh.inner.start_ea == function, function_handles))
|
||||
|
||||
if len(function_handles) == 0:
|
||||
print("0x%X not a function" % function)
|
||||
print(f"{hex(function)} not a function")
|
||||
return -1
|
||||
|
||||
print_features(function_handles, extractor)
|
||||
@@ -194,16 +194,16 @@ def print_features(functions, extractor: capa.features.extractors.base_extractor
|
||||
logger.debug("skipping library function %s (%s)", format_address(f.address), function_name)
|
||||
continue
|
||||
|
||||
print("func: %s" % (format_address(f.address)))
|
||||
print(f"func: {format_address(f.address)}")
|
||||
|
||||
for feature, addr in extractor.extract_function_features(f):
|
||||
if capa.features.common.is_global_feature(feature):
|
||||
continue
|
||||
|
||||
if f.address != addr:
|
||||
print(" func: %s: %s -> %s" % (format_address(f.address), feature, format_address(addr)))
|
||||
print(f" func: {format_address(f.address)}: {feature} -> {format_address(addr)}")
|
||||
else:
|
||||
print(" func: %s: %s" % (format_address(f.address), feature))
|
||||
print(f" func: {format_address(f.address)}: {feature}")
|
||||
|
||||
for bb in extractor.get_basic_blocks(f):
|
||||
for feature, addr in extractor.extract_basic_block_features(f, bb):
|
||||
@@ -211,9 +211,9 @@ def print_features(functions, extractor: capa.features.extractors.base_extractor
|
||||
continue
|
||||
|
||||
if bb.address != addr:
|
||||
print(" bb: %s: %s -> %s" % (format_address(bb.address), feature, format_address(addr)))
|
||||
print(f" bb: {format_address(bb.address)}: {feature} -> {format_address(addr)}")
|
||||
else:
|
||||
print(" bb: %s: %s" % (format_address(bb.address), feature))
|
||||
print(f" bb: {format_address(bb.address)}: {feature}")
|
||||
|
||||
for insn in extractor.get_instructions(f, bb):
|
||||
for feature, addr in extractor.extract_insn_features(f, bb, insn):
|
||||
@@ -223,16 +223,10 @@ def print_features(functions, extractor: capa.features.extractors.base_extractor
|
||||
try:
|
||||
if insn.address != addr:
|
||||
print(
|
||||
" insn: %s: %s: %s -> %s"
|
||||
% (
|
||||
format_address(f.address),
|
||||
format_address(insn.address),
|
||||
feature,
|
||||
format_address(addr),
|
||||
)
|
||||
f" insn: {format_address(f.address)}: {format_address(insn.address)}: {feature} -> {format_address(addr)}"
|
||||
)
|
||||
else:
|
||||
print(" insn: %s: %s" % (format_address(insn.address), feature))
|
||||
print(f" insn: {format_address(insn.address)}: {feature}")
|
||||
|
||||
except UnicodeEncodeError:
|
||||
# may be an issue while piping to less and encountering non-ascii characters
|
||||
|
||||
Reference in New Issue
Block a user