diff --git a/CHANGES.md b/CHANGES.md index a676aae..c0af7b7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -12,6 +12,7 @@ - Do not treat a target idle at its prompt as a busy loop. - Add the console over a NuttX netdev console (UDP or CAN ISO-TP) for sim, QEMU and real hardware (``netdev`` device). +- Detect the "_" C symbol prefix of RH850 and RX images. ## 0.0.3 diff --git a/src/ntfc/lib/elf/elf_parser.py b/src/ntfc/lib/elf/elf_parser.py index da6f2f4..3508e53 100644 --- a/src/ntfc/lib/elf/elf_parser.py +++ b/src/ntfc/lib/elf/elf_parser.py @@ -27,7 +27,7 @@ import os import re import subprocess -from typing import List, Pattern, Union +from typing import Dict, List, Pattern, Set, Tuple, Union class Symbol: @@ -43,6 +43,8 @@ def __init__(self, name: str, address: str = "", symbol_type: str = ""): class ElfParser: """ELF file parser for extracting symbols.""" + _PREFIX_ANCHORS = {"nx_start", "main"} + def __init__(self, elf_path: str): """Initialize ELF file parser.""" if not os.path.exists(elf_path) or not self._is_elf_file(elf_path): @@ -78,7 +80,7 @@ def _extract_symbols(self) -> List[Symbol]: check=True, ) - symbols = [] + entries: List[Tuple[str, Dict[str, str]]] = [] for line in result.stdout.splitlines(): line = line.strip() if not line: @@ -87,15 +89,20 @@ def _extract_symbols(self) -> List[Symbol]: parts = line.split() if len(parts) >= 3: address, symbol_type, name = parts[0], parts[1], parts[2] - symbols.append(Symbol(name, address, symbol_type)) - elif len(parts) >= 2: # pragma: no cover + kwargs = {"address": address, "symbol_type": symbol_type} + entries.append((name, kwargs)) + elif len(parts) >= 2: symbol_type, name = parts[0], parts[1] - symbols.append(Symbol(name, symbol_type=symbol_type)) + entries.append((name, {"symbol_type": symbol_type})) elif len(parts) == 1: # pragma: no cover name = parts[0] - symbols.append(Symbol(name)) + entries.append((name, {})) - return symbols + prefix = self._label_prefix({name for name, _ in entries}) + return [ + Symbol(name.removeprefix(prefix), **kwargs) + for name, kwargs in entries + ] except subprocess.CalledProcessError as e: # pragma: no cover logging.error( @@ -107,6 +114,14 @@ def _extract_symbols(self) -> List[Symbol]: logging.error(f"Unexpected error parsing ELF symbols: {e}") return [] + @classmethod + def _label_prefix(cls, names: Set[str]) -> str: + """Return "_" if the target prefixes C symbols, else "".""" + prefixed = {"_" + a for a in cls._PREFIX_ANCHORS} + if not names.isdisjoint(cls._PREFIX_ANCHORS): + return "" + return "_" if not names.isdisjoint(prefixed) else "" + def get_symbols_by_pattern( self, prefix: str = "", suffix: str = "" ) -> List[Symbol]: diff --git a/tests/lib/test_elfparser.py b/tests/lib/test_elfparser.py index b56e306..d42761c 100644 --- a/tests/lib/test_elfparser.py +++ b/tests/lib/test_elfparser.py @@ -46,3 +46,112 @@ def test_lib_elf_parser(): with pytest.raises(ValueError): _ = a.has_symbol(b"xx") + + +def _nm_output(mocker, lines): + result = mocker.Mock() + result.stdout = "\n".join(lines) + return mocker.patch( + "ntfc.lib.elf.elf_parser.subprocess.run", return_value=result + ) + + +def test_lib_elf_parser_label_prefix(mocker): + _nm_output( + mocker, + [ + "00000100 T _nx_start", + "00000200 T _ostest_main", + "00000300 T __start", + "00000400 T rh850_vector", + ], + ) + + a = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert a.has_symbol("nx_start") is True + assert a.has_symbol("ostest_main") is True + assert a.has_symbol("_ostest_main") is False + assert a.has_symbol("_start") is True + assert a.has_symbol("rh850_vector") is True + assert a.get_symbols_by_pattern("ostest", "main")[0].name == "ostest_main" + + +def test_lib_elf_parser_no_label_prefix(mocker): + _nm_output( + mocker, + [ + "00000100 T nx_start", + "00000200 T _ostest_main", + ], + ) + + a = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert a.has_symbol("_ostest_main") is True + assert a.has_symbol("ostest_main") is False + + _nm_output(mocker, ["00000100 T _foo_main"]) + + b = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert b.has_symbol("_foo_main") is True + + +def test_lib_elf_parser_label_prefix_app_binary(mocker): + # kernel-mode application binaries have main, not nx_start + _nm_output( + mocker, + [ + "00000100 T _main", + "00000200 T _hello_main", + ], + ) + + a = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert a.has_symbol("main") is True + assert a.has_symbol("hello_main") is True + assert a.has_symbol(re.compile("^hello")) is True + + +def _fields(parser): + return [(s.name, s.address, s.type) for s in parser.symbols] + + +def test_lib_elf_parser_short_lines(mocker): + _nm_output( + mocker, + [ + "00000100 T nx_start", + "T _hello_main", + "_ostest_main", + ], + ) + + a = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert _fields(a) == [ + ("nx_start", "00000100", "T"), + ("_hello_main", "", "T"), + ("_ostest_main", "", ""), + ] + + +def test_lib_elf_parser_short_lines_label_prefix(mocker): + _nm_output( + mocker, + [ + "00000100 T _nx_start", + "T _hello_main", + "_ostest_main", + ], + ) + + a = ElfParser("./tests/resources/nuttx/sim/nuttx") + + assert _fields(a) == [ + ("nx_start", "00000100", "T"), + ("hello_main", "", "T"), + ("ostest_main", "", ""), + ] diff --git a/tests/test_coreconfig.py b/tests/test_coreconfig.py index 9eb666e..cbb8075 100644 --- a/tests/test_coreconfig.py +++ b/tests/test_coreconfig.py @@ -260,3 +260,23 @@ def test_core_config_prompt(): p = CoreConfig(conf) # Should load from kv_config file or return None assert p.prompt == "nsh> " + + +def test_core_config_cmd_check_label_prefix(mocker): + result = mocker.Mock() + result.stdout = "00000100 T _nx_start\n00000200 T _ostest_main\n" + mocker.patch("ntfc.lib.elf.elf_parser.subprocess.run", return_value=result) + + conf = { + "name": "dummy", + "device": "qemu", + "elf_path": "./tests/resources/nuttx/sim/nuttx", + "conf_path": "./tests/resources/nuttx/sim/kv_config", + } + + p = CoreConfig(conf) + + assert p.cmd_check("ostest_main") is True + assert p.cmd_check("missing|ostest_main") is True + assert p.cmd_check("ostest.*") is True + assert p.cmd_check("_ostest_main") is False