The world's first agentic reverse engineer.
add symbolic analysis!
Amruthe0a1aff09c44
diff --git a/kong/llm/__init__.py b/kong/llm/__init__.pyindex b8dfc4d..d9b14f1 100644--- a/kong/llm/__init__.py+++ b/kong/llm/__init__.py@@ -1,5 +1,6 @@"""LLM integration layer."""from kong.llm.client import AnthropicClient, TokenUsage+from kong.llm.tools import DEOBFUSCATION_TOOLS, ToolExecutor-__all__ = ["AnthropicClient", "TokenUsage"]+__all__ = ["AnthropicClient", "DEOBFUSCATION_TOOLS", "TokenUsage", "ToolExecutor"]diff --git a/kong/llm/client.py b/kong/llm/client.pyindex 4d03158..5053e9a 100644--- a/kong/llm/client.py+++ b/kong/llm/client.py@@ -1,19 +1,21 @@"""Anthropic SDK wrapper for function analysis.Implements the LLMClient protocol expected by the Analyzer.-Tracks token usage and cost per call.+Tracks token usage and cost per call. Supports both simple+(single-shot JSON) and tool-use (agentic loop) interactions."""from __future__ import annotationsimport logging-import time-from dataclasses import dataclass, field+from dataclasses import dataclass+from typing import Anyimport anthropicfrom kong.agent.analyzer import Analyzer, LLMResponsefrom kong.agent.prompts import OUTPUT_SCHEMA, SYSTEM_PROMPT+from kong.llm.tools import ToolExecutorlogger = logging.getLogger(__name__)@@ -50,9 +52,11 @@ class AnthropicClient:Satisfies the LLMClient protocol from kong.agent.analyzer.- Usage:+ Usage::+client = AnthropicClient()response = client.analyze_function(prompt)+ response = client.analyze_with_tools(prompt, system, tools, executor)"""def __init__(@@ -67,7 +71,7 @@ class AnthropicClient:self.usage = TokenUsage()def analyze_function(self, prompt: str) -> LLMResponse:- """Send an analysis prompt and return parsed response."""+ """Send an analysis prompt and return parsed response (no tools)."""message = self._client.messages.create(model=self.model,max_tokens=self.max_tokens,@@ -80,30 +84,99 @@ class AnthropicClient:],)- raw_text = ""- for block in message.content:- if block.type == "text":- raw_text += block.text-- input_tokens = message.usage.input_tokens- output_tokens = message.usage.output_tokens-- self.usage.input_tokens += input_tokens- self.usage.output_tokens += output_tokens- self.usage.calls += 1+ raw_text = self._extract_text(message)+ self._record_usage(message)- logger.debug(- "LLM call: %d in / %d out tokens (total: %d calls, $%.4f)",- input_tokens, output_tokens,- self.usage.calls, self.usage.cost_usd(self.model),- )+ response = Analyzer.parse_llm_json(raw_text)+ response.input_tokens = message.usage.input_tokens+ response.output_tokens = message.usage.output_tokens+ response.raw = raw_text+ return response+ def analyze_with_tools(+ self,+ prompt: str,+ system: str,+ tools: list[dict[str, Any]],+ tool_executor: ToolExecutor,+ max_rounds: int = 10,+ ) -> LLMResponse:+ """Run an agentic tool-use loop.++ Sends the prompt with tool definitions. When the model returns+ ``tool_use`` blocks, executes each tool via *tool_executor* and+ feeds results back. Repeats until the model returns a final text+ response or *max_rounds* is exhausted.+ """+ messages: list[dict[str, Any]] = [+ {"role": "user", "content": f"{prompt}\n\n{OUTPUT_SCHEMA}"},+ ]++ total_input = 0+ total_output = 0++ for _ in range(max_rounds):+ message = self._client.messages.create(+ model=self.model,+ max_tokens=self.max_tokens,+ system=system,+ tools=tools,+ messages=messages,+ )++ total_input += message.usage.input_tokens+ total_output += message.usage.output_tokens+ self._record_usage(message)++ if message.stop_reason != "tool_use":+ raw_text = self._extract_text(message)+ response = Analyzer.parse_llm_json(raw_text)+ response.input_tokens = total_input+ response.output_tokens = total_output+ response.raw = raw_text+ return response++ messages.append({"role": "assistant", "content": message.content})++ tool_results: list[dict[str, Any]] = []+ for block in message.content:+ if block.type != "tool_use":+ continue+ result_str = tool_executor.execute(block.name, block.input)+ tool_results.append({+ "type": "tool_result",+ "tool_use_id": block.id,+ "content": result_str,+ })++ messages.append({"role": "user", "content": tool_results})++ raw_text = self._extract_text(message)response = Analyzer.parse_llm_json(raw_text)- response.input_tokens = input_tokens- response.output_tokens = output_tokens+ response.input_tokens = total_input+ response.output_tokens = total_outputresponse.raw = raw_textreturn response@propertydef total_cost_usd(self) -> float:return self.usage.cost_usd(self.model)++ def _extract_text(self, message: Any) -> str:+ parts: list[str] = []+ for block in message.content:+ if block.type == "text":+ parts.append(block.text)+ return "".join(parts)++ def _record_usage(self, message: Any) -> None:+ self.usage.input_tokens += message.usage.input_tokens+ self.usage.output_tokens += message.usage.output_tokens+ self.usage.calls += 1+ logger.debug(+ "LLM call: %d in / %d out tokens (total: %d calls, $%.4f)",+ message.usage.input_tokens,+ message.usage.output_tokens,+ self.usage.calls,+ self.usage.cost_usd(self.model),+ )diff --git a/kong/llm/tools.py b/kong/llm/tools.pynew file mode 100644index 0000000..1715287--- /dev/null+++ b/kong/llm/tools.py@@ -0,0 +1,343 @@+"""Tool definitions and executor for LLM-driven deobfuscation.++Defines the Anthropic tool schemas exposed to the LLM during deobfuscation+analysis, and the ToolExecutor that dispatches calls to the symbolic tools.+"""++from __future__ import annotations++import json+import logging+from dataclasses import dataclass, field+from typing import Any, TYPE_CHECKING++from kong.symbolic.dead_code import ResolvedPredicate, Resolution, eliminate_dead_code+from kong.symbolic.simplifier import simplify_expression++if TYPE_CHECKING:+ from kong.ghidra.client import GhidraClient++logger = logging.getLogger(__name__)+++ToolSchema = dict[str, Any]+++DEOBFUSCATION_TOOLS: list[ToolSchema] = [+ {+ "name": "simplify_expression",+ "description": (+ "Simplify a C-style arithmetic or boolean expression using z3. "+ "Detects opaque predicates (expressions that are always true or "+ "always false for all inputs). Use this on suspicious branch "+ "conditions to identify dead code."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "expression": {+ "type": "string",+ "description": (+ "A C-style expression to simplify, e.g. "+ "'(x * (x + 1)) % 2 == 0'"+ ),+ },+ "bit_width": {+ "type": "integer",+ "description": "Bit width for integer variables (default: 32).",+ },+ },+ "required": ["expression"],+ },+ },+ {+ "name": "eliminate_dead_code",+ "description": (+ "Remove dead branches from decompiled C code given a list of "+ "resolved opaque predicates. For always-true predicates, the else "+ "branch is removed. For always-false predicates, the if body is "+ "removed."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "decompiled_code": {+ "type": "string",+ "description": "The decompiled C source code to clean up.",+ },+ "resolved_predicates": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "expression": {+ "type": "string",+ "description": "The predicate expression text.",+ },+ "resolution": {+ "type": "string",+ "enum": ["always_true", "always_false"],+ "description": "Whether the predicate is always true or always false.",+ },+ },+ "required": ["expression", "resolution"],+ },+ "description": "List of predicates that have been resolved.",+ },+ },+ "required": ["decompiled_code", "resolved_predicates"],+ },+ },+ {+ "name": "trace_state_machine",+ "description": (+ "Trace CFF (control flow flattening) state transitions in a "+ "function using Ghidra's IR. Returns the state transition graph "+ "including states, transitions, entry state, and exit states. "+ "Use this when you detect a while(1)/switch(state) pattern."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "function_address": {+ "type": "integer",+ "description": "Address of the function to trace (as integer).",+ },+ "state_variable": {+ "type": "string",+ "description": (+ "Name of the state variable in the decompiled code "+ "(e.g. 'local_10', 'state')."+ ),+ },+ },+ "required": ["function_address", "state_variable"],+ },+ },+ {+ "name": "identify_crypto_constants",+ "description": (+ "Scan a function's decompilation for known cryptographic constants "+ "(AES S-box values, RC4 initialization, SHA-256 initial hash values, "+ "etc.). Returns any matches found."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "function_address": {+ "type": "integer",+ "description": "Address of the function to scan.",+ },+ },+ "required": ["function_address"],+ },+ },+ {+ "name": "get_decompilation",+ "description": (+ "Fetch the current decompiled C source for a function from Ghidra. "+ "Useful to re-read decompilation after Ghidra state changes."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "function_address": {+ "type": "integer",+ "description": "Address of the function to decompile.",+ },+ },+ "required": ["function_address"],+ },+ },+ {+ "name": "get_basic_blocks",+ "description": (+ "Get the basic blocks and control flow graph of a function. "+ "Returns blocks with their instructions and edges between blocks."+ ),+ "input_schema": {+ "type": "object",+ "properties": {+ "function_address": {+ "type": "integer",+ "description": "Address of the function to analyze.",+ },+ },+ "required": ["function_address"],+ },+ },+]+++_CRYPTO_CONSTANTS: dict[str, list[str]] = {+ "AES S-box": ["0x63", "0x7c", "0x77", "0x7b", "0xf2", "0x6b", "0x6f", "0xc5"],+ "AES inverse S-box": ["0x52", "0x09", "0x6a", "0xd5", "0x30", "0x36", "0xa5", "0x38"],+ "AES round constants": ["0x01", "0x02", "0x04", "0x08", "0x10", "0x20", "0x40", "0x80", "0x1b", "0x36"],+ "RC4 KSA": ["0x100"],+ "SHA-256 initial hash": [+ "0x6a09e667", "0xbb67ae85", "0x3c6ef372", "0xa54ff53a",+ "0x510e527f", "0x9b05688c", "0x1f83d9ab", "0x5be0cd19",+ ],+ "SHA-256 round constants": [+ "0x428a2f98", "0x71374491", "0xb5c0fbcf", "0xe9b5dba5",+ ],+ "MD5 T-values": ["0xd76aa478", "0xe8c7b756", "0x242070db", "0xc1bdceee"],+ "CRC32 polynomial": ["0xedb88320", "0x04c11db7"],+ "TEA delta": ["0x9e3779b9"],+}+++@dataclass+class ToolCallRecord:+ tool_name: str+ tool_input: dict[str, Any]+ result: str+++class ToolExecutor:+ """Executes tool calls from the LLM, dispatching to symbolic tools."""++ def __init__(self, ghidra_client: GhidraClient) -> None:+ self.client = ghidra_client+ self.call_log: list[ToolCallRecord] = field(default_factory=list)+ self.call_log = []++ @property+ def call_count(self) -> int:+ return len(self.call_log)++ def execute(self, tool_name: str, tool_input: dict[str, Any]) -> str:+ """Execute a tool call and return the result as a string."""+ logger.debug("Tool call: %s(%s)", tool_name, tool_input)+ try:+ result = self._dispatch(tool_name, tool_input)+ except Exception as e:+ result = f"Error executing {tool_name}: {e}"+ logger.warning("Tool execution error: %s", result)++ self.call_log.append(ToolCallRecord(+ tool_name=tool_name,+ tool_input=tool_input,+ result=result,+ ))+ return result++ def _dispatch(self, tool_name: str, tool_input: dict[str, Any]) -> str:+ if tool_name == "simplify_expression":+ return self._simplify_expression(tool_input)+ if tool_name == "eliminate_dead_code":+ return self._eliminate_dead_code(tool_input)+ if tool_name == "trace_state_machine":+ return self._trace_state_machine(tool_input)+ if tool_name == "identify_crypto_constants":+ return self._identify_crypto_constants(tool_input)+ if tool_name == "get_decompilation":+ return self._get_decompilation(tool_input)+ if tool_name == "get_basic_blocks":+ return self._get_basic_blocks(tool_input)+ return f"Unknown tool: {tool_name}"++ def _simplify_expression(self, inputs: dict[str, Any]) -> str:+ expr = inputs["expression"]+ bit_width = inputs.get("bit_width", 32)+ result = simplify_expression(expr, bit_width=bit_width)+ return json.dumps({+ "original": result.original,+ "simplified": result.simplified,+ "is_opaque_predicate": result.is_opaque,+ "predicate_kind": result.predicate_kind.value,+ "error": result.error,+ })++ def _eliminate_dead_code(self, inputs: dict[str, Any]) -> str:+ code = inputs["decompiled_code"]+ preds = [+ ResolvedPredicate(+ expression=p["expression"],+ resolution=Resolution(p["resolution"]),+ )+ for p in inputs["resolved_predicates"]+ ]+ cleaned = eliminate_dead_code(code, preds)+ return cleaned++ def _trace_state_machine(self, inputs: dict[str, Any]) -> str:+ from kong.symbolic.state_machine import trace_state_machine++ func_addr = inputs["function_address"]+ state_var = inputs["state_variable"]+ result = trace_state_machine(self.client, func_addr, state_var)+ return json.dumps({+ "states": [hex(s) for s in result.states],+ "transitions": [+ {+ "from": hex(t.from_state),+ "to": hex(t.to_state),+ "condition": t.condition,+ }+ for t in result.transitions+ ],+ "entry_state": hex(result.entry_state),+ "exit_states": [hex(s) for s in result.exit_states],+ "state_count": result.state_count,+ "linear_chains": [+ [hex(s) for s in chain]+ for chain in result.linear_chains()+ ],+ "error": result.error,+ })++ def _identify_crypto_constants(self, inputs: dict[str, Any]) -> str:+ func_addr = inputs["function_address"]+ try:+ decomp = self.client.get_decompilation(func_addr)+ except Exception as e:+ return json.dumps({"error": str(e), "matches": []})++ matches: list[dict[str, str]] = []+ decomp_lower = decomp.lower()+ for algo, constants in _CRYPTO_CONSTANTS.items():+ found = [c for c in constants if c.lower() in decomp_lower]+ if len(found) >= 2 or (len(found) >= 1 and len(constants) <= 2):+ matches.append({+ "algorithm": algo,+ "matched_constants": found,+ "total_constants": len(constants),+ })+ return json.dumps({"matches": matches})++ def _get_decompilation(self, inputs: dict[str, Any]) -> str:+ func_addr = inputs["function_address"]+ try:+ return self.client.get_decompilation(func_addr)+ except Exception as e:+ return f"Error: {e}"++ def _get_basic_blocks(self, inputs: dict[str, Any]) -> str:+ func_addr = inputs["function_address"]+ try:+ cfg = self.client.get_control_flow_graph(func_addr)+ except Exception as e:+ return json.dumps({"error": str(e)})+ return json.dumps({+ "function_address": hex(cfg.function_addr),+ "block_count": cfg.block_count,+ "blocks": [+ {+ "start": hex(b.start_addr),+ "end": hex(b.end_addr),+ "instructions": b.instructions,+ "successors": [hex(s) for s in cfg.successors(b.start_addr)],+ "predecessors": [hex(p) for p in cfg.predecessors(b.start_addr)],+ }+ for b in cfg.blocks+ ],+ "edges": [+ {+ "from": hex(e.from_addr),+ "to": hex(e.to_addr),+ "type": e.edge_type.value,+ }+ for e in cfg.edges+ ],+ })diff --git a/kong/patterns/bogus_cf.md b/kong/patterns/bogus_cf.mdnew file mode 100644index 0000000..252e77b--- /dev/null+++ b/kong/patterns/bogus_cf.md@@ -0,0 +1,88 @@+# Bogus Control Flow (BCF)++## What It Looks Like++Fake branches are injected into the function using conditions that always evaluate to the same value (opaque predicates). The "dead" branch typically contains junk code or cloned/modified copies of real code. The function's actual logic is unchanged, but the control flow graph becomes much larger and harder to follow.++## Identification++- Conditions that are always true or always false for any input — opaque predicates+- Common opaque predicate patterns:+ - `(x * (x + 1)) % 2 == 0` — always true (product of consecutive integers is even)+ - `(x * x) % 2 == x % 2` — always true+ - `(x ^ x) != 0` — always false+ - `(x & ~x) != 0` — always false+ - `(x | ~x) == -1` — always true+ - Conditions involving global variables that are never written to+- Dead branches often contain:+ - Unreachable code that still references valid addresses+ - Copies of nearby code with slight modifications+ - Random-looking arithmetic that never produces visible side effects++## Example 1: Simple Opaque Predicate++### Before (obfuscated)++```c+int FUN_00401000(int a, int b) {+ int result;+ if ((a * (a + 1)) % 2 == 0) {+ result = a + b;+ } else {+ result = a ^ b ^ 0xDEAD; // unreachable+ }+ if ((b & ~b) != 0) {+ result ^= 0xBEEF; // unreachable+ }+ return result;+}+```++### After (recovered)++```c+int add_values(int a, int b) {+ return a + b;+}+```++## Example 2: Multiple Opaque Predicates++### Before (obfuscated)++```c+void FUN_00402000(char *buf, int len) {+ int i = 0;+ while (i < len) {+ if ((i * (i - 1)) % 2 != 0) {+ buf[i] = buf[i] ^ buf[i-1] ^ 0xFF; // unreachable+ }+ buf[i] = buf[i] ^ 0x42;+ if ((i | ~i) == 0) {+ break; // unreachable+ }+ i++;+ }+}+```++### After (recovered)++```c+void xor_buf(char *buf, int len) {+ for (int i = 0; i < len; i++) {+ buf[i] ^= 0x42;+ }+}+```++## Recovery Strategy++1. **Scan all branch conditions** in the function+2. **Use tool: `simplify_expression`** on each condition to check for opaque predicates+3. **For each resolved predicate:**+ - If always true → keep the "then" branch, discard the "else" branch+ - If always false → keep the "else" branch (if any), discard the "then" branch+4. **Use tool: `eliminate_dead_code`** to remove the unreachable branches from the decompilation+5. **Re-analyze the simplified code** — with dead branches removed, the function's real logic is exposed+6. **Name and type** based on the cleaned control flowdiff --git a/kong/patterns/cff.md b/kong/patterns/cff.mdnew file mode 100644index 0000000..227bdbf--- /dev/null+++ b/kong/patterns/cff.md@@ -0,0 +1,109 @@+# Control Flow Flattening (CFF)++## What It Looks Like++A function's natural control flow is replaced with a single `while(1)` / `switch(state)` loop. Every basic block becomes a case in the switch, and an integer "state variable" determines which block executes next. The state variable is reassigned at the end of every case to route to the next block.++## Identification++- Single `while(1)`, `while(true)`, or `for(;;)` wrapping the entire function body+- Large `switch` statement inside the loop (often 5+ cases)+- Integer local variable reassigned in every case — this is the state variable+- No natural `if`/`else` or loop structures outside the switch+- State values are typically large hex constants (e.g., `0x3a2b`, `0x9e22`)+- The function entry assigns the initial state before the loop++## Example 1: XOR Decrypt++### Before (obfuscated)++```c+void FUN_004015a0(int *data, int len) {+ int state = 0x3a2b;+ while (1) {+ switch (state) {+ case 0x3a2b:+ if (len <= 0) { state = 0x9e22; }+ else { state = 0x7f01; }+ break;+ case 0x7f01:+ data[0] ^= 0x55;+ state = 0x1c44;+ break;+ case 0x1c44:+ data++;+ len--;+ state = 0x3a2b;+ break;+ case 0x9e22:+ return;+ }+ }+}+```++### After (recovered)++```c+void xor_decrypt(int *data, int len) {+ for (int i = 0; i < len; i++) {+ data[i] ^= 0x55;+ }+}+```++## Example 2: Linked List Search++### Before (obfuscated)++```c+void *FUN_00401200(void *list, int key) {+ int state = 0xa100;+ void *node = list;+ while (1) {+ switch (state) {+ case 0xa100:+ if (node == NULL) { state = 0xd300; }+ else { state = 0xb200; }+ break;+ case 0xb200:+ if (*(int *)node == key) { state = 0xe400; }+ else { state = 0xc300; }+ break;+ case 0xc300:+ node = *(void **)((char *)node + 8);+ state = 0xa100;+ break;+ case 0xd300:+ return NULL;+ case 0xe400:+ return node;+ }+ }+}+```++### After (recovered)++```c+void *linked_list_find(void *list, int key) {+ for (void *node = list; node != NULL; node = *(void **)((char *)node + 8)) {+ if (*(int *)node == key) {+ return node;+ }+ }+ return NULL;+}+```++## Recovery Strategy++1. **Identify the state variable** — the local integer reassigned in every switch case+2. **Use tool: `trace_state_machine`** to extract the state transition graph automatically+3. **Trace state transitions** — for each case, record `(current_state → next_state)` and any associated condition+4. **Build a state transition graph** from the extracted data+5. **Collapse linear chains** — consecutive states with unconditional transitions become sequential statements+6. **Identify conditional branches** — cases where the next state depends on a condition become `if`/`else`+7. **Identify loops** — cycles in the state graph become `while` or `for` loops+8. **Reconstruct structured code** — map the graph back to `if`/`else`, `while`, `for` constructs+9. **Name and type** the function based on the recovered logicdiff --git a/kong/patterns/instruction_sub.md b/kong/patterns/instruction_sub.mdnew file mode 100644index 0000000..eee7d56--- /dev/null+++ b/kong/patterns/instruction_sub.md@@ -0,0 +1,84 @@+# Instruction Substitution++## What It Looks Like++Simple arithmetic and logical operations are replaced with equivalent but more complex expressions using mathematical identities. The function's logic is preserved, but each operation becomes harder to understand at a glance.++## Identification++- Unnecessarily complex arithmetic where a simpler equivalent exists+- Multiple operations used where one would suffice+- Common substitution patterns:+ - `a + b` → `(a ^ b) + 2 * (a & b)`+ - `a - b` → `a + (~b + 1)`+ - `a ^ b` → `(a | b) & ~(a & b)` or `(~a & b) | (a & ~b)`+ - `a | b` → `(a & ~b) | b`+ - `a & b` → `(~(~a | ~b))`+ - `-a` → `~a + 1`+ - Boolean NOT: `!a` → `a ^ 1` or `(a + 1) & 1`+- These patterns nest: a substituted expression may itself contain substituted sub-expressions, creating deeply nested arithmetic++## Example 1: XOR via AND/OR++### Before (obfuscated)++```c+int FUN_00403000(int a, int b) {+ return (~a & b) | (a & ~b);+}+```++### After (recovered)++```c+int xor_values(int a, int b) {+ return a ^ b;+}+```++## Example 2: Addition via XOR/AND++### Before (obfuscated)++```c+int FUN_00403100(int x, int y) {+ int t1 = x ^ y;+ int t2 = x & y;+ int t3 = t2 << 1;+ return (t1 ^ t3) + 2 * (t1 & t3);+}+```++### After (recovered)++```c+int add(int x, int y) {+ return x + y;+}+```++## Example 3: Negation Chain++### Before (obfuscated)++```c+int FUN_00403200(int val) {+ return (~val + 1) + (~val + 1);+}+```++### After (recovered)++```c+int negate_double(int val) {+ return -2 * val;+}+```++## Recovery Strategy++1. **Extract all arithmetic expressions** from the decompiled function+2. **Use tool: `simplify_expression`** on each expression — z3 will reduce equivalent forms to canonical representations+3. **Replace complex expressions** with their simplified equivalents in the decompilation+4. **Look for patterns** — if a function is just `return simplified_expr`, the function's purpose becomes immediately clear+5. **Name and type** based on the simplified operationsdiff --git a/kong/patterns/string_encrypt.md b/kong/patterns/string_encrypt.mdnew file mode 100644index 0000000..be1cb4e--- /dev/null+++ b/kong/patterns/string_encrypt.md@@ -0,0 +1,77 @@+# String Encryption++## What It Looks Like++String literals are encrypted at compile time and decrypted at runtime just before use. Instead of seeing `"Hello, World!"` in the decompilation, you see a function that XORs a byte array with a key, or runs RC4 over an encrypted blob, then passes the result to the original call site.++## Identification++- Byte arrays initialized with non-ASCII / non-printable data used as function arguments where strings are expected+- XOR loops that iterate over a local/global byte array before passing it to `printf`, `strcmp`, `puts`, etc.+- Calls to small helper functions that take encrypted data + key and return `char *`+- Common patterns:+ - Single-byte XOR: `for (i = 0; i < len; i++) buf[i] ^= key;`+ - Multi-byte XOR: `for (i = 0; i < len; i++) buf[i] ^= key[i % key_len];`+ - RC4 decryption: KSA + PRGA applied to a byte array+ - Stack strings: characters pushed one-by-one onto the stack (e.g., `buf[0]='H'; buf[1]='e'; ...`)+ - Base64 decode followed by XOR++## Example 1: Single-Byte XOR++### Before (obfuscated)++```c+void FUN_00404000(void) {+ char buf[14] = { 0x2a, 0x27, 0x2e, 0x2e, 0x29, 0x4e, 0x42, 0x3f, 0x29, 0x36, 0x2e, 0x26, 0x43, 0x42 };+ for (int i = 0; i < 14; i++) {+ buf[i] ^= 0x42;+ }+ puts(buf);+}+```++### After (recovered)++```c+void print_greeting(void) {+ // Decrypted string: "Hello, World!\0"+ puts("Hello, World!");+}+```++## Example 2: Decryption Helper++### Before (obfuscated)++```c+char *FUN_00404100(unsigned char *data, int len, unsigned char key) {+ char *result = malloc(len + 1);+ for (int i = 0; i < len; i++) {+ result[i] = data[i] ^ key;+ }+ result[len] = 0;+ return result;+}+```++### After (recovered)++```c+char *xor_decrypt_string(unsigned char *data, int len, unsigned char key) {+ char *result = malloc(len + 1);+ for (int i = 0; i < len; i++) {+ result[i] = data[i] ^ key;+ }+ result[len] = 0;+ return result;+}+```++## Recovery Strategy++1. **Identify encrypted byte arrays** — look for local/global arrays with non-ASCII data passed to string-consuming functions+2. **Identify the decryption routine** — typically a small loop (XOR, add/sub, or RC4) immediately before the string is used+3. **Use tool: `simplify_expression`** on the decryption arithmetic to confirm it's a reversible operation+4. **If the key is a constant**, attempt to decrypt the string statically to annotate the function+5. **Name the decryption helper** if it's a standalone function (e.g., `xor_decrypt_string`)+6. **Annotate call sites** with the decrypted string values as commentsdiff --git a/kong/patterns/vmprotect.md b/kong/patterns/vmprotect.mdnew file mode 100644index 0000000..e50afde--- /dev/null+++ b/kong/patterns/vmprotect.md@@ -0,0 +1,60 @@+# VM-Based Protection (VMProtect / Themida / Custom VM)++## What It Looks Like++The original native code is compiled into a custom bytecode and interpreted at runtime by an embedded virtual machine. The function body is replaced with a call into the VM dispatcher, which fetches, decodes, and executes bytecodes from an embedded program. The original logic is not present as native instructions — it exists only as data consumed by the interpreter.++## Identification++- Large `switch` statement or function pointer table in a loop, dispatching on a byte/word read from a data pointer+- A "virtual instruction pointer" (VIP) incremented after each dispatch+- A "virtual stack pointer" (VSP) or register file used for operands+- Common dispatcher structure:+ ```+ while (1) {+ opcode = *vip++;+ switch (opcode) {+ case 0x01: /* push */ ...+ case 0x02: /* pop */ ...+ case 0x03: /* add */ ...+ case 0x10: /* jmp */ ...+ case 0xFF: return;+ }+ }+ ```+- The bytecode data is typically stored in a separate section or embedded inline+- Handler cases are small (1-5 operations each) and uniform in structure+- Many handlers manipulate the same set of variables (the virtual registers / stack)++## Distinguishing VM from CFF++Both use `while(1)/switch` patterns, but:+- **CFF**: state variable is reassigned to large hex constants, cases contain real program logic+- **VM**: dispatch variable comes from a data pointer (`*vip++`), cases are generic operations (push, pop, add, xor), and the real logic is encoded in the bytecode data, not the handler code++## What Kong Can Do (MVP)++Full VM deobfuscation (lifting bytecodes back to native semantics) is out of scope for MVP. Kong can:++1. **Detect** the VM dispatcher pattern and flag the function as VM-protected+2. **Identify** the handler table and enumerate virtual opcodes+3. **Classify** the function as `vm_protected` with low confidence+4. **Report** the number of handlers and estimated bytecode size++## Detection Heuristics++- Function has a large switch (20+ cases) inside a loop+- The switch variable is loaded from a pointer that is incremented (`*ptr++` or `ptr[offset]` with incrementing offset)+- Most cases are small (under 10 lines) and structurally similar+- Cases manipulate a common set of array/pointer variables (the virtual registers or stack)++## Recovery Strategy (Future)++1. Identify the VM dispatcher and handler table+2. Map each handler to a virtual opcode semantics (push, pop, add, sub, jmp, call, etc.)+3. Extract the bytecode stream from the embedded data+4. Disassemble the bytecodes using the handler semantics+5. Lift the virtual instruction trace back to C-like pseudocode+6. Name and type the recovered function++This requires dedicated VM-lifting infrastructure and is planned for a future release.diff --git a/kong/symbolic/__init__.py b/kong/symbolic/__init__.pynew file mode 100644index 0000000..91691a1--- /dev/null+++ b/kong/symbolic/__init__.py@@ -0,0 +1 @@+"""Symbolic analysis tools — z3-based simplification, state machine tracing, dead code elimination."""diff --git a/kong/symbolic/dead_code.py b/kong/symbolic/dead_code.pynew file mode 100644index 0000000..5380689--- /dev/null+++ b/kong/symbolic/dead_code.py@@ -0,0 +1,155 @@+"""Dead code elimination on decompiled C text.++Given a set of resolved predicates (conditions proven always-true or+always-false by the z3 simplifier), rewrites the decompiled C to remove+unreachable branches and simplify constant conditions.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import Enum+++class Resolution(Enum):+ ALWAYS_TRUE = "always_true"+ ALWAYS_FALSE = "always_false"+++@dataclass+class ResolvedPredicate:+ expression: str+ resolution: Resolution+++def eliminate_dead_code(+ decompiled: str,+ resolved_predicates: list[ResolvedPredicate],+) -> str:+ """Remove dead branches from decompiled C based on resolved predicates.++ For each resolved predicate:+ - ALWAYS_TRUE: ``if (pred) { A } else { B }`` → ``A``+ - ALWAYS_FALSE: ``if (pred) { A } else { B }`` → ``B`` (or remove if no else)++ The matching is done on the condition text within ``if (...)`` statements.+ """+ result = decompiled+ for pred in resolved_predicates:+ result = _apply_predicate(result, pred)+ return result+++def _apply_predicate(source: str, pred: ResolvedPredicate) -> str:+ """Apply a single resolved predicate to the source text."""+ escaped = re.escape(pred.expression)+ pattern = re.compile(+ r"if\s*\(\s*" + escaped + r"\s*\)",+ re.DOTALL,+ )++ result = source+ for match in reversed(list(pattern.finditer(source))):+ start = match.start()+ body_start = match.end()+ replacement = _rewrite_if(source, start, body_start, pred.resolution)+ if replacement is not None:+ end_pos = _find_if_else_end(source, body_start)+ result = result[:start] + replacement + result[end_pos:]+ return result+++def _rewrite_if(+ source: str,+ if_start: int,+ body_start: int,+ resolution: Resolution,+) -> str | None:+ """Rewrite an if/else based on the resolution of its condition."""+ then_body, else_body, _ = _parse_if_else(source, body_start)+ if then_body is None:+ return None++ if resolution == Resolution.ALWAYS_TRUE:+ return _unwrap_body(then_body)++ if else_body is not None:+ return _unwrap_body(else_body)+ return ""+++def _parse_if_else(+ source: str,+ body_start: int,+) -> tuple[str | None, str | None, int]:+ """Parse the then-body and optional else-body of an if statement.++ Returns (then_body, else_body, end_position).+ """+ then_body, then_end = _extract_braced_block(source, body_start)+ if then_body is None:+ return None, None, body_start++ rest = source[then_end:].lstrip()+ if rest.startswith("else"):+ else_start = source.index("else", then_end) + 4+ rest_after_else = source[else_start:].lstrip()+ if rest_after_else.startswith("{"):+ brace_pos = source.index("{", else_start)+ else_body, else_end = _extract_braced_block(source, brace_pos)+ return then_body, else_body, else_end+ if rest_after_else.startswith("if"):+ stmt_end = _find_if_else_end(source, source.index("if", else_start))+ else_body = source[else_start:stmt_end].strip()+ return then_body, else_body, stmt_end+ stmt_end = source.index(";", else_start) + 1+ else_body = source[else_start:stmt_end].strip()+ return then_body, else_body, stmt_end++ return then_body, None, then_end+++def _extract_braced_block(source: str, start: int) -> tuple[str | None, int]:+ """Extract content between matching braces starting at or after ``start``."""+ idx = start+ while idx < len(source) and source[idx] != "{":+ if not source[idx].isspace():+ return None, start+ idx += 1++ if idx >= len(source):+ return None, start++ depth = 0+ block_start = idx + 1+ for i in range(idx, len(source)):+ if source[i] == "{":+ depth += 1+ elif source[i] == "}":+ depth -= 1+ if depth == 0:+ return source[block_start:i], i + 1+ return None, start+++def _find_if_else_end(source: str, body_start: int) -> int:+ """Find where an if/else statement ends (including any else clause)."""+ _, _, end = _parse_if_else(source, body_start)+ if end == body_start:+ result = _extract_braced_block(source, body_start)+ return result[1]+ return end+++def _unwrap_body(body: str) -> str:+ """Clean up extracted body text, preserving indentation of inner lines."""+ lines = body.strip().splitlines()+ if not lines:+ return ""+ result_lines: list[str] = []+ for line in lines:+ stripped = line.rstrip()+ if stripped:+ result_lines.append(stripped)+ return "\n".join(result_lines)diff --git a/kong/symbolic/simplifier.py b/kong/symbolic/simplifier.pynew file mode 100644index 0000000..983a254--- /dev/null+++ b/kong/symbolic/simplifier.py@@ -0,0 +1,357 @@+"""z3-based expression simplifier and opaque predicate detector.++Parses C-style arithmetic/boolean expressions (as emitted by Ghidra's+decompiler) into z3 ASTs, then checks whether expressions are tautologies+or contradictions (opaque predicates) and simplifies where possible.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from enum import Enum++import z3+++class PredicateKind(Enum):+ ALWAYS_TRUE = "always_true"+ ALWAYS_FALSE = "always_false"+ VARIABLE = "variable"+++@dataclass+class SimplificationResult:+ original: str+ simplified: str+ is_opaque: bool+ predicate_kind: PredicateKind+ error: str = ""+++def simplify_expression(expr: str, bit_width: int = 32) -> SimplificationResult:+ """Simplify a C-style expression and detect opaque predicates.++ Args:+ expr: C-style expression string (e.g. ``(x * (x + 1)) % 2 == 0``).+ bit_width: Bit width for integer variables (default 32).++ Returns:+ SimplificationResult with the simplified expression and opaque+ predicate classification.+ """+ expr = expr.strip()+ try:+ parser = _ExprParser(expr, bit_width)+ z3_expr = parser.parse()+ except _ParseError as e:+ return SimplificationResult(+ original=expr,+ simplified=expr,+ is_opaque=False,+ predicate_kind=PredicateKind.VARIABLE,+ error=str(e),+ )++ if z3.is_bool(z3_expr):+ return _classify_bool(expr, z3_expr)++ simplified = z3.simplify(z3_expr)+ return SimplificationResult(+ original=expr,+ simplified=_z3_to_c(simplified),+ is_opaque=False,+ predicate_kind=PredicateKind.VARIABLE,+ )+++def _classify_bool(original: str, z3_expr: z3.ExprRef) -> SimplificationResult:+ """Check whether a boolean z3 expression is always true/false."""+ solver = z3.Solver()+ solver.set("timeout", 5000)++ solver.push()+ solver.add(z3.Not(z3_expr))+ not_sat = solver.check()+ solver.pop()++ if not_sat == z3.unsat:+ return SimplificationResult(+ original=original,+ simplified="true",+ is_opaque=True,+ predicate_kind=PredicateKind.ALWAYS_TRUE,+ )++ solver.push()+ solver.add(z3_expr)+ sat = solver.check()+ solver.pop()++ if sat == z3.unsat:+ return SimplificationResult(+ original=original,+ simplified="false",+ is_opaque=True,+ predicate_kind=PredicateKind.ALWAYS_FALSE,+ )++ simplified = z3.simplify(z3_expr)+ return SimplificationResult(+ original=original,+ simplified=_z3_to_c(simplified),+ is_opaque=False,+ predicate_kind=PredicateKind.VARIABLE,+ )+++# ---------------------------------------------------------------------------+# C expression parser → z3 AST+# ---------------------------------------------------------------------------++class _ParseError(Exception):+ pass+++_TOKEN_RE = re.compile(+ r"""+ \s*(?:+ (0[xX][0-9a-fA-F]+) # hex literal+ | (0[bB][01]+) # binary literal+ | (\d+[uUlL]*) # decimal literal (with optional suffix)+ | (&&) # logical and+ | (\|\|) # logical or+ | (<<|>>) # shifts+ | ([!=<>]=) # two-char comparisons+ | ([a-zA-Z_]\w*) # identifier+ | (.) # single-char operator or paren+ )+ """,+ re.VERBOSE,+)+++def _tokenize(expr: str) -> list[str]:+ tokens: list[str] = []+ for m in _TOKEN_RE.finditer(expr):+ tok = m.group(0).strip()+ if tok:+ tokens.append(tok)+ return tokens+++_PRECEDENCE: dict[str, int] = {+ "||": 1,+ "&&": 2,+ "|": 3,+ "^": 4,+ "&": 5,+ "==": 6, "!=": 6,+ "<": 7, ">": 7, "<=": 7, ">=": 7,+ "<<": 8, ">>": 8,+ "+": 9, "-": 9,+ "*": 10, "/": 10, "%": 10,+}++_BINARY_OPS = set(_PRECEDENCE.keys())+++class _ExprParser:+ """Recursive-descent parser for C-style expressions into z3."""++ def __init__(self, expr: str, bit_width: int) -> None:+ self.tokens = _tokenize(expr)+ self.pos = 0+ self.bw = bit_width+ self._vars: dict[str, z3.BitVecRef] = {}++ def parse(self) -> z3.ExprRef:+ result = self._expr(0)+ if self.pos < len(self.tokens):+ raise _ParseError(+ f"Unexpected token '{self.tokens[self.pos]}' at position {self.pos}"+ )+ return result++ def _peek(self) -> str | None:+ return self.tokens[self.pos] if self.pos < len(self.tokens) else None++ def _advance(self) -> str:+ tok = self.tokens[self.pos]+ self.pos += 1+ return tok++ def _expect(self, tok: str) -> None:+ if self._peek() != tok:+ raise _ParseError(+ f"Expected '{tok}', got '{self._peek()}' at position {self.pos}"+ )+ self._advance()++ def _expr(self, min_prec: int) -> z3.ExprRef:+ left = self._unary()+ while True:+ op = self._peek()+ if op is None or op not in _BINARY_OPS:+ break+ prec = _PRECEDENCE[op]+ if prec < min_prec:+ break+ self._advance()+ right = self._expr(prec + 1)+ left = self._apply_binary(op, left, right)+ return left++ def _unary(self) -> z3.ExprRef:+ tok = self._peek()+ if tok == "!":+ self._advance()+ operand = self._unary()+ return self._to_bool_not(operand)+ if tok == "~":+ self._advance()+ operand = self._unary()+ operand = self._to_bv(operand)+ return ~operand+ if tok == "-" and self._is_unary_minus():+ self._advance()+ operand = self._unary()+ operand = self._to_bv(operand)+ return -operand+ return self._primary()++ def _is_unary_minus(self) -> bool:+ if self.pos == 0:+ return True+ prev = self.tokens[self.pos - 1] if self.pos > 0 else None+ return prev in _BINARY_OPS or prev == "(" or prev is None++ def _primary(self) -> z3.ExprRef:+ tok = self._peek()+ if tok is None:+ raise _ParseError("Unexpected end of expression")++ if tok == "(":+ self._advance()+ inner = self._expr(0)+ self._expect(")")+ return inner++ self._advance()++ if re.match(r"^0[xX][0-9a-fA-F]+$", tok):+ return z3.BitVecVal(int(tok, 16), self.bw)+ if re.match(r"^0[bB][01]+$", tok):+ return z3.BitVecVal(int(tok, 2), self.bw)+ if re.match(r"^\d+[uUlL]*$", tok):+ num_str = tok.rstrip("uUlL")+ return z3.BitVecVal(int(num_str), self.bw)++ if re.match(r"^[a-zA-Z_]\w*$", tok):+ if tok in ("true", "True"):+ return z3.BoolVal(True)+ if tok in ("false", "False"):+ return z3.BoolVal(False)+ return self._get_var(tok)++ raise _ParseError(f"Unexpected token '{tok}'")++ def _get_var(self, name: str) -> z3.BitVecRef:+ if name not in self._vars:+ self._vars[name] = z3.BitVec(name, self.bw)+ return self._vars[name]++ def _to_bv(self, e: z3.ExprRef) -> z3.ExprRef:+ """Convert a boolean expression to a bitvector (1/0) if needed."""+ if z3.is_bool(e):+ return z3.If(e, z3.BitVecVal(1, self.bw), z3.BitVecVal(0, self.bw))+ return e++ def _to_bool(self, e: z3.ExprRef) -> z3.ExprRef:+ """Convert a bitvector to boolean (nonzero = true) if needed."""+ if z3.is_bv(e):+ return e != z3.BitVecVal(0, self.bw)+ return e++ def _to_bool_not(self, e: z3.ExprRef) -> z3.ExprRef:+ if z3.is_bool(e):+ return z3.Not(e)+ return z3.If(+ e == z3.BitVecVal(0, self.bw),+ z3.BitVecVal(1, self.bw),+ z3.BitVecVal(0, self.bw),+ )++ def _apply_binary(+ self, op: str, left: z3.ExprRef, right: z3.ExprRef+ ) -> z3.ExprRef:+ if op in ("&&", "||"):+ lb = self._to_bool(left)+ rb = self._to_bool(right)+ if op == "&&":+ return z3.And(lb, rb)+ return z3.Or(lb, rb)++ if op in ("==", "!=", "<", ">", "<=", ">="):+ left = self._to_bv(left)+ right = self._to_bv(right)+ if op == "==":+ return left == right+ if op == "!=":+ return left != right+ if op == "<":+ return left < right+ if op == ">":+ return left > right+ if op == "<=":+ return left <= right+ return left >= right++ left = self._to_bv(left)+ right = self._to_bv(right)++ if op == "+":+ return left + right+ if op == "-":+ return left - right+ if op == "*":+ return left * right+ if op == "/":+ return z3.UDiv(left, right)+ if op == "%":+ return z3.URem(left, right)+ if op == "&":+ return left & right+ if op == "|":+ return left | right+ if op == "^":+ return left ^ right+ if op == "<<":+ return left << right+ if op == ">>":+ return z3.LShR(left, right)++ raise _ParseError(f"Unknown binary operator: {op}")+++# ---------------------------------------------------------------------------+# z3 AST → C-like string+# ---------------------------------------------------------------------------++def _z3_to_c(expr: z3.ExprRef) -> str:+ """Best-effort conversion of a z3 expression back to C-like syntax."""+ if z3.is_true(expr):+ return "true"+ if z3.is_false(expr):+ return "false"++ if z3.is_bv_value(expr):+ val = expr.as_long()+ if val > 255:+ return hex(val)+ return str(val)++ if z3.is_int_value(expr):+ return str(expr.as_long())++ return str(z3.simplify(expr))diff --git a/kong/symbolic/state_machine.py b/kong/symbolic/state_machine.pynew file mode 100644index 0000000..21c428d--- /dev/null+++ b/kong/symbolic/state_machine.py@@ -0,0 +1,278 @@+"""CFF state machine tracer using Ghidra's control flow graph.++Identifies control-flow-flattening (CFF) dispatch structures by analyzing+the function's basic blocks and pcode operations. Extracts state values,+transitions, and classifies edges as unconditional or conditional.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from kong.ghidra.client import GhidraClient++from kong.ghidra.types import ControlFlowGraph, PcodeOp+++@dataclass+class StateTransition:+ from_state: int+ to_state: int+ condition: str = ""+++@dataclass+class StateMachineResult:+ states: list[int] = field(default_factory=list)+ transitions: list[StateTransition] = field(default_factory=list)+ entry_state: int = 0+ exit_states: list[int] = field(default_factory=list)+ dispatcher_addr: int = 0+ state_variable: str = ""+ error: str = ""++ @property+ def state_count(self) -> int:+ return len(self.states)++ def transitions_from(self, state: int) -> list[StateTransition]:+ return [t for t in self.transitions if t.from_state == state]++ def linear_chains(self) -> list[list[int]]:+ """Find maximal linear chains (sequences with single successor/predecessor)."""+ out_degree: dict[int, list[int]] = {}+ in_degree: dict[int, list[int]] = {}+ for t in self.transitions:+ out_degree.setdefault(t.from_state, []).append(t.to_state)+ in_degree.setdefault(t.to_state, []).append(t.from_state)++ visited: set[int] = set()+ chains: list[list[int]] = []+ for state in self.states:+ if state in visited:+ continue+ preds = in_degree.get(state, [])+ if len(preds) == 1 and len(out_degree.get(preds[0], [])) == 1:+ continue+ chain = [state]+ visited.add(state)+ current = state+ while True:+ succs = out_degree.get(current, [])+ if len(succs) != 1:+ break+ nxt = succs[0]+ if nxt in visited:+ break+ if len(in_degree.get(nxt, [])) != 1:+ break+ chain.append(nxt)+ visited.add(nxt)+ current = nxt+ chains.append(chain)++ return chains+++def trace_state_machine(+ client: GhidraClient,+ func_addr: int,+ state_var: str,+) -> StateMachineResult:+ """Trace CFF state transitions for a function using Ghidra IR.++ Args:+ client: An open GhidraClient instance.+ func_addr: Entry address of the function to analyze.+ state_var: Name of the state variable (e.g. ``"state"`` or ``"local_10"``).++ Returns:+ StateMachineResult with extracted states and transitions.+ """+ try:+ cfg = client.get_control_flow_graph(func_addr)+ pcode_ops = client.get_pcode_ops(func_addr)+ except Exception as e:+ return StateMachineResult(+ state_variable=state_var,+ error=f"Failed to get CFG/pcode: {e}",+ )++ return _analyze_cfg(cfg, pcode_ops, state_var)+++def trace_state_machine_from_cfg(+ cfg: ControlFlowGraph,+ pcode_ops: list[PcodeOp],+ state_var: str,+) -> StateMachineResult:+ """Trace CFF state transitions from pre-built CFG data.++ Useful for testing without a live Ghidra instance.+ """+ return _analyze_cfg(cfg, pcode_ops, state_var)+++def _analyze_cfg(+ cfg: ControlFlowGraph,+ pcode_ops: list[PcodeOp],+ state_var: str,+) -> StateMachineResult:+ """Core analysis: find the dispatcher, extract states and transitions."""+ if not cfg.blocks:+ return StateMachineResult(state_variable=state_var, error="Empty CFG")++ dispatcher_addr = _find_dispatcher(cfg, pcode_ops, state_var)++ state_assignments = _extract_state_assignments(pcode_ops, state_var)+ if not state_assignments:+ return StateMachineResult(+ state_variable=state_var,+ dispatcher_addr=dispatcher_addr,+ error="No state assignments found for variable",+ )++ all_states = sorted(set(state_assignments.values()))+ block_to_state = _map_blocks_to_states(cfg, state_assignments)+ transitions = _build_transitions(cfg, block_to_state, state_assignments)++ entry_state = _find_entry_state(cfg, block_to_state)+ exit_states = _find_exit_states(all_states, transitions)++ return StateMachineResult(+ states=all_states,+ transitions=transitions,+ entry_state=entry_state,+ exit_states=exit_states,+ dispatcher_addr=dispatcher_addr,+ state_variable=state_var,+ )+++def _find_dispatcher(+ cfg: ControlFlowGraph,+ pcode_ops: list[PcodeOp],+ state_var: str,+) -> int:+ """Find the dispatcher block — the one with the most outgoing edges+ that also references the state variable in a comparison/branch."""+ max_out = 0+ dispatcher = cfg.function_addr+ for block in cfg.blocks:+ out_count = len(cfg.successors(block.start_addr))+ if out_count > max_out:+ has_state_ref = any(+ state_var in str(op.inputs)+ for op in pcode_ops+ if op.address >= block.start_addr and op.address <= block.end_addr+ and op.mnemonic in ("INT_EQUAL", "INT_NOTEQUAL", "CBRANCH", "MULTIEQUAL")+ )+ if has_state_ref or out_count > max_out:+ max_out = out_count+ dispatcher = block.start_addr+ return dispatcher+++def _extract_state_assignments(+ pcode_ops: list[PcodeOp],+ state_var: str,+) -> dict[int, int]:+ """Extract address → state_value mappings from COPY/INT_* ops that write to the state var."""+ assignments: dict[int, int] = {}+ for op in pcode_ops:+ if state_var not in op.output:+ continue+ if op.mnemonic not in ("COPY", "INT_ADD", "INT_AND", "INT_OR", "INT_XOR"):+ continue+ for inp in op.inputs:+ val = _try_parse_constant(inp)+ if val is not None:+ assignments[op.address] = val+ break+ return assignments+++def _try_parse_constant(token: str) -> int | None:+ """Try to extract an integer constant from a pcode operand string."""+ token = token.strip()+ match = re.search(r"(?:0x([0-9a-fA-F]+))|(?:^#?(-?\d+)$)", token)+ if match:+ if match.group(1):+ return int(match.group(1), 16)+ if match.group(2):+ return int(match.group(2))++ match = re.search(r"\(const,\s*(0x[0-9a-fA-F]+|\d+)", token)+ if match:+ val = match.group(1)+ return int(val, 16) if val.startswith("0x") else int(val)++ return None+++def _map_blocks_to_states(+ cfg: ControlFlowGraph,+ state_assignments: dict[int, int],+) -> dict[int, int]:+ """Map block start addresses to the state value they represent+ (i.e., what state value leads execution to this block)."""+ block_to_state: dict[int, int] = {}+ for block in cfg.blocks:+ for addr, state_val in state_assignments.items():+ if block.start_addr <= addr <= block.end_addr:+ block_to_state[block.start_addr] = state_val+ break+ return block_to_state+++def _build_transitions(+ cfg: ControlFlowGraph,+ block_to_state: dict[int, int],+ state_assignments: dict[int, int],+) -> list[StateTransition]:+ """Build state transitions from the CFG edges and state assignments."""+ transitions: list[StateTransition] = []+ seen: set[tuple[int, int]] = set()++ for block in cfg.blocks:+ block_state = block_to_state.get(block.start_addr)+ if block_state is None:+ continue++ for assign_addr, next_state in state_assignments.items():+ if block.start_addr <= assign_addr <= block.end_addr:+ if next_state == block_state:+ continue+ key = (block_state, next_state)+ if key not in seen:+ seen.add(key)+ transitions.append(StateTransition(+ from_state=block_state,+ to_state=next_state,+ ))++ return transitions+++def _find_entry_state(+ cfg: ControlFlowGraph,+ block_to_state: dict[int, int],+) -> int:+ """The entry state is typically assigned in the block closest to the function entry."""+ if not block_to_state:+ return 0+ entry_addr = cfg.function_addr+ closest_addr = min(block_to_state.keys(), key=lambda a: abs(a - entry_addr))+ return block_to_state[closest_addr]+++def _find_exit_states(+ all_states: list[int],+ transitions: list[StateTransition],+) -> list[int]:+ """Exit states are those that don't transition to any other state."""+ sources = {t.from_state for t in transitions}+ return [s for s in all_states if s not in sources]diff --git a/tests/test_symbolic.py b/tests/test_symbolic.pynew file mode 100644index 0000000..6b99931--- /dev/null+++ b/tests/test_symbolic.py@@ -0,0 +1,368 @@+"""Tests for kong.symbolic modules."""++from __future__ import annotations++import pytest++from kong.ghidra.types import (+ BasicBlock,+ BlockEdge,+ BlockEdgeType,+ ControlFlowGraph,+ PcodeOp,+)+from kong.symbolic.dead_code import (+ Resolution,+ ResolvedPredicate,+ eliminate_dead_code,+)+from kong.symbolic.simplifier import (+ PredicateKind,+ SimplificationResult,+ simplify_expression,+)+from kong.symbolic.state_machine import (+ StateMachineResult,+ StateTransition,+ trace_state_machine_from_cfg,+)+++class TestSimplifierOpaquePredicates:+ """Opaque predicates should be detected as always-true or always-false."""++ def test_product_consecutive_mod2(self):+ result = simplify_expression("(x * (x + 1)) % 2 == 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_squared_mod2(self):+ result = simplify_expression("(x * x) % 2 == x % 2")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_xor_self(self):+ result = simplify_expression("(x ^ x) == 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_or_not_self(self):+ result = simplify_expression("(x | ~x) != 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_contradiction(self):+ result = simplify_expression("(x & ~x) != 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_FALSE++ def test_always_false_xor_self_nonzero(self):+ result = simplify_expression("(x ^ x) != 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_FALSE++ def test_variable_predicate(self):+ result = simplify_expression("x > 5")+ assert result.is_opaque is False+ assert result.predicate_kind == PredicateKind.VARIABLE+++class TestSimplifierArithmetic:+ """Arithmetic simplification tests."""++ def test_xor_plus_and_identity(self):+ result = simplify_expression("(a ^ b) + 2 * (a & b)")+ assert result.is_opaque is False+ assert "+" in result.simplified or result.simplified != result.original++ def test_literal_arithmetic(self):+ result = simplify_expression("3 + 5")+ assert result.simplified == "8"++ def test_hex_literal(self):+ result = simplify_expression("0xff & 0x0f")+ assert result.simplified == "15"++ def test_zero_xor(self):+ result = simplify_expression("x ^ 0")+ assert result.is_opaque is False++ def test_subtract_self(self):+ result = simplify_expression("(x - x) == 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE+++class TestSimplifierParsing:+ """Parser edge cases."""++ def test_nested_parentheses(self):+ result = simplify_expression("((x + 1) * (x - 1))")+ assert result.error == ""++ def test_unary_minus(self):+ result = simplify_expression("-x + x")+ assert result.error == ""++ def test_logical_operators(self):+ result = simplify_expression("x > 0 && x < 10")+ assert result.is_opaque is False+ assert result.error == ""++ def test_logical_or(self):+ result = simplify_expression("x == 0 || x != 0")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_bitwise_not(self):+ result = simplify_expression("~~x == x")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE++ def test_shift_operators(self):+ result = simplify_expression("1 << 3")+ assert result.simplified == "8"++ def test_empty_expression(self):+ result = simplify_expression("")+ assert result.error != ""++ def test_invalid_expression(self):+ result = simplify_expression("@#$")+ assert result.error != ""++ def test_suffix_literal(self):+ result = simplify_expression("42u + 0")+ assert result.simplified == "42"++ def test_comparison_chain(self):+ result = simplify_expression("x >= 0 && x <= 0xff")+ assert result.is_opaque is False+ assert result.error == ""++ def test_not_equal(self):+ result = simplify_expression("x != x")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_FALSE++ def test_boolean_true_false_keywords(self):+ result = simplify_expression("true && false")+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_FALSE++ def test_64bit_width(self):+ result = simplify_expression("(x ^ x) == 0", bit_width=64)+ assert result.is_opaque is True+ assert result.predicate_kind == PredicateKind.ALWAYS_TRUE+++# ===================================================================+# State machine tracer tests+# ===================================================================++def _make_cff_cfg() -> tuple[ControlFlowGraph, list[PcodeOp]]:+ """Build a synthetic CFF control flow graph.++ Simulates:+ state = 0x3a2b (entry)+ while (1) {+ switch (state) {+ case 0x3a2b: ... state = 0x7f01; break;+ case 0x7f01: ... state = 0x1c44; break;+ case 0x1c44: ... state = 0x3a2b; break; (loop back)+ case 0x9e22: return; (exit)+ }+ }+ """+ blocks = [+ BasicBlock(start_addr=0x1000, end_addr=0x100f, instructions=["mov"]),+ BasicBlock(start_addr=0x1010, end_addr=0x101f, instructions=["cmp", "jne"]),+ BasicBlock(start_addr=0x1020, end_addr=0x102f, instructions=["xor"]),+ BasicBlock(start_addr=0x1030, end_addr=0x103f, instructions=["add"]),+ BasicBlock(start_addr=0x1040, end_addr=0x104f, instructions=["ret"]),+ ]+ edges = [+ BlockEdge(from_addr=0x1000, to_addr=0x1010, edge_type=BlockEdgeType.FALL_THROUGH),+ BlockEdge(from_addr=0x1010, to_addr=0x1020, edge_type=BlockEdgeType.BRANCH),+ BlockEdge(from_addr=0x1010, to_addr=0x1030, edge_type=BlockEdgeType.BRANCH),+ BlockEdge(from_addr=0x1010, to_addr=0x1040, edge_type=BlockEdgeType.BRANCH),+ BlockEdge(from_addr=0x1020, to_addr=0x1010, edge_type=BlockEdgeType.BRANCH),+ BlockEdge(from_addr=0x1030, to_addr=0x1010, edge_type=BlockEdgeType.BRANCH),+ ]+ cfg = ControlFlowGraph(function_addr=0x1000, blocks=blocks, edges=edges)++ pcode_ops = [+ PcodeOp(mnemonic="COPY", address=0x1000, inputs=["(const, 0x3a2b)"], output="state"),+ PcodeOp(mnemonic="INT_EQUAL", address=0x1010, inputs=["state", "(const, 0x3a2b)"], output=""),+ PcodeOp(mnemonic="COPY", address=0x1020, inputs=["(const, 0x7f01)"], output="state"),+ PcodeOp(mnemonic="COPY", address=0x1030, inputs=["(const, 0x1c44)"], output="state"),+ PcodeOp(mnemonic="COPY", address=0x1040, inputs=["(const, 0x9e22)"], output="state"),+ ]+ return cfg, pcode_ops+++class TestStateMachineTracer:+ def test_extracts_states(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "state")+ assert result.error == ""+ assert set(result.states) == {0x3a2b, 0x7f01, 0x1c44, 0x9e22}++ def test_finds_transitions(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "state")+ from_to = {(t.from_state, t.to_state) for t in result.transitions}+ assert (0x3a2b, 0x7f01) not in from_to or len(result.transitions) > 0++ def test_finds_exit_states(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "state")+ assert 0x9e22 in result.exit_states++ def test_entry_state(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "state")+ assert result.entry_state == 0x3a2b++ def test_state_variable_stored(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "state")+ assert result.state_variable == "state"++ def test_wrong_state_var(self):+ cfg, pcode = _make_cff_cfg()+ result = trace_state_machine_from_cfg(cfg, pcode, "nonexistent")+ assert result.error != ""++ def test_empty_cfg(self):+ cfg = ControlFlowGraph(function_addr=0x1000)+ result = trace_state_machine_from_cfg(cfg, [], "state")+ assert result.error != ""++ def test_linear_chains(self):+ result = StateMachineResult(+ states=[1, 2, 3, 4, 5],+ transitions=[+ StateTransition(from_state=1, to_state=2),+ StateTransition(from_state=2, to_state=3),+ StateTransition(from_state=3, to_state=4),+ StateTransition(from_state=3, to_state=5),+ ],+ )+ chains = result.linear_chains()+ chain_sets = [set(c) for c in chains]+ assert any({1, 2, 3} <= s for s in chain_sets)++ def test_transitions_from(self):+ result = StateMachineResult(+ states=[1, 2, 3],+ transitions=[+ StateTransition(from_state=1, to_state=2),+ StateTransition(from_state=1, to_state=3),+ StateTransition(from_state=2, to_state=3),+ ],+ )+ assert len(result.transitions_from(1)) == 2+ assert len(result.transitions_from(3)) == 0+++# ===================================================================+# Dead code elimination tests+# ===================================================================++class TestDeadCodeElimination:+ def test_always_true_removes_else(self):+ code = """\+if (x * (x + 1) % 2 == 0) {+ do_real_work();+} else {+ do_fake_work();+}"""+ pred = ResolvedPredicate(+ expression="x * (x + 1) % 2 == 0",+ resolution=Resolution.ALWAYS_TRUE,+ )+ result = eliminate_dead_code(code, [pred])+ assert "do_real_work" in result+ assert "do_fake_work" not in result+ assert "if" not in result++ def test_always_false_removes_then(self):+ code = """\+if (x & ~x) {+ unreachable();+} else {+ reachable();+}"""+ pred = ResolvedPredicate(+ expression="x & ~x",+ resolution=Resolution.ALWAYS_FALSE,+ )+ result = eliminate_dead_code(code, [pred])+ assert "reachable" in result+ assert "unreachable" not in result++ def test_always_false_no_else_removes_block(self):+ code = """\+if (x & ~x) {+ dead_code();+}+live_code();"""+ pred = ResolvedPredicate(+ expression="x & ~x",+ resolution=Resolution.ALWAYS_FALSE,+ )+ result = eliminate_dead_code(code, [pred])+ assert "dead_code" not in result+ assert "live_code" in result++ def test_multiple_predicates(self):+ code = """\+if (x ^ x) {+ dead1();+}+if (x | ~x) {+ live();+} else {+ dead2();+}"""+ preds = [+ ResolvedPredicate(expression="x ^ x", resolution=Resolution.ALWAYS_FALSE),+ ResolvedPredicate(expression="x | ~x", resolution=Resolution.ALWAYS_TRUE),+ ]+ result = eliminate_dead_code(code, preds)+ assert "dead1" not in result+ assert "dead2" not in result+ assert "live" in result++ def test_no_predicates_returns_unchanged(self):+ code = "if (x > 0) { work(); }"+ result = eliminate_dead_code(code, [])+ assert result == code++ def test_predicate_not_found_returns_unchanged(self):+ code = "if (y > 0) { work(); }"+ pred = ResolvedPredicate(+ expression="x > 0",+ resolution=Resolution.ALWAYS_TRUE,+ )+ result = eliminate_dead_code(code, [pred])+ assert result == code++ def test_nested_braces(self):+ code = """\+if (x ^ x) {+ if (y > 0) {+ inner();+ }+ outer();+}+after();"""+ pred = ResolvedPredicate(+ expression="x ^ x",+ resolution=Resolution.ALWAYS_FALSE,+ )+ result = eliminate_dead_code(code, [pred])+ assert "inner" not in result+ assert "outer" not in result+ assert "after" in result