xref: /aosp_15_r20/build/bazel/scripts/difftool/diffs/nm.py (revision 7594170e27e0732bc44b93d1440d87a54b6ffe7c)
1#!/usr/bin/env python3
2#
3# Copyright (C) 2022 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#   http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License."""
16
17import pathlib
18import re
19import subprocess
20from diffs.diff import Diff, ExtractInfo
21
22class _Symbol:
23    """Data structure to hold a symbol as specified by nm
24
25    Equality of symbols is based on their name and attributes.
26
27    The self._addr property is excluded from comparisons in this class
28    because the location of a symbol in one binary is not a useful
29    difference from another binary.
30    """
31    def __init__(self, name, addr, attr):
32        self.name = name
33        self._addr = addr
34        self.attr = attr
35    def __hash__(self):
36        return (self.name + self.attr).__hash__()
37    def __eq__(self, other):
38        return self.name == other.name and self.attr == other.attr
39    def __repr__(self):
40        return f"{self.name}{{{self.attr}}}"
41
42
43class NmSymbolDiff(Diff):
44  """Compares symbols the symbol table output by nm
45
46  Example nm output:
47  0000000000000140 t GetExceptionSummary
48                   U ExpandableStringInitialize
49                   U ExpandableStringRelease
50  0000000000000cf0 T jniCreateString
51
52  The first column is the address of the symbol in the binary, the second
53  column is an attribute associated with the symbol (see man nm for details),
54  and the last column is the demangled symbol name.
55  """
56  _nm_re = re.compile(r"^(\w+)?\s+([a-zA-Z])\s(\S+)$")
57
58  def __init__(self, tool: ExtractInfo, tool_name: str):
59    self.tool = tool
60    self.tool_name = tool_name
61
62  def _read_symbols(nm_output):
63      symbols = set()
64      for line in nm_output:
65          match = NmSymbolDiff._nm_re.match(line)
66          if match:
67              symbols.add(_Symbol(match.group(3), match.group(1), match.group(2)))
68      return symbols
69
70  def diff(self, left_path: pathlib.Path, right_path: pathlib.Path) -> list[str]:
71    left_nm = subprocess.run(["nm", left_path], capture_output=True, encoding="utf-8").stdout.splitlines()
72    right_nm = subprocess.run(["nm", right_path], capture_output=True, encoding="utf-8").stdout.splitlines()
73    left_symbols = NmSymbolDiff._read_symbols(left_nm)
74    right_symbols = NmSymbolDiff._read_symbols(right_nm)
75
76    left_only = []
77    for s in left_symbols:
78        if s not in right_symbols:
79          left_only.append(s)
80    right_only = []
81    for s in right_symbols:
82        if s not in left_symbols:
83          right_only.append(s)
84
85    errors = []
86    if left_only:
87      errors.append(f"symbols in {left_path} not in {right_path}:")
88      errors.extend("\t" + str(s) for s in left_only)
89    if right_only:
90      errors.append(f"symbols in {right_path} not in {left_path}:")
91      errors.extend("\t" + str(s) for s in right_only)
92
93    return errors
94