pcode-graph 3.0.2__py3-none-any.whl → 4.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,13 @@
1
- """Summary analysis of stack memory accesses.
1
+ """Summary analysis of stack and static memory accesses.
2
2
 
3
3
  LOAD and STORE addresses are resolved relatively to the stack pointer value at the entry
4
- of the code, so that loads can be linked to the stores they read. This mainly targets
5
- spilled variables, as found in code compiled without optimization (-O0).
4
+ of the code, or as absolute constants, so that loads can be linked to the stores they read.
5
+ This mainly targets spilled variables, as found in code compiled without optimization (-O0),
6
+ and global variables.
6
7
 
7
8
  No assumption is made on the use of the stack: calls to unknown code and stores to
8
- unresolved addresses may write anywhere, so the loads they reach keep the coarse single MEMORY model.
9
+ unresolved addresses may write anywhere, so the loads they reach remain unresolved.
10
+ Stack and absolute addresses are supposed not to alias each other.
9
11
  """
10
12
 
11
13
  from dataclasses import dataclass, field
@@ -13,11 +15,13 @@ import heapq
13
15
 
14
16
  from pypcode import OpCode, PcodeOp
15
17
 
18
+ from pcode_graph.analysis.pass_base import PassBase
16
19
  from pcode_graph.arch import Arch
17
- from pcode_graph.analysis import (
20
+ from pcode_graph.analysis.program import (
18
21
  EntryIndex,
22
+ Memory,
19
23
  OpIndex,
20
- RichPcodeList,
24
+ Program,
21
25
  UnknownCodeIndex,
22
26
  Var,
23
27
  VarKinds,
@@ -49,50 +53,57 @@ class StackAddress:
49
53
  # Known constant, stack address or unknown value
50
54
  AbstractValue = int | StackAddress | None
51
55
 
56
+ # Tracked memory byte: (is relative to the stack, offset or absolute address)
57
+ MemoryByte = tuple[bool, int]
58
+
52
59
 
53
60
  @dataclass(frozen=True, slots=True)
54
- class StackAccess:
61
+ class MemoryAccess:
62
+ in_stack: bool
55
63
  offset: int
56
64
  size: int
57
65
 
58
66
  @property
59
- def offsets(self) -> range:
60
- return range(self.offset, self.offset + self.size)
67
+ def bytes(self) -> list[MemoryByte]:
68
+ return [
69
+ (self.in_stack, offset)
70
+ for offset in range(self.offset, self.offset + self.size)
71
+ ]
61
72
 
62
73
 
63
74
  @dataclass(frozen=True, slots=True)
64
- class StackState:
65
- # Definitions of tracked bytes by offset
66
- tracked: dict[int, frozenset[OpIndex]]
75
+ class MemoryState:
76
+ # Definitions of tracked bytes
77
+ tracked: dict[MemoryByte, frozenset[OpIndex]]
67
78
 
68
79
  # Definitions of untracked bytes
69
80
  default: frozenset[OpIndex]
70
81
 
71
- def read(self, access: StackAccess) -> frozenset[OpIndex]:
82
+ def read(self, access: MemoryAccess) -> frozenset[OpIndex]:
72
83
  return frozenset().union(
73
- *(self.tracked.get(offset, self.default) for offset in access.offsets)
84
+ *(self.tracked.get(byte, self.default) for byte in access.bytes)
74
85
  )
75
86
 
76
- def write(self, access: StackAccess, index: OpIndex) -> "StackState":
87
+ def write(self, access: MemoryAccess, index: OpIndex) -> "MemoryState":
77
88
  written = frozenset({index})
78
89
  tracked = dict(self.tracked)
79
- for offset in access.offsets:
80
- tracked[offset] = written
81
- return StackState(tracked, self.default)
90
+ for byte in access.bytes:
91
+ tracked[byte] = written
92
+ return MemoryState(tracked, self.default)
82
93
 
83
- def clobber(self) -> "StackState":
94
+ def clobber(self) -> "MemoryState":
84
95
  unknown = {UnknownWriteIndex}
85
- return StackState(
86
- {offset: defs | unknown for offset, defs in self.tracked.items()},
96
+ return MemoryState(
97
+ {byte: defs | unknown for byte, defs in self.tracked.items()},
87
98
  self.default | unknown,
88
99
  )
89
100
 
90
- def merge(self, other: "StackState") -> "StackState":
91
- return StackState(
101
+ def merge(self, other: "MemoryState") -> "MemoryState":
102
+ return MemoryState(
92
103
  {
93
- offset: self.tracked.get(offset, self.default)
94
- | other.tracked.get(offset, other.default)
95
- for offset in self.tracked.keys() | other.tracked.keys()
104
+ byte: self.tracked.get(byte, self.default)
105
+ | other.tracked.get(byte, other.default)
106
+ for byte in self.tracked.keys() | other.tracked.keys()
96
107
  },
97
108
  self.default | other.default,
98
109
  )
@@ -102,34 +113,23 @@ ADDRESS_OPCODES = {OpCode.COPY, OpCode.INT_ADD, OpCode.INT_SUB, OpCode.INT_OR}
102
113
  CALL_OPCODES = {OpCode.CALL, OpCode.CALLIND, OpCode.CALLOTHER}
103
114
 
104
115
 
105
- @dataclass
106
- class StackMemory:
107
- """Results of the stack memory analysis."""
108
-
109
- # Maps a stack-reading LOAD to possible STORE definitions
110
- load_defs: dict[OpIndex, set[OpIndex]] = field(default_factory=dict)
111
-
112
- # Maps a load to defining stores if reading exactly the values written by them
113
- forwarded_loads: dict[OpIndex, list[OpIndex]] = field(default_factory=dict)
114
-
116
+ class MemoryAnalyzer(PassBase):
115
117
 
116
- def analyze_stack_memory(program: RichPcodeList) -> StackMemory:
117
- return StackMemoryAnalyzer(program)()
118
+ def __init__(self, program: Program) -> None:
119
+ super().__init__(program)
118
120
 
119
-
120
- class StackMemoryAnalyzer:
121
-
122
- def __init__(self, program: RichPcodeList) -> None:
123
- self.program = program
124
121
  self.stack_pointer = STACK_POINTERS.get(program.arch)
125
- self.result = StackMemory()
126
122
  self._output_values: dict[OpIndex, AbstractValue] = {}
127
- self._loads: dict[OpIndex, StackAccess] = {}
128
- self._stores: dict[OpIndex, StackAccess | None] = {}
123
+ self._loads: dict[OpIndex, MemoryAccess] = {}
124
+ self._stores: dict[OpIndex, MemoryAccess | None] = {}
125
+
126
+ @property
127
+ def result(self) -> Memory:
128
+ return self.program.memory
129
129
 
130
- def __call__(self) -> StackMemory:
130
+ def __call__(self):
131
131
  if self.stack_pointer is None or not self.program.basic_blocks:
132
- return self.result
132
+ return
133
133
 
134
134
  for index, op in enumerate(self.program.operations):
135
135
  if not self.program.reachable(index):
@@ -145,7 +145,7 @@ class StackMemoryAnalyzer:
145
145
  self._stores[index] = self._compute_access(index, op.inputs[2].size)
146
146
 
147
147
  self._collect_load_defs(self._compute_reads())
148
- return self.result
148
+
149
149
 
150
150
  def value_of(self, index: OpIndex, var: Var) -> AbstractValue:
151
151
  """Evaluates the given variable when read by the given operation."""
@@ -202,14 +202,17 @@ class StackMemoryAnalyzer:
202
202
  return value
203
203
  return None
204
204
 
205
- def _compute_access(self, index: OpIndex, size: int) -> StackAccess | None:
205
+ def _compute_access(self, index: OpIndex, size: int) -> MemoryAccess | None:
206
206
  address = self.value_of(index, wrap(self.program.operations[index].inputs[1]))
207
- if isinstance(address, StackAddress):
208
- return StackAccess(address.offset, size)
207
+ match address:
208
+ case StackAddress(offset):
209
+ return MemoryAccess(True, offset, size)
210
+ case int(absolute):
211
+ return MemoryAccess(False, absolute, size)
209
212
  return None
210
213
 
211
- def _apply(self, index: OpIndex, state: StackState) -> StackState:
212
- """Returns the stack state after the given operation."""
214
+ def _apply(self, index: OpIndex, state: MemoryState) -> MemoryState:
215
+ """Returns the memory state after the given operation."""
213
216
 
214
217
  op = self.program.operations[index]
215
218
  if op.opcode == OpCode.STORE:
@@ -225,8 +228,8 @@ class StackMemoryAnalyzer:
225
228
  """Computes the definitions of the bytes read by each resolved load."""
226
229
 
227
230
  blocks = self.program.basic_blocks
228
- block_inputs: list[StackState | None] = [None] * len(blocks)
229
- block_inputs[0] = StackState({}, frozenset({EntryIndex}))
231
+ block_inputs: list[MemoryState | None] = [None] * len(blocks)
232
+ block_inputs[0] = MemoryState({}, frozenset({EntryIndex}))
230
233
  reads: dict[OpIndex, frozenset[OpIndex]] = {}
231
234
  pending = [0]
232
235
  queued = {0}
@@ -0,0 +1,119 @@
1
+ from typing import override
2
+
3
+ from pypcode import OpCode, PcodeOp
4
+
5
+ from pcode_graph.analysis.pass_base import PassBase
6
+ from pcode_graph.bit_utils import unsigned_to_signed
7
+ from pcode_graph.pcode import from_native_opcode
8
+
9
+ from .program import (
10
+ BasicBlock,
11
+ EntryIndex,
12
+ ExitIndex,
13
+ OpIndex,
14
+ Program,
15
+ UnknownCodeIndex,
16
+ Address,
17
+ )
18
+
19
+
20
+ class CFGBuilder(PassBase):
21
+
22
+ def __init__(self, program: Program) -> None:
23
+ super().__init__(program)
24
+
25
+ # First P-Code operation for each instruction address
26
+ self.addresses: dict[Address, OpIndex] = {}
27
+
28
+ def __call__(self):
29
+ # First collects instruction addresses encoded in IMARK operations
30
+ for i, op in enumerate(self.program.operations):
31
+ if op.opcode == OpCode.IMARK:
32
+ self.addresses[op.inputs[0].offset] = i
33
+
34
+ # Successors of jumping operations
35
+ self._jumps: dict[OpIndex, list[OpIndex]] = {}
36
+ for index, op in enumerate(self.program.operations):
37
+ self.visit(from_native_opcode(op.opcode), index, op)
38
+
39
+ op_count = len(self.program.operations)
40
+ leaders = {0} | {index + 1 for index in self._jumps}
41
+ for targets in self._jumps.values():
42
+ leaders.update(target for target in targets if target >= 0)
43
+ sorted_leaders = sorted(leaders - {op_count}) if op_count else []
44
+
45
+ self.program.basic_blocks = []
46
+ self.program.block_indexes = []
47
+ for start, end in zip(sorted_leaders, sorted_leaders[1:] + [op_count]):
48
+ self.program.block_indexes.extend(
49
+ [len(self.program.basic_blocks)] * (end - start)
50
+ )
51
+ self.program.basic_blocks.append(BasicBlock(start, end))
52
+
53
+ for block_index, block in enumerate(self.program.basic_blocks):
54
+ last_index = block.last_op_index
55
+ for successor in self._jumps.get(
56
+ last_index, [self._next_index(last_index)]
57
+ ):
58
+ if successor >= 0:
59
+ successor = self.program.block_indexes[successor]
60
+ self.program.basic_blocks[successor].pred_blocks.add(block_index)
61
+ block.succ_blocks.append(successor)
62
+
63
+ if self.program.basic_blocks:
64
+ self.program.basic_blocks[0].pred_blocks.add(EntryIndex)
65
+
66
+ def _next_index(self, index: OpIndex) -> OpIndex:
67
+ return index + 1 if index + 1 < len(self.program.operations) else ExitIndex
68
+
69
+ def _get_jump_target(self, index: OpIndex, op: PcodeOp) -> OpIndex:
70
+ address = op.inputs[0]
71
+ match address.space.name:
72
+ case "ram":
73
+ return self.addresses.get(address.offset, UnknownCodeIndex)
74
+ case "const":
75
+ # Relative jump inside the current instruction
76
+ target = index + unsigned_to_signed(address.offset, address.size)
77
+ assert 0 <= target < len(self.program.operations)
78
+ return target
79
+ case "register" | "unique":
80
+ return UnknownCodeIndex
81
+ case _ as name:
82
+ raise ValueError(f"Unexpected address space for jump address: {name}")
83
+
84
+ @override
85
+ def visit_default(self, index: OpIndex, op: PcodeOp) -> None:
86
+ pass
87
+
88
+ @override
89
+ def visit_branch(self, index: OpIndex, op: PcodeOp) -> None:
90
+ self._jumps[index] = [self._get_jump_target(index, op)]
91
+
92
+ @override
93
+ def visit_branchind(self, index: OpIndex, op: PcodeOp) -> None:
94
+ self._jumps[index] = [self._get_jump_target(index, op)]
95
+
96
+ @override
97
+ def visit_return(self, index: OpIndex, op: PcodeOp) -> None:
98
+ self._jumps[index] = [self._get_jump_target(index, op)]
99
+
100
+ @override
101
+ def visit_call(self, index: OpIndex, op: PcodeOp) -> None:
102
+ target = self._get_jump_target(index, op)
103
+ if target == UnknownCodeIndex:
104
+ # Calling an unseen function: we suppose it returns here after
105
+ self._jumps[index] = [target, self._next_index(index)]
106
+ else:
107
+ self._jumps[index] = [target]
108
+
109
+ @override
110
+ def visit_callind(self, index: OpIndex, op: PcodeOp) -> None:
111
+ self.visit_call(index, op)
112
+
113
+ @override
114
+ def visit_cbranch(self, index: OpIndex, op: PcodeOp) -> None:
115
+ self._jumps[index] = [self._get_jump_target(index, op), self._next_index(index)]
116
+
117
+ @override
118
+ def visit_callother(self, index: OpIndex, op: PcodeOp) -> None:
119
+ self._jumps[index] = [UnknownCodeIndex, self._next_index(index)]
@@ -0,0 +1,116 @@
1
+ import heapq
2
+
3
+ from .pass_base import PassBase
4
+ from .program import (
5
+ BasicBlock,
6
+ BlockIndex,
7
+ Definitions,
8
+ EntryIndex,
9
+ Var,
10
+ VarKinds,
11
+ wrap,
12
+ split,
13
+ apply_operation,
14
+ )
15
+
16
+
17
+ class ReachingDefBuilder(PassBase):
18
+
19
+ def __call__(self):
20
+ self.program.reaching_defs = [{} for _ in self.program.operations]
21
+ if not self.program.basic_blocks:
22
+ return
23
+
24
+ block_inputs: list[Definitions] = [{} for _ in self.program.basic_blocks]
25
+
26
+ # Initialize
27
+ for index in range(len(self.program.operations)):
28
+ if not self.program.reachable(index):
29
+ continue
30
+ for var in self.program.iter_inputs(index):
31
+ if var.kind == VarKinds.Register:
32
+ for byte in split(var):
33
+ block_inputs[0][byte] = {EntryIndex}
34
+
35
+ # Block effects are computed once, on demand, as (generated defs, killed variables)
36
+ effects: dict[BlockIndex, tuple[Definitions, set[Var]]] = {}
37
+
38
+ # Each reachable block is processed at least once, lowest index first:
39
+ # follows the code layout, close to a reverse post-order.
40
+ # The list is sorted, so it is already a valid heap.
41
+ pending = [
42
+ index
43
+ for index, block in enumerate(self.program.basic_blocks)
44
+ if block.reachable
45
+ ]
46
+ queued = set(pending)
47
+
48
+ while pending:
49
+ block_index = heapq.heappop(pending)
50
+ queued.remove(block_index)
51
+
52
+ if block_index not in effects:
53
+ effects[block_index] = self._compute_effect(
54
+ self.program.basic_blocks[block_index]
55
+ )
56
+ generated, killed = effects[block_index]
57
+ outputs = self._apply_effect(block_inputs[block_index], generated, killed)
58
+
59
+ for successor in self.program.basic_blocks[block_index].succ_blocks:
60
+ if successor < 0:
61
+ continue
62
+ changed = self._merge_definitions(block_inputs[successor], outputs)
63
+ if changed and successor not in queued:
64
+ heapq.heappush(pending, successor)
65
+ queued.add(successor)
66
+
67
+ for block, inputs in zip(self.program.basic_blocks, block_inputs):
68
+ if block.reachable:
69
+ self._expand_block(block, inputs)
70
+
71
+ def _compute_effect(self, block: BasicBlock) -> tuple[Definitions, set[Var]]:
72
+ generated: Definitions = {}
73
+ killed: set[Var] = set()
74
+ for index in block.op_indexes:
75
+ op = self.program.operations[index]
76
+ if op.output:
77
+ written = {index}
78
+ for byte in split(wrap(op.output)):
79
+ generated[byte] = written
80
+ killed.add(byte)
81
+ return generated, killed
82
+
83
+ @staticmethod
84
+ def _apply_effect(
85
+ inputs: Definitions, generated: Definitions, killed: set[Var]
86
+ ) -> Definitions:
87
+ # Sets are never modified in place, so they can be shared
88
+ outputs = dict(generated)
89
+ for var, defs in inputs.items():
90
+ if var in killed:
91
+ continue
92
+ outputs[var] = outputs[var] | defs if var in outputs else defs
93
+ return outputs
94
+
95
+ def _expand_block(self, block: BasicBlock, inputs: Definitions):
96
+ """Computes the definitions reaching each operation of the block."""
97
+
98
+ current = inputs
99
+ for index in block.op_indexes:
100
+ self.program.reaching_defs[index] = current
101
+ current = apply_operation(current, index, self.program.operations[index])
102
+
103
+ @staticmethod
104
+ def _merge_definitions(target: Definitions, source: Definitions) -> bool:
105
+ """Adds source definitions to target ones, returns True if target changed."""
106
+
107
+ changed = False
108
+ for var, defs in source.items():
109
+ target_defs = target.get(var)
110
+ if target_defs is None:
111
+ target[var] = set(defs)
112
+ changed = True
113
+ elif not defs <= target_defs:
114
+ target_defs |= defs
115
+ changed = True
116
+ return changed
@@ -0,0 +1,164 @@
1
+ """Rewrites direct accesses to "ram" varnodes into explicit LOAD and STORE operations.
2
+
3
+ P-Code may read or write a static memory address directly, as for PC-relative accesses.
4
+ Once rewritten, memory is only accessed through LOAD and STORE.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from typing import Any, cast
9
+
10
+ from pypcode import OpCode, PcodeOp
11
+
12
+ from .native_pcode import (
13
+ CONST_SPACE,
14
+ JUMP_OPCODES,
15
+ RELATIVE_JUMP_OPCODES,
16
+ UNIQUE_SPACE,
17
+ SyntheticOperation,
18
+ SyntheticVarnode,
19
+ is_data_input,
20
+ )
21
+ from .program import Program
22
+
23
+ from .pass_base import PassBase
24
+ from pcode_graph.bit_utils import signed_to_unsigned, unsigned_to_signed
25
+
26
+
27
+ def _relative_jump_target(index: int, operation: PcodeOp) -> int | None:
28
+ if operation.opcode not in RELATIVE_JUMP_OPCODES:
29
+ return None
30
+ address = operation.inputs[0]
31
+ if address.space.name != "const":
32
+ return None
33
+ return index + unsigned_to_signed(address.offset, address.size)
34
+
35
+
36
+ class LoadStoreInserter(PassBase):
37
+
38
+ def __init__(self, program: Program) -> None:
39
+
40
+ super().__init__(program)
41
+
42
+ self.pointer_size = self.program.arch.pointer_size
43
+ self.next_unique_offset = max(
44
+ (
45
+ varnode.offset + varnode.size
46
+ for operation in self.operations
47
+ for varnode in [operation.output, *operation.inputs]
48
+ if varnode is not None and varnode.space.name == "unique"
49
+ ),
50
+ default=0,
51
+ )
52
+ # Temporaries holding the value of static addresses, by (address, size)
53
+ self.cached_values: dict[tuple[int, int], SyntheticVarnode] = {}
54
+
55
+ @property
56
+ def operations(self):
57
+ return self.program.operations
58
+
59
+ def __call__(self):
60
+ jump_targets = {
61
+ index: target
62
+ for index, operation in enumerate(self.operations)
63
+ if (target := _relative_jump_target(index, operation)) is not None
64
+ }
65
+ reached_by_jump = set(jump_targets.values())
66
+
67
+ expansions: list[list[Any]] = []
68
+ for index, operation in enumerate(self.operations):
69
+ # Cached values are only reused inside straight-line code
70
+ if index in reached_by_jump or operation.opcode == OpCode.IMARK:
71
+ self.cached_values.clear()
72
+ expansions.append(self._expand(operation))
73
+ if operation.opcode in JUMP_OPCODES:
74
+ self.cached_values.clear()
75
+
76
+ starts = [0]
77
+ for expansion in expansions:
78
+ starts.append(starts[-1] + len(expansion))
79
+
80
+ # Relative jumps inside an instruction are shifted by inserted operations
81
+ for index, target in jump_targets.items():
82
+ expansion = expansions[index]
83
+ (position,) = [
84
+ position
85
+ for position, operation in enumerate(expansion)
86
+ if operation.opcode in RELATIVE_JUMP_OPCODES
87
+ ]
88
+ jump = expansion[position]
89
+ offset = starts[target] - (starts[index] + position)
90
+ address = jump.inputs[0]
91
+ if offset != unsigned_to_signed(address.offset, address.size):
92
+ new_address = SyntheticVarnode(
93
+ CONST_SPACE, signed_to_unsigned(offset, address.size), address.size
94
+ )
95
+ expansion[position] = SyntheticOperation(
96
+ jump.opcode, [new_address, *jump.inputs[1:]], jump.output
97
+ )
98
+
99
+ self.program.operations = cast(
100
+ list[PcodeOp], [op for expansion in expansions for op in expansion]
101
+ )
102
+
103
+ def _expand(self, operation: PcodeOp) -> list[Any]:
104
+ """Returns the operations replacing the given one."""
105
+
106
+ expansion: list[Any] = []
107
+ inputs = list(operation.inputs)
108
+ changed = False
109
+ for position, varnode in enumerate(operation.inputs):
110
+ if varnode.space.name != "ram" or not is_data_input(
111
+ operation.opcode, position
112
+ ):
113
+ continue
114
+ key = (varnode.offset, varnode.size)
115
+ temporary = self.cached_values.get(key)
116
+ if temporary is None:
117
+ temporary = self._new_temporary(varnode.size)
118
+ expansion.append(
119
+ SyntheticOperation(
120
+ OpCode.LOAD,
121
+ [self._space_id(), self._address(varnode.offset)],
122
+ temporary,
123
+ )
124
+ )
125
+ self.cached_values[key] = temporary
126
+ inputs[position] = temporary # type: ignore
127
+ changed = True
128
+
129
+ output = operation.output
130
+ store = None
131
+ if output is not None and output.space.name == "ram":
132
+ written = range(output.offset, output.offset + output.size)
133
+ for address, size in list(self.cached_values):
134
+ if address < written.stop and written.start < address + size:
135
+ del self.cached_values[(address, size)]
136
+ temporary = self._new_temporary(output.size)
137
+ self.cached_values[(output.offset, output.size)] = temporary
138
+ store = SyntheticOperation(
139
+ OpCode.STORE,
140
+ [self._space_id(), self._address(output.offset), temporary],
141
+ None,
142
+ )
143
+ output = temporary
144
+ changed = True
145
+
146
+ expansion.append(
147
+ SyntheticOperation(operation.opcode, inputs, output)
148
+ if changed
149
+ else operation
150
+ )
151
+ if store is not None:
152
+ expansion.append(store)
153
+ return expansion
154
+
155
+ def _new_temporary(self, size: int) -> SyntheticVarnode:
156
+ temporary = SyntheticVarnode(UNIQUE_SPACE, self.next_unique_offset, size)
157
+ self.next_unique_offset += size
158
+ return temporary
159
+
160
+ def _space_id(self) -> SyntheticVarnode:
161
+ return SyntheticVarnode(CONST_SPACE, 0, self.pointer_size)
162
+
163
+ def _address(self, address: int) -> SyntheticVarnode:
164
+ return SyntheticVarnode(CONST_SPACE, address, self.pointer_size)
@@ -0,0 +1,78 @@
1
+ """Helpers to deal with pypcode native operations.
2
+ """
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ import pypcode
8
+
9
+ # Operations whose first input is not a data value (code address, space or user operation id)
10
+ NON_DATA_FIRST_INPUT_OPCODES = frozenset(
11
+ {
12
+ pypcode.OpCode.CBRANCH,
13
+ pypcode.OpCode.BRANCH,
14
+ pypcode.OpCode.CALL,
15
+ pypcode.OpCode.LOAD,
16
+ pypcode.OpCode.STORE,
17
+ pypcode.OpCode.CALLOTHER,
18
+ }
19
+ )
20
+
21
+ JUMP_OPCODES = {
22
+ pypcode.OpCode.BRANCH,
23
+ pypcode.OpCode.BRANCHIND,
24
+ pypcode.OpCode.CALL,
25
+ pypcode.OpCode.CALLIND,
26
+ pypcode.OpCode.CBRANCH,
27
+ pypcode.OpCode.RETURN,
28
+ pypcode.OpCode.CALLOTHER,
29
+ }
30
+
31
+ RELATIVE_JUMP_OPCODES = frozenset({pypcode.OpCode.BRANCH, pypcode.OpCode.CBRANCH})
32
+
33
+
34
+ def is_data_input(opcode: pypcode.OpCode, position: int) -> bool:
35
+ """Tells whether the given input of an operation is a value read by this operation."""
36
+
37
+ if opcode == pypcode.OpCode.IMARK:
38
+ return False
39
+ return position != 0 or opcode not in NON_DATA_FIRST_INPUT_OPCODES
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class SyntheticSpace:
44
+ name: str
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class SyntheticVarnode:
49
+ """Mimics the parts of pypcode.Varnode used by the analyses."""
50
+
51
+ space: SyntheticSpace
52
+ offset: int
53
+ size: int
54
+
55
+ def getRegisterName(self) -> str:
56
+ return ""
57
+
58
+
59
+ @dataclass(slots=True)
60
+ class SyntheticOperation:
61
+ """Mimics the parts of pypcode.PcodeOp used by the analyses."""
62
+
63
+ opcode: pypcode.OpCode
64
+ inputs: list[Any]
65
+ output: Any
66
+
67
+
68
+ CONST_SPACE = SyntheticSpace("const")
69
+ UNIQUE_SPACE = SyntheticSpace("unique")
70
+
71
+
72
+ def accesses_ram(operation: pypcode.PcodeOp) -> bool:
73
+ if operation.output is not None and operation.output.space.name == "ram":
74
+ return True
75
+ return any(
76
+ varnode.space.name == "ram" and is_data_input(operation.opcode, position)
77
+ for position, varnode in enumerate(operation.inputs)
78
+ )
@@ -0,0 +1,9 @@
1
+ from pcode_graph.analysis.program import Program
2
+ from pcode_graph.visitor import PcodeVisitor
3
+
4
+
5
+ class PassBase(PcodeVisitor):
6
+
7
+ def __init__(self, program: Program) -> None:
8
+ super().__init__()
9
+ self.program = program