- Updated retail-debugger-entry-options.md to clarify the status of the debugger in No Remorse and No Regret, including findings from recent investigations. - Revised usecode-format-specification.md to improve clarity on opcode behavior and historical naming conventions, with added references to Japanese executable analysis. - Introduced usecode-jp-dispatch-analysis.md to document findings from the Japanese No Remorse executable, detailing opcode dispatch and search object behavior. - Added ghidra_to_dosbox_memory.py, a new tool for translating Ghidra segment:offset addresses to DOSBox physical memory offsets, including comprehensive address validation. - Created test_ghidra_to_dosbox_memory.py to ensure the correctness of address translation logic and selector base loading, with unit tests covering various scenarios.
186 lines
No EOL
6.7 KiB
Python
186 lines
No EOL
6.7 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import sys
|
|
from dataclasses import asdict, dataclass
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
NE_SELECTOR_BASE = 0x1000
|
|
NE_SELECTOR_STRIDE = 8
|
|
MAX_NE_SELECTOR = 0xFFF8
|
|
MAX_NE_SEGMENTS = (MAX_NE_SELECTOR - NE_SELECTOR_BASE) // NE_SELECTOR_STRIDE + 1
|
|
MAX_ADDRESS = 0xFFFFFFFF
|
|
ADDRESS_PATTERN = re.compile(r"^\s*(0[xX][0-9a-fA-F]+|[0-9a-fA-F]+)\s*:\s*(0[xX][0-9a-fA-F]+|[0-9a-fA-F]+)\s*$")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class AddressTranslation:
|
|
source: str
|
|
selector: int
|
|
ne_segment: int
|
|
segment_offset: int
|
|
physical_address: int
|
|
|
|
|
|
def selector_to_ne_segment(selector: int) -> int:
|
|
selector_delta = selector - NE_SELECTOR_BASE
|
|
if selector_delta < 0 or selector_delta % NE_SELECTOR_STRIDE:
|
|
raise ValueError(f"invalid Crusader NE selector: 0x{selector:04X}")
|
|
|
|
segment = selector_delta // NE_SELECTOR_STRIDE + 1
|
|
if segment > MAX_NE_SEGMENTS:
|
|
raise ValueError(f"selector is outside the NE segment range: 0x{selector:04X}")
|
|
return segment
|
|
|
|
|
|
def ne_segment_to_selector(segment: int) -> int:
|
|
if not 1 <= segment <= MAX_NE_SEGMENTS:
|
|
raise ValueError(f"NE segment must be in 1..0x{MAX_NE_SEGMENTS:X}: {segment}")
|
|
return NE_SELECTOR_BASE + (segment - 1) * NE_SELECTOR_STRIDE
|
|
|
|
|
|
def parse_ghidra_address(value: str) -> tuple[int, int]:
|
|
match = ADDRESS_PATTERN.fullmatch(value)
|
|
if match is None:
|
|
raise ValueError(f"expected a Ghidra address in segment:offset form: {value!r}")
|
|
|
|
segment = int(match.group(1).removeprefix("0x").removeprefix("0X"), 16)
|
|
offset = int(match.group(2).removeprefix("0x").removeprefix("0X"), 16)
|
|
if segment > 0xFFFF or offset > 0xFFFF:
|
|
raise ValueError(f"address components must fit in 16 bits: {value!r}")
|
|
return segment, offset
|
|
|
|
|
|
def load_selector_bases(path: Path) -> tuple[str, dict[int, int]]:
|
|
try:
|
|
document = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError) as error:
|
|
raise ValueError(f"cannot read selector-base map {path}: {error}") from error
|
|
|
|
if not isinstance(document, dict):
|
|
raise ValueError("selector-base map must be a JSON object")
|
|
|
|
program = document.get("program")
|
|
raw_bases = document.get("selector_bases")
|
|
if not isinstance(program, str) or not program.strip():
|
|
raise ValueError("selector-base map must contain a non-empty 'program' string")
|
|
if not isinstance(raw_bases, dict) or not raw_bases:
|
|
raise ValueError("selector-base map must contain a non-empty 'selector_bases' object")
|
|
|
|
selector_bases: dict[int, int] = {}
|
|
for raw_selector, raw_base in raw_bases.items():
|
|
selector = _parse_map_integer(raw_selector, "selector")
|
|
base = _parse_map_integer(raw_base, f"base for selector 0x{selector:04X}")
|
|
selector_to_ne_segment(selector)
|
|
if not 0 <= base <= MAX_ADDRESS:
|
|
raise ValueError(f"physical base is outside the 32-bit address range: {base}")
|
|
if selector in selector_bases:
|
|
raise ValueError(f"duplicate selector in map: 0x{selector:04X}")
|
|
selector_bases[selector] = base
|
|
|
|
return program.strip(), selector_bases
|
|
|
|
|
|
def _parse_map_integer(value: Any, field_name: str) -> int:
|
|
if isinstance(value, bool):
|
|
raise ValueError(f"{field_name} must be an integer or 0x-prefixed string")
|
|
if isinstance(value, int):
|
|
return value
|
|
if isinstance(value, str):
|
|
try:
|
|
return int(value, 0)
|
|
except ValueError as error:
|
|
raise ValueError(f"{field_name} must be an integer or 0x-prefixed string") from error
|
|
raise ValueError(f"{field_name} must be an integer or 0x-prefixed string")
|
|
|
|
|
|
def translate_address(
|
|
value: str,
|
|
selector_bases: dict[int, int],
|
|
address_format: str = "auto",
|
|
) -> AddressTranslation:
|
|
segment_field, offset = parse_ghidra_address(value)
|
|
|
|
if address_format == "auto":
|
|
address_format = "selector" if segment_field >= NE_SELECTOR_BASE else "ne-segment"
|
|
|
|
if address_format == "selector":
|
|
selector = segment_field
|
|
ne_segment = selector_to_ne_segment(selector)
|
|
elif address_format == "ne-segment":
|
|
ne_segment = segment_field
|
|
selector = ne_segment_to_selector(ne_segment)
|
|
else:
|
|
raise ValueError(f"unsupported address format: {address_format}")
|
|
|
|
if selector not in selector_bases:
|
|
raise ValueError(
|
|
f"no verified physical base for selector 0x{selector:04X} "
|
|
f"(NE segment 0x{ne_segment:02X})"
|
|
)
|
|
|
|
physical_address = selector_bases[selector] + offset
|
|
if physical_address > MAX_ADDRESS:
|
|
raise ValueError(f"translated address exceeds the 32-bit range: {value}")
|
|
|
|
return AddressTranslation(
|
|
source=value,
|
|
selector=selector,
|
|
ne_segment=ne_segment,
|
|
segment_offset=offset,
|
|
physical_address=physical_address,
|
|
)
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(
|
|
description="Translate Crusader Ghidra segment:offset addresses to DOSBox physical memory offsets."
|
|
)
|
|
parser.add_argument("--base-map", required=True, type=Path, help="JSON file of verified runtime selector bases")
|
|
parser.add_argument(
|
|
"--format",
|
|
choices=("auto", "ne-segment", "selector"),
|
|
default="auto",
|
|
help="address prefix format; auto treats values below 0x1000 as NE segment indexes",
|
|
)
|
|
parser.add_argument("--json", action="store_true", help="print JSON output")
|
|
parser.add_argument("addresses", nargs="+", help="Ghidra addresses such as 0007:28ce or 1480:712c")
|
|
return parser
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
args = build_parser().parse_args(argv)
|
|
try:
|
|
program, selector_bases = load_selector_bases(args.base_map)
|
|
translations = [
|
|
translate_address(address, selector_bases, args.format)
|
|
for address in args.addresses
|
|
]
|
|
except ValueError as error:
|
|
print(f"error: {error}", file=sys.stderr)
|
|
return 2
|
|
|
|
if args.json:
|
|
payload = {
|
|
"program": program,
|
|
"translations": [asdict(translation) for translation in translations],
|
|
}
|
|
print(json.dumps(payload, indent=2))
|
|
else:
|
|
for translation in translations:
|
|
print(
|
|
f"{translation.source} "
|
|
f"selector=0x{translation.selector:04X} "
|
|
f"ne_segment=0x{translation.ne_segment:02X} "
|
|
f"offset=0x{translation.segment_offset:04X} "
|
|
f"physical=0x{translation.physical_address:08X} "
|
|
f"mcp_offset={translation.physical_address}"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main()) |