check_callgraph.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. #!/usr/bin/env python
  2. #
  3. # Based on cally.py (https://github.com/chaudron/cally/), Copyright 2018, Eelco Chaudron
  4. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  5. # SPDX-License-Identifier: Apache-2.0
  6. import argparse
  7. import os
  8. import re
  9. from functools import partial
  10. from typing import BinaryIO, Callable, Dict, Generator, List, Optional, Tuple
  11. import elftools
  12. from elftools.elf import elffile
  13. FUNCTION_REGEX = re.compile(
  14. r'^;; Function (?P<mangle>.*)\s+\((?P<function>\S+)(,.*)?\).*$'
  15. )
  16. CALL_REGEX = re.compile(r'^.*\(call.*"(?P<target>.*)".*$')
  17. SYMBOL_REF_REGEX = re.compile(r'^.*\(symbol_ref[^()]*\("(?P<target>.*)"\).*$')
  18. class RtlFunction(object):
  19. def __init__(self, name: str, rtl_filename: str, tu_filename: str) -> None:
  20. self.name = name
  21. self.rtl_filename = rtl_filename
  22. self.tu_filename = tu_filename
  23. self.calls: List[str] = list()
  24. self.refs: List[str] = list()
  25. self.sym = None
  26. class SectionAddressRange(object):
  27. def __init__(self, name: str, addr: int, size: int) -> None:
  28. self.name = name
  29. self.low = addr
  30. self.high = addr + size
  31. def __str__(self) -> str:
  32. return '{}: 0x{:08x} - 0x{:08x}'.format(self.name, self.low, self.high)
  33. def contains_address(self, addr: int) -> bool:
  34. return self.low <= addr < self.high
  35. TARGET_SECTIONS: Dict[str, List[SectionAddressRange]] = {
  36. 'esp32': [
  37. SectionAddressRange('.rom.text', 0x40000000, 0x70000),
  38. SectionAddressRange('.rom.rodata', 0x3ff96000, 0x9018)
  39. ],
  40. 'esp32s2': [
  41. SectionAddressRange('.rom.text', 0x40000000, 0x1bed0),
  42. SectionAddressRange('.rom.rodata', 0x3ffac600, 0x392c)
  43. ],
  44. 'esp32s3': [
  45. SectionAddressRange('.rom.text', 0x40000000, 0x568d0),
  46. SectionAddressRange('.rom.rodata', 0x3ff071c0, 0x8e30)
  47. ]
  48. }
  49. class Symbol(object):
  50. def __init__(self, name: str, addr: int, local: bool, filename: Optional[str], section: Optional[str]) -> None:
  51. self.name = name
  52. self.addr = addr
  53. self.local = local
  54. self.filename = filename
  55. self.section = section
  56. self.refers_to: List[Symbol] = list()
  57. self.referred_from: List[Symbol] = list()
  58. def __str__(self) -> str:
  59. return '{} @0x{:08x} [{}]{} {}'.format(
  60. self.name,
  61. self.addr,
  62. self.section or 'unknown',
  63. ' (local)' if self.local else '',
  64. self.filename
  65. )
  66. class Reference(object):
  67. def __init__(self, from_sym: Symbol, to_sym: Symbol) -> None:
  68. self.from_sym = from_sym
  69. self.to_sym = to_sym
  70. def __str__(self) -> str:
  71. return '{} @0x{:08x} ({}) -> {} @0x{:08x} ({})'.format(
  72. self.from_sym.name,
  73. self.from_sym.addr,
  74. self.from_sym.section,
  75. self.to_sym.name,
  76. self.to_sym.addr,
  77. self.to_sym.section
  78. )
  79. class ElfInfo(object):
  80. def __init__(self, elf_file: BinaryIO) -> None:
  81. self.elf_file = elf_file
  82. self.elf_obj = elffile.ELFFile(self.elf_file)
  83. self.section_ranges = self._load_sections()
  84. self.symbols = self._load_symbols()
  85. def _load_symbols(self) -> List[Symbol]:
  86. symbols = []
  87. for s in self.elf_obj.iter_sections():
  88. if not isinstance(s, elftools.elf.sections.SymbolTableSection):
  89. continue
  90. filename = None
  91. for sym in s.iter_symbols():
  92. sym_type = sym.entry['st_info']['type']
  93. if sym_type == 'STT_FILE':
  94. filename = sym.name
  95. if sym_type in ['STT_NOTYPE', 'STT_FUNC', 'STT_OBJECT']:
  96. local = sym.entry['st_info']['bind'] == 'STB_LOCAL'
  97. addr = sym.entry['st_value']
  98. symbols.append(
  99. Symbol(
  100. sym.name,
  101. addr,
  102. local,
  103. filename if local else None,
  104. self.section_for_addr(addr),
  105. )
  106. )
  107. return symbols
  108. def _load_sections(self) -> List[SectionAddressRange]:
  109. result = []
  110. for segment in self.elf_obj.iter_segments():
  111. if segment['p_type'] == 'PT_LOAD':
  112. for section in self.elf_obj.iter_sections():
  113. if not segment.section_in_segment(section):
  114. continue
  115. result.append(
  116. SectionAddressRange(
  117. section.name, section['sh_addr'], section['sh_size']
  118. )
  119. )
  120. target = os.environ.get('IDF_TARGET')
  121. if target in TARGET_SECTIONS:
  122. result += TARGET_SECTIONS[target]
  123. return result
  124. def symbols_by_name(self, name: str) -> List['Symbol']:
  125. res = []
  126. for sym in self.symbols:
  127. if sym.name == name:
  128. res.append(sym)
  129. return res
  130. def section_for_addr(self, sym_addr: int) -> Optional[str]:
  131. for sar in self.section_ranges:
  132. if sar.contains_address(sym_addr):
  133. return sar.name
  134. return None
  135. def load_rtl_file(rtl_filename: str, tu_filename: str, functions: List[RtlFunction]) -> None:
  136. last_function: Optional[RtlFunction] = None
  137. for line in open(rtl_filename):
  138. # Find function definition
  139. match = re.match(FUNCTION_REGEX, line)
  140. if match:
  141. function_name = match.group('function')
  142. last_function = RtlFunction(function_name, rtl_filename, tu_filename)
  143. functions.append(last_function)
  144. continue
  145. if last_function:
  146. # Find direct function calls
  147. match = re.match(CALL_REGEX, line)
  148. if match:
  149. target = match.group('target')
  150. if target not in last_function.calls:
  151. last_function.calls.append(target)
  152. continue
  153. # Find symbol references
  154. match = re.match(SYMBOL_REF_REGEX, line)
  155. if match:
  156. target = match.group('target')
  157. if target not in last_function.refs:
  158. last_function.refs.append(target)
  159. continue
  160. def rtl_filename_matches_sym_filename(rtl_filename: str, symbol_filename: str) -> bool:
  161. # Symbol file names (from ELF debug info) are short source file names, without path: "cpu_start.c".
  162. # RTL file names are paths relative to the build directory, e.g.:
  163. # "build/esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/cpu_start.c.234r.expand"
  164. #
  165. # The check below may give a false positive if there are two files with the same name in
  166. # different directories. This doesn't seem to happen in IDF now, but if it does happen,
  167. # an assert in find_symbol_by_rtl_func should catch this.
  168. #
  169. # If this becomes and issue, consider also loading the .map file and using it to figure out
  170. # which object file was used as the source of each symbol. Names of the object files and RTL files
  171. # should be much easier to match.
  172. return os.path.basename(rtl_filename).startswith(symbol_filename)
  173. class SymbolNotFound(RuntimeError):
  174. pass
  175. def find_symbol_by_name(name: str, elfinfo: ElfInfo, local_func_matcher: Callable[[Symbol], bool]) -> Optional[Symbol]:
  176. """
  177. Find an ELF symbol for the given name.
  178. local_func_matcher is a callback function which checks is the candidate local symbol is suitable.
  179. """
  180. syms = elfinfo.symbols_by_name(name)
  181. if not syms:
  182. return None
  183. if len(syms) == 1:
  184. return syms[0]
  185. else:
  186. # There are multiple symbols with a given name. Find the best fit.
  187. local_candidate = None
  188. global_candidate = None
  189. for sym in syms:
  190. if not sym.local:
  191. assert not global_candidate # can't have two global symbols with the same name
  192. global_candidate = sym
  193. elif local_func_matcher(sym):
  194. assert not local_candidate # can't have two symbols with the same name in a single file
  195. local_candidate = sym
  196. # If two symbols with the same name are defined, a global and a local one,
  197. # prefer the local symbol as the reference target.
  198. return local_candidate or global_candidate
  199. def match_local_source_func(rtl_filename: str, sym: Symbol) -> bool:
  200. """
  201. Helper for match_rtl_funcs_to_symbols, checks if local symbol sym is a good candidate for the
  202. reference source (caller), based on the RTL file name.
  203. """
  204. assert sym.filename # should be set for local functions
  205. return rtl_filename_matches_sym_filename(rtl_filename, sym.filename)
  206. def match_local_target_func(rtl_filename: str, sym_from: Symbol, sym: Symbol) -> bool:
  207. """
  208. Helper for match_rtl_funcs_to_symbols, checks if local symbol sym is a good candidate for the
  209. reference target (callee or referenced data), based on RTL filename of the source symbol
  210. and the source symbol itself.
  211. """
  212. assert sym.filename # should be set for local functions
  213. if sym_from.local:
  214. # local symbol referencing another local symbol
  215. return sym_from.filename == sym.filename
  216. else:
  217. # global symbol referencing a local symbol;
  218. # source filename is not known, use RTL filename as a hint
  219. return rtl_filename_matches_sym_filename(rtl_filename, sym.filename)
  220. def match_rtl_funcs_to_symbols(rtl_functions: List[RtlFunction], elfinfo: ElfInfo) -> Tuple[List[Symbol], List[Reference]]:
  221. symbols: List[Symbol] = []
  222. refs: List[Reference] = []
  223. # General idea:
  224. # - iterate over RTL functions.
  225. # - for each RTL function, find the corresponding symbol
  226. # - iterate over the functions and variables referenced from this RTL function
  227. # - find symbols corresponding to the references
  228. # - record every pair (sym_from, sym_to) as a Reference object
  229. for source_rtl_func in rtl_functions:
  230. maybe_sym_from = find_symbol_by_name(source_rtl_func.name, elfinfo, partial(match_local_source_func, source_rtl_func.rtl_filename))
  231. if maybe_sym_from is None:
  232. # RTL references a symbol, but the symbol is not defined in the generated object file.
  233. # This means that the symbol was likely removed (or not included) at link time.
  234. # There is nothing we can do to check section placement in this case.
  235. continue
  236. sym_from = maybe_sym_from
  237. if sym_from not in symbols:
  238. symbols.append(sym_from)
  239. for target_rtl_func_name in source_rtl_func.calls + source_rtl_func.refs:
  240. if '*.LC' in target_rtl_func_name: # skip local labels
  241. continue
  242. maybe_sym_to = find_symbol_by_name(target_rtl_func_name, elfinfo, partial(match_local_target_func, source_rtl_func.rtl_filename, sym_from))
  243. if not maybe_sym_to:
  244. # This may happen for a extern reference in the RTL file, if the reference was later removed
  245. # by one of the optimization passes, and the external definition got garbage-collected.
  246. # TODO: consider adding some sanity check that we are here not because of some bug in
  247. # find_symbol_by_name?..
  248. continue
  249. sym_to = maybe_sym_to
  250. sym_from.refers_to.append(sym_to)
  251. sym_to.referred_from.append(sym_from)
  252. refs.append(Reference(sym_from, sym_to))
  253. if sym_to not in symbols:
  254. symbols.append(sym_to)
  255. return symbols, refs
  256. def get_symbols_and_refs(rtl_list: List[str], elf_file: BinaryIO) -> Tuple[List[Symbol], List[Reference]]:
  257. elfinfo = ElfInfo(elf_file)
  258. rtl_functions: List[RtlFunction] = []
  259. for file_name in rtl_list:
  260. load_rtl_file(file_name, file_name, rtl_functions)
  261. return match_rtl_funcs_to_symbols(rtl_functions, elfinfo)
  262. def list_refs_from_to_sections(refs: List[Reference], from_sections: List[str], to_sections: List[str]) -> int:
  263. found = 0
  264. for ref in refs:
  265. if (not from_sections or ref.from_sym.section in from_sections) and \
  266. (not to_sections or ref.to_sym.section in to_sections):
  267. print(str(ref))
  268. found += 1
  269. return found
  270. def find_files_recursive(root_path: str, ext: str) -> Generator[str, None, None]:
  271. for root, _, files in os.walk(root_path):
  272. for basename in files:
  273. if basename.endswith(ext):
  274. filename = os.path.join(root, basename)
  275. yield filename
  276. def main() -> None:
  277. parser = argparse.ArgumentParser()
  278. parser.add_argument(
  279. '--rtl-list',
  280. help='File with the list of RTL files',
  281. type=argparse.FileType('r'),
  282. )
  283. parser.add_argument(
  284. '--rtl-dir', help='Directory where to look for RTL files, recursively'
  285. )
  286. parser.add_argument(
  287. '--elf-file',
  288. required=True,
  289. help='Program ELF file',
  290. type=argparse.FileType('rb'),
  291. )
  292. action_sub = parser.add_subparsers(dest='action')
  293. find_refs_parser = action_sub.add_parser(
  294. 'find-refs',
  295. help='List the references coming from a given list of source sections'
  296. 'to a given list of target sections.',
  297. )
  298. find_refs_parser.add_argument(
  299. '--from-sections', help='comma-separated list of source sections'
  300. )
  301. find_refs_parser.add_argument(
  302. '--to-sections', help='comma-separated list of target sections'
  303. )
  304. find_refs_parser.add_argument(
  305. '--exit-code',
  306. action='store_true',
  307. help='If set, exits with non-zero code when any references found',
  308. )
  309. action_sub.add_parser(
  310. 'all-refs',
  311. help='Print the list of all references',
  312. )
  313. parser.parse_args()
  314. args = parser.parse_args()
  315. if args.rtl_list:
  316. with open(args.rtl_list, 'r') as rtl_list_file:
  317. rtl_list = [line.strip() for line in rtl_list_file]
  318. else:
  319. if not args.rtl_dir:
  320. raise RuntimeError('Either --rtl-list or --rtl-dir must be specified')
  321. rtl_list = list(find_files_recursive(args.rtl_dir, '.expand'))
  322. if not rtl_list:
  323. raise RuntimeError('No RTL files specified')
  324. _, refs = get_symbols_and_refs(rtl_list, args.elf_file)
  325. if args.action == 'find-refs':
  326. from_sections = args.from_sections.split(',') if args.from_sections else []
  327. to_sections = args.to_sections.split(',') if args.to_sections else []
  328. found = list_refs_from_to_sections(
  329. refs, from_sections, to_sections
  330. )
  331. if args.exit_code and found:
  332. raise SystemExit(1)
  333. elif args.action == 'all-refs':
  334. for r in refs:
  335. print(str(r))
  336. if __name__ == '__main__':
  337. main()