Skip to content

armgit / kong

Public Imported from GitHub
0

The world's first agentic reverse engineer.

add label extraction

Amruth414447dcb6e6
diff --git a/tools/xda/src/extract_labels.py b/tools/xda/src/extract_labels.py
new file mode 100644
index 0000000..cc92aa9
--- /dev/null
+++ b/tools/xda/src/extract_labels.py
@@ -0,0 +1,73 @@
+from elftools.elf.elffile import ELFFile
+
+def extract_function_boundaries(elf_path: str) -> list[dict]:
+ """Extract function start/end addresses from DWARF debug info.
+
+ Returns list of {"name": str | None, "start": int, "end": int}.
+ """
+ functions: list[dict] = []
+ with open(elf_path, "rb") as f:
+ elf = ELFFile(f)
+ if not elf.has_dwarf_info():
+ return []
+
+ dwarf = elf.get_dwarf_info()
+ for cu in dwarf.iter_CUs():
+ for die in cu.iter_DIEs():
+ if die.tag != "DW_TAG_subprogram":
+ continue
+ if "DW_AT_low_pc" not in die.attributes:
+ continue
+
+ low_pc = die.attributes["DW_AT_low_pc"].value
+ high_pc_attr = die.attributes.get("DW_AT_high_pc")
+ if high_pc_attr is None:
+ continue
+
+ if high_pc_attr.form in ("DW_FORM_addr",):
+ high_pc = high_pc_attr.value
+ else:
+ high_pc = low_pc + high_pc_attr.value
+
+ if high_pc <= low_pc:
+ continue
+
+ name_attr = die.attributes.get("DW_AT_name")
+ name = name_attr.value.decode() if name_attr else None
+ functions.append({"name": name, "start": low_pc, "end": high_pc})
+
+ return functions
+
+def generate_byte_labels(
+ elf_path: str,
+ boundaries: list[dict],
+) -> tuple[bytes, list[int]]:
+ """Generate per-byte labels for the .text section.
+
+ Labels: 0 = non-function, 1 = function_start, 2 = function_body.
+ Returns (text_section_bytes, labels).
+ """
+ with open(elf_path, "rb") as f:
+ elf = ELFFile(f)
+ text = elf.get_section_by_name(".text")
+ if text is None:
+ return b"", []
+
+ text_start = text["sh_addr"]
+ text_bytes = text.data()
+
+ labels = [0] * len(text_bytes)
+
+ for func in boundaries:
+ start_off = func["start"] - text_start
+ end_off = func["end"] - text_start
+
+ if start_off < 0 or start_off >= len(text_bytes):
+ continue
+ end_off = min(end_off, len(text_bytes))
+
+ labels[start_off] = 1 # function_start
+ for i in range(start_off + 1, end_off):
+ labels[i] = 2 # function_body
+
+ return bytes(text_bytes), labels
\ No newline at end of file
diff --git a/tools/xda/tests/test_extract_labels.py b/tools/xda/tests/test_extract_labels.py
new file mode 100644
index 0000000..3d8dd5b
--- /dev/null
+++ b/tools/xda/tests/test_extract_labels.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+import functools
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from src.extract_labels import extract_function_boundaries, generate_byte_labels
+
+
+def _probe_compile(cmd_prefix: list[str]) -> bool:
+ with tempfile.TemporaryDirectory() as tmp:
+ p = Path(tmp)
+ src = p / "probe.c"
+ out = p / "probe.bin"
+ src.write_text("int main(void) { return 0; }\n")
+ try:
+ subprocess.run(
+ [*cmd_prefix, "-g", "-O0", "-o", str(out), str(src)],
+ check=True,
+ capture_output=True,
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ return False
+ return out.read_bytes()[:4] == b"\x7fELF"
+
+
[email protected]_cache(maxsize=1)
+def _elf_compile_prefix() -> list[str]:
+ if sys.platform == "linux":
+ candidates: tuple[list[str], ...] = (["gcc"], ["clang"])
+ else:
+ candidates = (
+ ["x86_64-linux-gnu-gcc"],
+ ["aarch64-linux-gnu-gcc"],
+ ["x86_64-elf-gcc"],
+ ["zig", "cc", "-target", "x86_64-linux-gnu"],
+ ["zig", "cc", "-target", "aarch64-linux-gnu"],
+ ["gcc"],
+ ["clang"],
+ )
+ for prefix in candidates:
+ if shutil.which(prefix[0]) and _probe_compile(prefix):
+ return prefix
+ pytest.skip(
+ "No C compiler found that emits ELF (native macOS clang produces Mach-O; "
+ "install Zig, brew install x86_64-elf-gcc, or a Linux cross-compiler)."
+ )
+
+
+def _compile_test_binary(src: str, out: Path) -> Path:
+ """Compile a C string to an ELF binary with debug info."""
+ src_file = out / "test.c"
+ bin_file = out / "test.elf"
+ src_file.write_text(src)
+
+ prefix = _elf_compile_prefix()
+ subprocess.run(
+ [*prefix, "-g", "-O0", "-o", str(bin_file), str(src_file)],
+ check=True,
+ )
+ return bin_file
+
+
+def test_extract_boundaries_from_simple_binary():
+ src = """
+ int add(int a, int b) { return a + b; }
+ int mul(int a, int b) { return a * b; }
+ int main() { return add(1, 2) + mul(3, 4); }
+ """
+ with tempfile.TemporaryDirectory() as tmp:
+ binary = _compile_test_binary(src, Path(tmp))
+ boundaries = extract_function_boundaries(str(binary))
+
+ names = {b["name"] for b in boundaries}
+ assert "add" in names
+ assert "mul" in names
+ assert "main" in names
+
+ for b in boundaries:
+ assert b["start"] < b["end"]
+ assert b["end"] - b["start"] > 0
+
+
+def test_generate_byte_labels():
+ src = "int foo() { return 42; } int main() { return foo(); }"
+ with tempfile.TemporaryDirectory() as tmp:
+ binary = _compile_test_binary(src, Path(tmp))
+ boundaries = extract_function_boundaries(str(binary))
+ text_bytes, labels = generate_byte_labels(str(binary), boundaries)
+
+ assert len(text_bytes) == len(labels)
+ assert len(text_bytes) > 0
+
+ # At least some bytes should be labeled as function_start (1)
+ assert 1 in labels
+ # At least some bytes should be labeled as function_body (2)
+ assert 2 in labels
+ # At least some bytes should be non-function (0) unless .text is fully covered
\ No newline at end of file