Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion chb/app/CHVersion.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
chbversion: str = "0.3.0-20250805"
chbversion: str = "0.3.0-20250808"
8 changes: 8 additions & 0 deletions chb/app/Cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,14 @@ def successors(self, src: str) -> Sequence[str]:
else:
return []

def exitblocks(self) -> Sequence[str]:
blocks = list(self.blocks.keys())
result: List[str] = []
for b in blocks:
if not b in self.edges or len(self.edges[b]) == 0:
result.append(b)
return result

def __str__(self) -> str:
lines: List[str] = []
lines.append("Basic blocks: ")
Expand Down
6 changes: 6 additions & 0 deletions chb/app/Function.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,12 @@ def block(self, baddr: str) -> BasicBlock:
else:
raise UF.CHBError("Block " + baddr + " not found in " + self.faddr)

def containing_block(self, iaddr: str) -> str:
for (baddr, b) in self.blocks.items():
if b.has_instruction(iaddr):
return baddr
raise UF.CHBError("Containing block not found for instruction address " + iaddr)

def load_instructions(self) -> Mapping[str, Sequence[Instruction]]:
"""Return a mapping of block address to instructions that save to memory."""

Expand Down
11 changes: 11 additions & 0 deletions chb/app/Instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,17 @@ def rhs_expressions(self, filter: Callable[[XXpr], bool]) -> List[XXpr]:
def return_value(self) -> Optional[XXpr]:
return None

def reaching_definitions(self, var: str) -> List[str]:
rdefs = self.xdata.reachingdefs
result: List[str] = []
for rdef in rdefs:
if rdef is not None:
if str(rdef.variable) == var:
for loc in rdef.deflocations:
if str(loc) not in result:
result.append(str(loc))
return result

def assembly_ast(self, astree: ASTInterface) -> List[AST.ASTInstruction]:
raise UF.CHBError("assembly-ast not defined")

Expand Down
4 changes: 3 additions & 1 deletion chb/arm/opcodes/ARMBranch.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ def opargs(self) -> List[ARMOperand]:
def ft_conditions(self, xdata: InstrXData) -> Sequence[XXpr]:
xd = ARMBranchXData(xdata)
if xdata.has_branch_conditions():
if xd.is_ok:
if xd.is_ctcond_ok:
return [xd.cfcond, xd.ctcond]
elif xd.is_ok:
return [xd.fcond, xd.tcond]
else:
return [xd.fxpr, xd.txpr]
Expand Down
1 change: 1 addition & 0 deletions chb/astinterface/ASTInterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,7 @@ def introduce_ssa_variables(
for (reg, locs) in rdeflocs.items():
for lst in locs:
if len(lst) > 0:
# print("DEBUG: " + str(reg) + ": [" + ", ".join(str(loc) for loc in lst) + "]")
loc1 = lst[0]
vtype = None
if loc1 in ftypes:
Expand Down
59 changes: 57 additions & 2 deletions chb/cmdline/astcmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,13 @@
from chb.cmdline.PatchResults import PatchResults, PatchEvent
import chb.cmdline.XInfo as XI

from chb.graphics.DotRdefPath import DotRdefPath

from chb.userdata.UserHints import UserHints

import chb.util.dotutil as UD
import chb.util.fileutil as UF
import chb.util.graphutil as UG
from chb.util.loggingutil import chklogger, LogLevel


Expand Down Expand Up @@ -144,8 +148,8 @@ def buildast(args: argparse.Namespace) -> NoReturn:
xpatchresultsfile = args.patch_results_file
hide_globals: bool = args.hide_globals
hide_annotations: bool = args.hide_annotations
remove_edges: List[str] = args.remove_edges
add_edges: List[str] = args.add_edges
show_reachingdefs: str = args.show_reachingdefs
output_reachingdefs: str = args.output_reachingdefs
verbose: bool = args.verbose
loglevel: str = args.loglevel
logfilename: Optional[str] = args.logfilename
Expand Down Expand Up @@ -386,6 +390,57 @@ def buildast(args: argparse.Namespace) -> NoReturn:
functions_failed += 1
continue

if show_reachingdefs is not None:
if output_reachingdefs is None:
UC.print_error("\nSpecify a file to save the reaching defs")
continue

rdefspec = show_reachingdefs.split(":")
if len(rdefspec) != 2:
UC.print_error(
"\nArgument to show_reachingdefs not recognized")
continue

useloc = rdefspec[0]
register = rdefspec[1]

if not f.has_instruction(useloc):
UC.print_status_update("Useloc: " + useloc + " not found")
continue

tgtinstr = f.instruction(useloc)

if not register in f.rdef_locations():
UC.print_status_update(
"Register " + register + " not found in rdeflocations")
continue

cblock = f.containing_block(useloc)
graph = UG.DirectedGraph(list(f.cfg.blocks.keys()), f.cfg.edges)
rdefs = tgtinstr.reaching_definitions(register)
dotpaths: List[DotRdefPath] = []
graph.find_paths(f.faddr, cblock)
for (i, p) in enumerate(
sorted(graph.get_paths(), key=lambda p: len(p))):
cfgpath = DotRdefPath(
"path" + str(i),
f,
astinterface,
p,
subgraph=True,
nodeprefix = str(i) +":",
rdefinstrs = rdefs)
dotpaths.append(cfgpath)

pdffilename = UD.print_dot_subgraphs(
app.path,
"paths",
output_reachingdefs,
"pdf",
[dotcfg.build() for dotcfg in dotpaths])

UC.print_status_update("Printed " + pdffilename)

else:
UC.print_error("Unable to find function " + faddr)
functions_failed += 1
Expand Down
16 changes: 6 additions & 10 deletions chb/cmdline/chkx
Original file line number Diff line number Diff line change
Expand Up @@ -730,19 +730,15 @@ def parse() -> argparse.Namespace:
"--hide_annotations",
help="do not include annotations in printed C code",
action="store_true")
buildast.add_argument(
"--remove_edges",
nargs="*",
default=[],
help="list of edges to be removed (in the form faddr:src-addr:tgt-addr in hex)")
buildast.add_argument(
"--add_edges",
nargs="*",
default=[],
help="list of edges to be added (in the form faddr:src-addr:tgt-addr in hex)")
buildast.add_argument(
"--verbose", "-v",
action="store_true")
buildast.add_argument(
"--show_reachingdefs",
help="create a dot file for the reaching defs of <addr>:<reg>")
buildast.add_argument(
"--output_reachingdefs",
help="name of output file (without extension) to store dot/pdf file of reachingdefs")
buildast.add_argument(
"--loglevel", "-log",
choices=UL.LogLevel.options(),
Expand Down
209 changes: 209 additions & 0 deletions chb/graphics/DotRdefPath.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2025 Aarno Labs LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ------------------------------------------------------------------------------

from typing import Dict, List, Optional, TYPE_CHECKING

import chb.util.fileutil as UF

from chb.util.DotGraph import DotGraph

if TYPE_CHECKING:
from chb.app.Function import Function
from chb.app.Instruction import Instruction
from chb.astinterface.ASTInterface import ASTInterface


class DotRdefPath:

def __init__(
self,
graphname: str,
fn: "Function",
astree: "ASTInterface",
path: List[str],
nodeprefix: str = "",
replacements: Dict[str, str] = {},
rdefinstrs: List[str] = [],
subgraph: bool = False) -> None:

self._fn = fn
self._graphname = graphname
self._astree = astree
self._path = path
self._nodeprefix = nodeprefix
self._subgraph = subgraph
self._replacements = replacements
self._rdefinstrs = rdefinstrs
self._dotgraph = DotGraph(graphname, subgraph=self.subgraph)

@property
def function(self) -> "Function":
return self._fn

@property
def graphname(self) -> str:
return self._graphname

@property
def astree(self) -> "ASTInterface":
return self._astree

@property
def path(self) -> List[str]:
return self._path

@property
def nodeprefix(self) -> str:
return self._nodeprefix

@property
def subgraph(self) -> bool:
return self._subgraph

def pathindex(self, baddr: str) -> int:
for (i, n) in enumerate(self.path):
if n == baddr:
return i
raise UF.CHBError("Address " + baddr + " not found in path")

def build(self) -> DotGraph:
for n in self.path:
self.add_node(n)

for i in range(len(self.path) - 1):
self.add_edge(self.path[i], self.path[i+1])

if self.init_is_exposed():
(fvar, _) = self.astree.get_formal_locindices(0)
btype = fvar.bctyp
self._dotgraph.add_node(
self.nodeprefix + "init",
labeltxt="{ init | " + str(btype) + " " + fvar.vname + "}",
shaded=True,
color="orange",
recordformat=True)
self._dotgraph.add_edge(
self.nodeprefix + "init", self.nodeprefix + self.path[0])

return self._dotgraph

def init_is_exposed(self) -> bool:
result = True
for p in self.path:
instrs = self.rdef_instructions(p)
if any(not instr.has_control_flow() for instr in instrs):
result = False
return result

def is_exposed(self, n: str) -> bool:
index = self.pathindex(n)
for i in range(index + 1, len(self.path)):
node = self.path[i]
instrs = self.rdef_instructions(node)
if any(not instr.has_control_flow() for instr in instrs):
return False
return True

def replace_text(self, txt: str) -> str:
result = txt
for src in sorted(self._replacements, key=lambda x: len(x), reverse=True):
result = result.replace(src, self._replacements[src])
return result

def get_branch_instruction(self, n: str) -> Optional["Instruction"]:
src = self.function.cfg.blocks[n]
instraddr = src.lastaddr
return self.function.instruction(instraddr)

def rdef_instructions(self, n: str) -> List["Instruction"]:
block = self.function.blocks[n]
lastaddr = block.lastaddr
baddr = int(n, 16)
xaddr = int(lastaddr, 16)
result: List["Instruction"] = []
for i in self._rdefinstrs:
if i == "init":
continue
ix = int(i, 16)
if ix >= baddr and ix <= xaddr:
instr = block.instructions[i]
result.append(instr)
return result

def add_node(self, n: str) -> None:
nodename = self.nodeprefix + n
rdefinstrs = self.rdef_instructions(n)
blocktxt = n
color: Optional[str] = None
fillcolor: Optional[str] = None
if len(rdefinstrs) > 0:
conditions: List[str] = []
pinstrs: List[str] = []
for instr in rdefinstrs:
(hlinstrs, _) = instr.ast_prov(self.astree)
pinstrs.extend(str(hlinstr) for hlinstr in hlinstrs)
if instr.has_control_flow():
(cc, _) = instr.ast_cc_condition_prov(self.astree)
conditions.append(str(cc))
if self.is_exposed(n):
if any(instr.has_control_flow() for instr in rdefinstrs):
fillcolor = "yellow"
else:
fillcolor = "orange"
if len(conditions) > 0:
blocktxt = (
"{" + n + "|" + ("if " + "\\n".join(conditions))
+ "|" + "\\n".join(pinstrs) + "}")
else:
blocktxt = ("{" + n + "|" + "\\n".join(pinstrs) + "}")
self._dotgraph.add_node(
str(nodename),
labeltxt=blocktxt,
shaded=True,
color=color,
fillcolor=fillcolor,
recordformat=True)

def add_edge(self, n1: str, n2: str) -> None:
nodename1 = self.nodeprefix + n1
nodename2 = self.nodeprefix + n2
srcblock = self.function.block(n1)
labeltxt: Optional[str] = None
if len(self.function.cfg.edges[n1]) == 2:
tgtedges = self.function.cfg.edges[n1]
branchinstr = self.get_branch_instruction(n1)
if branchinstr and branchinstr.is_branch_instruction:
ftconds = branchinstr.ft_conditions
if len(ftconds) == 2:
if n2 == tgtedges[0]:
astcond = branchinstr.ast_condition_prov(
self.astree, reverse=True)
else:
astcond = branchinstr.ast_condition_prov(
self.astree, reverse=False)
labeltxt = str(astcond[0])
self._dotgraph.add_edge(nodename1, nodename2, labeltxt=labeltxt)
Loading